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 // Single-precision floating-point arithmetic.
175 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
176 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
177 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
178 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
180 // Double-precision floating-point arithmetic.
181 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
182 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
183 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
184 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
186 // Single-precision comparisons.
187 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
188 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
189 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
190 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
191 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
192 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
193 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
194 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
196 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
197 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
198 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
199 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
200 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
205 // Double-precision comparisons.
206 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
207 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
208 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
209 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
210 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
211 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
212 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
213 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
215 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
216 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
217 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
218 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
219 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
224 // Floating-point to integer conversions.
225 // i64 conversions are done via library routines even when generating VFP
226 // instructions, so use the same ones.
227 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
228 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
229 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
230 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
232 // Conversions between floating types.
233 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
234 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
236 // Integer to floating-point conversions.
237 // i64 conversions are done via library routines even when generating VFP
238 // instructions, so use the same ones.
239 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
240 // e.g., __floatunsidf vs. __floatunssidfvfp.
241 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
242 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
243 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
244 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
248 // These libcalls are not available in 32-bit.
249 setLibcallName(RTLIB::SHL_I128, nullptr);
250 setLibcallName(RTLIB::SRL_I128, nullptr);
251 setLibcallName(RTLIB::SRA_I128, nullptr);
253 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
254 !Subtarget->isTargetWindows()) {
255 static const struct {
256 const RTLIB::Libcall Op;
257 const char * const Name;
258 const CallingConv::ID CC;
259 const ISD::CondCode Cond;
261 // Double-precision floating-point arithmetic helper functions
262 // RTABI chapter 4.1.2, Table 2
263 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268 // Double-precision floating-point comparison helper functions
269 // RTABI chapter 4.1.2, Table 3
270 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
271 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
272 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
273 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
274 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
276 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
277 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
279 // Single-precision floating-point arithmetic helper functions
280 // RTABI chapter 4.1.2, Table 4
281 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286 // Single-precision floating-point comparison helper functions
287 // RTABI chapter 4.1.2, Table 5
288 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
289 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
290 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
291 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
292 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
294 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
295 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
297 // Floating-point to integer conversions.
298 // RTABI chapter 4.1.2, Table 6
299 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 // Conversions between floating types.
309 // RTABI chapter 4.1.2, Table 7
310 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 // Integer to floating-point conversions.
315 // RTABI chapter 4.1.2, Table 8
316 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 // Long long helper functions
326 // RTABI chapter 4.2, Table 9
327 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 // Integer division functions
333 // RTABI chapter 4.3.1
334 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 // RTABI chapter 4.3.4
345 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350 for (const auto &LC : LibraryCalls) {
351 setLibcallName(LC.Op, LC.Name);
352 setLibcallCallingConv(LC.Op, LC.CC);
353 if (LC.Cond != ISD::SETCC_INVALID)
354 setCmpLibcallCC(LC.Op, LC.Cond);
358 if (Subtarget->isTargetWindows()) {
359 static const struct {
360 const RTLIB::Libcall Op;
361 const char * const Name;
362 const CallingConv::ID CC;
364 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
366 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
371 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
374 for (const auto &LC : LibraryCalls) {
375 setLibcallName(LC.Op, LC.Name);
376 setLibcallCallingConv(LC.Op, LC.CC);
380 // Use divmod compiler-rt calls for iOS 5.0 and later.
381 if (Subtarget->getTargetTriple().isiOS() &&
382 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
383 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
384 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
387 // The half <-> float conversion functions are always soft-float, but are
388 // needed for some targets which use a hard-float calling convention by
390 if (Subtarget->isAAPCS_ABI()) {
391 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
393 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
395 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
396 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
397 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
400 if (Subtarget->isThumb1Only())
401 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
403 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
404 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
405 !Subtarget->isThumb1Only()) {
406 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
407 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
410 for (MVT VT : MVT::vector_valuetypes()) {
411 for (MVT InnerVT : MVT::vector_valuetypes()) {
412 setTruncStoreAction(VT, InnerVT, Expand);
413 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
414 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
415 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
418 setOperationAction(ISD::MULHS, VT, Expand);
419 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
420 setOperationAction(ISD::MULHU, VT, Expand);
421 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
423 setOperationAction(ISD::BSWAP, VT, Expand);
426 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
427 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
429 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
430 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
432 if (Subtarget->hasNEON()) {
433 addDRTypeForNEON(MVT::v2f32);
434 addDRTypeForNEON(MVT::v8i8);
435 addDRTypeForNEON(MVT::v4i16);
436 addDRTypeForNEON(MVT::v2i32);
437 addDRTypeForNEON(MVT::v1i64);
439 addQRTypeForNEON(MVT::v4f32);
440 addQRTypeForNEON(MVT::v2f64);
441 addQRTypeForNEON(MVT::v16i8);
442 addQRTypeForNEON(MVT::v8i16);
443 addQRTypeForNEON(MVT::v4i32);
444 addQRTypeForNEON(MVT::v2i64);
446 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
447 // neither Neon nor VFP support any arithmetic operations on it.
448 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
449 // supported for v4f32.
450 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
451 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
452 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
453 // FIXME: Code duplication: FDIV and FREM are expanded always, see
454 // ARMTargetLowering::addTypeForNEON method for details.
455 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
456 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
457 // FIXME: Create unittest.
458 // In another words, find a way when "copysign" appears in DAG with vector
460 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
461 // FIXME: Code duplication: SETCC has custom operation action, see
462 // ARMTargetLowering::addTypeForNEON method for details.
463 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
464 // FIXME: Create unittest for FNEG and for FABS.
465 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
466 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
467 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
468 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
469 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
470 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
471 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
472 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
473 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
474 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
475 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
476 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
477 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
478 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
479 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
480 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
481 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
482 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
483 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
485 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
486 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
487 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
488 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
489 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
490 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
491 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
492 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
493 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
494 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
495 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
496 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
497 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
498 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
499 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
501 // Mark v2f32 intrinsics.
502 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
503 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
504 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
505 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
506 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
507 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
508 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
509 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
510 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
511 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
512 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
513 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
514 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
515 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
516 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
518 // Neon does not support some operations on v1i64 and v2i64 types.
519 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
520 // Custom handling for some quad-vector types to detect VMULL.
521 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
522 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
523 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
524 // Custom handling for some vector types to avoid expensive expansions
525 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
526 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
527 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
528 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
529 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
530 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
531 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
532 // a destination type that is wider than the source, and nor does
533 // it have a FP_TO_[SU]INT instruction with a narrower destination than
535 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
536 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
537 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
538 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
540 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
541 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
543 // NEON does not have single instruction CTPOP for vectors with element
544 // types wider than 8-bits. However, custom lowering can leverage the
545 // v8i8/v16i8 vcnt instruction.
546 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
547 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
548 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
549 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
551 // NEON does not have single instruction CTTZ for vectors.
552 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
553 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
554 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
555 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
557 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
558 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
559 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
560 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
563 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
564 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
565 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
567 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
568 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
569 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
570 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
572 // NEON only has FMA instructions as of VFP4.
573 if (!Subtarget->hasVFP4()) {
574 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
575 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
578 setTargetDAGCombine(ISD::INTRINSIC_VOID);
579 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
580 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
581 setTargetDAGCombine(ISD::SHL);
582 setTargetDAGCombine(ISD::SRL);
583 setTargetDAGCombine(ISD::SRA);
584 setTargetDAGCombine(ISD::SIGN_EXTEND);
585 setTargetDAGCombine(ISD::ZERO_EXTEND);
586 setTargetDAGCombine(ISD::ANY_EXTEND);
587 setTargetDAGCombine(ISD::SELECT_CC);
588 setTargetDAGCombine(ISD::BUILD_VECTOR);
589 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
590 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
591 setTargetDAGCombine(ISD::STORE);
592 setTargetDAGCombine(ISD::FP_TO_SINT);
593 setTargetDAGCombine(ISD::FP_TO_UINT);
594 setTargetDAGCombine(ISD::FDIV);
595 setTargetDAGCombine(ISD::LOAD);
597 // It is legal to extload from v4i8 to v4i16 or v4i32.
598 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
600 for (MVT VT : MVT::integer_vector_valuetypes()) {
601 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
602 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
603 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
608 // ARM and Thumb2 support UMLAL/SMLAL.
609 if (!Subtarget->isThumb1Only())
610 setTargetDAGCombine(ISD::ADDC);
612 if (Subtarget->isFPOnlySP()) {
613 // When targetting a floating-point unit with only single-precision
614 // operations, f64 is legal for the few double-precision instructions which
615 // are present However, no double-precision operations other than moves,
616 // loads and stores are provided by the hardware.
617 setOperationAction(ISD::FADD, MVT::f64, Expand);
618 setOperationAction(ISD::FSUB, MVT::f64, Expand);
619 setOperationAction(ISD::FMUL, MVT::f64, Expand);
620 setOperationAction(ISD::FMA, MVT::f64, Expand);
621 setOperationAction(ISD::FDIV, MVT::f64, Expand);
622 setOperationAction(ISD::FREM, MVT::f64, Expand);
623 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
624 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
625 setOperationAction(ISD::FNEG, MVT::f64, Expand);
626 setOperationAction(ISD::FABS, MVT::f64, Expand);
627 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
628 setOperationAction(ISD::FSIN, MVT::f64, Expand);
629 setOperationAction(ISD::FCOS, MVT::f64, Expand);
630 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
631 setOperationAction(ISD::FPOW, MVT::f64, Expand);
632 setOperationAction(ISD::FLOG, MVT::f64, Expand);
633 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
634 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
635 setOperationAction(ISD::FEXP, MVT::f64, Expand);
636 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
637 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
638 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
639 setOperationAction(ISD::FRINT, MVT::f64, Expand);
640 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
641 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
642 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
643 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
644 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
645 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
646 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
647 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
648 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
649 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
652 computeRegisterProperties(Subtarget->getRegisterInfo());
654 // ARM does not have floating-point extending loads.
655 for (MVT VT : MVT::fp_valuetypes()) {
656 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
657 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
660 // ... or truncating stores
661 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
662 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
663 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
665 // ARM does not have i1 sign extending load.
666 for (MVT VT : MVT::integer_valuetypes())
667 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
669 // ARM supports all 4 flavors of integer indexed load / store.
670 if (!Subtarget->isThumb1Only()) {
671 for (unsigned im = (unsigned)ISD::PRE_INC;
672 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
673 setIndexedLoadAction(im, MVT::i1, Legal);
674 setIndexedLoadAction(im, MVT::i8, Legal);
675 setIndexedLoadAction(im, MVT::i16, Legal);
676 setIndexedLoadAction(im, MVT::i32, Legal);
677 setIndexedStoreAction(im, MVT::i1, Legal);
678 setIndexedStoreAction(im, MVT::i8, Legal);
679 setIndexedStoreAction(im, MVT::i16, Legal);
680 setIndexedStoreAction(im, MVT::i32, Legal);
684 setOperationAction(ISD::SADDO, MVT::i32, Custom);
685 setOperationAction(ISD::UADDO, MVT::i32, Custom);
686 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
687 setOperationAction(ISD::USUBO, MVT::i32, Custom);
689 // i64 operation support.
690 setOperationAction(ISD::MUL, MVT::i64, Expand);
691 setOperationAction(ISD::MULHU, MVT::i32, Expand);
692 if (Subtarget->isThumb1Only()) {
693 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
694 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
696 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
697 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
698 setOperationAction(ISD::MULHS, MVT::i32, Expand);
700 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
701 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
702 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
703 setOperationAction(ISD::SRL, MVT::i64, Custom);
704 setOperationAction(ISD::SRA, MVT::i64, Custom);
706 if (!Subtarget->isThumb1Only()) {
707 // FIXME: We should do this for Thumb1 as well.
708 setOperationAction(ISD::ADDC, MVT::i32, Custom);
709 setOperationAction(ISD::ADDE, MVT::i32, Custom);
710 setOperationAction(ISD::SUBC, MVT::i32, Custom);
711 setOperationAction(ISD::SUBE, MVT::i32, Custom);
714 // ARM does not have ROTL.
715 setOperationAction(ISD::ROTL, MVT::i32, Expand);
716 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
717 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
718 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
719 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
721 // These just redirect to CTTZ and CTLZ on ARM.
722 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
723 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
725 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
727 // Only ARMv6 has BSWAP.
728 if (!Subtarget->hasV6Ops())
729 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
731 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
732 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
733 // These are expanded into libcalls if the cpu doesn't have HW divider.
734 setOperationAction(ISD::SDIV, MVT::i32, Expand);
735 setOperationAction(ISD::UDIV, MVT::i32, Expand);
738 // FIXME: Also set divmod for SREM on EABI
739 setOperationAction(ISD::SREM, MVT::i32, Expand);
740 setOperationAction(ISD::UREM, MVT::i32, Expand);
741 // Register based DivRem for AEABI (RTABI 4.2)
742 if (Subtarget->isTargetAEABI()) {
743 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
744 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
745 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
746 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
747 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
748 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
749 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
750 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
752 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
753 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
754 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
755 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
756 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
757 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
758 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
759 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
761 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
762 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
764 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
765 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
768 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
769 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
770 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
771 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
772 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
774 setOperationAction(ISD::TRAP, MVT::Other, Legal);
776 // Use the default implementation.
777 setOperationAction(ISD::VASTART, MVT::Other, Custom);
778 setOperationAction(ISD::VAARG, MVT::Other, Expand);
779 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
780 setOperationAction(ISD::VAEND, MVT::Other, Expand);
781 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
782 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
784 if (!Subtarget->isTargetMachO()) {
785 // Non-MachO platforms may return values in these registers via the
786 // personality function.
787 setExceptionPointerRegister(ARM::R0);
788 setExceptionSelectorRegister(ARM::R1);
791 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
792 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
794 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
796 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
797 // the default expansion. If we are targeting a single threaded system,
798 // then set them all for expand so we can lower them later into their
800 if (TM.Options.ThreadModel == ThreadModel::Single)
801 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
802 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
803 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
804 // to ldrex/strex loops already.
805 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
807 // On v8, we have particularly efficient implementations of atomic fences
808 // if they can be combined with nearby atomic loads and stores.
809 if (!Subtarget->hasV8Ops()) {
810 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
811 setInsertFencesForAtomic(true);
814 // If there's anything we can use as a barrier, go through custom lowering
816 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
817 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
819 // Set them all for expansion, which will force libcalls.
820 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
821 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
822 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
823 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
824 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
825 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
826 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
827 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
828 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
829 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
830 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
831 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
832 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
833 // Unordered/Monotonic case.
834 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
835 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
838 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
840 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
841 if (!Subtarget->hasV6Ops()) {
842 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
843 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
845 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
847 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
848 !Subtarget->isThumb1Only()) {
849 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
850 // iff target supports vfp2.
851 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
852 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
855 // We want to custom lower some of our intrinsics.
856 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
857 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
858 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
859 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
860 if (Subtarget->isTargetDarwin())
861 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
863 setOperationAction(ISD::SETCC, MVT::i32, Expand);
864 setOperationAction(ISD::SETCC, MVT::f32, Expand);
865 setOperationAction(ISD::SETCC, MVT::f64, Expand);
866 setOperationAction(ISD::SELECT, MVT::i32, Custom);
867 setOperationAction(ISD::SELECT, MVT::f32, Custom);
868 setOperationAction(ISD::SELECT, MVT::f64, Custom);
869 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
870 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
871 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
873 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
874 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
875 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
876 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
877 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
879 // We don't support sin/cos/fmod/copysign/pow
880 setOperationAction(ISD::FSIN, MVT::f64, Expand);
881 setOperationAction(ISD::FSIN, MVT::f32, Expand);
882 setOperationAction(ISD::FCOS, MVT::f32, Expand);
883 setOperationAction(ISD::FCOS, MVT::f64, Expand);
884 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
885 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
886 setOperationAction(ISD::FREM, MVT::f64, Expand);
887 setOperationAction(ISD::FREM, MVT::f32, Expand);
888 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
889 !Subtarget->isThumb1Only()) {
890 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
891 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
893 setOperationAction(ISD::FPOW, MVT::f64, Expand);
894 setOperationAction(ISD::FPOW, MVT::f32, Expand);
896 if (!Subtarget->hasVFP4()) {
897 setOperationAction(ISD::FMA, MVT::f64, Expand);
898 setOperationAction(ISD::FMA, MVT::f32, Expand);
901 // Various VFP goodness
902 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
903 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
904 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
905 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
906 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
909 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
910 if (!Subtarget->hasFP16()) {
911 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
912 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
916 // Combine sin / cos into one node or libcall if possible.
917 if (Subtarget->hasSinCos()) {
918 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
919 setLibcallName(RTLIB::SINCOS_F64, "sincos");
920 if (Subtarget->getTargetTriple().isiOS()) {
921 // For iOS, we don't want to the normal expansion of a libcall to
922 // sincos. We want to issue a libcall to __sincos_stret.
923 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
924 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
928 // FP-ARMv8 implements a lot of rounding-like FP operations.
929 if (Subtarget->hasFPARMv8()) {
930 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
931 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
932 setOperationAction(ISD::FROUND, MVT::f32, Legal);
933 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
934 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
935 setOperationAction(ISD::FRINT, MVT::f32, Legal);
936 if (!Subtarget->isFPOnlySP()) {
937 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
938 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
939 setOperationAction(ISD::FROUND, MVT::f64, Legal);
940 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
941 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
942 setOperationAction(ISD::FRINT, MVT::f64, Legal);
945 // We have target-specific dag combine patterns for the following nodes:
946 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
947 setTargetDAGCombine(ISD::ADD);
948 setTargetDAGCombine(ISD::SUB);
949 setTargetDAGCombine(ISD::MUL);
950 setTargetDAGCombine(ISD::AND);
951 setTargetDAGCombine(ISD::OR);
952 setTargetDAGCombine(ISD::XOR);
954 if (Subtarget->hasV6Ops())
955 setTargetDAGCombine(ISD::SRL);
957 setStackPointerRegisterToSaveRestore(ARM::SP);
959 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
960 !Subtarget->hasVFP2())
961 setSchedulingPreference(Sched::RegPressure);
963 setSchedulingPreference(Sched::Hybrid);
965 //// temporary - rewrite interface to use type
966 MaxStoresPerMemset = 8;
967 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
968 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
969 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
970 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
971 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
973 // On ARM arguments smaller than 4 bytes are extended, so all arguments
974 // are at least 4 bytes aligned.
975 setMinStackArgumentAlignment(4);
977 // Prefer likely predicted branches to selects on out-of-order cores.
978 PredictableSelectIsExpensive = Subtarget->isLikeA9();
980 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
983 bool ARMTargetLowering::useSoftFloat() const {
984 return Subtarget->useSoftFloat();
987 // FIXME: It might make sense to define the representative register class as the
988 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
989 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
990 // SPR's representative would be DPR_VFP2. This should work well if register
991 // pressure tracking were modified such that a register use would increment the
992 // pressure of the register class's representative and all of it's super
993 // classes' representatives transitively. We have not implemented this because
994 // of the difficulty prior to coalescing of modeling operand register classes
995 // due to the common occurrence of cross class copies and subregister insertions
997 std::pair<const TargetRegisterClass *, uint8_t>
998 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1000 const TargetRegisterClass *RRC = nullptr;
1002 switch (VT.SimpleTy) {
1004 return TargetLowering::findRepresentativeClass(TRI, VT);
1005 // Use DPR as representative register class for all floating point
1006 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1007 // the cost is 1 for both f32 and f64.
1008 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1009 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1010 RRC = &ARM::DPRRegClass;
1011 // When NEON is used for SP, only half of the register file is available
1012 // because operations that define both SP and DP results will be constrained
1013 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1014 // coalescing by double-counting the SP regs. See the FIXME above.
1015 if (Subtarget->useNEONForSinglePrecisionFP())
1018 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1019 case MVT::v4f32: case MVT::v2f64:
1020 RRC = &ARM::DPRRegClass;
1024 RRC = &ARM::DPRRegClass;
1028 RRC = &ARM::DPRRegClass;
1032 return std::make_pair(RRC, Cost);
1035 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1036 switch ((ARMISD::NodeType)Opcode) {
1037 case ARMISD::FIRST_NUMBER: break;
1038 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1039 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1040 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1041 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1042 case ARMISD::CALL: return "ARMISD::CALL";
1043 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1044 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1045 case ARMISD::tCALL: return "ARMISD::tCALL";
1046 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1047 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1048 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1049 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1050 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1051 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1052 case ARMISD::CMP: return "ARMISD::CMP";
1053 case ARMISD::CMN: return "ARMISD::CMN";
1054 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1055 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1056 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1057 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1058 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1060 case ARMISD::CMOV: return "ARMISD::CMOV";
1062 case ARMISD::RBIT: return "ARMISD::RBIT";
1064 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1065 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1066 case ARMISD::RRX: return "ARMISD::RRX";
1068 case ARMISD::ADDC: return "ARMISD::ADDC";
1069 case ARMISD::ADDE: return "ARMISD::ADDE";
1070 case ARMISD::SUBC: return "ARMISD::SUBC";
1071 case ARMISD::SUBE: return "ARMISD::SUBE";
1073 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1074 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1076 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1077 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1078 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1080 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1082 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1084 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1086 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1088 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1090 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1092 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1093 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1094 case ARMISD::VCGE: return "ARMISD::VCGE";
1095 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1096 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1097 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1098 case ARMISD::VCGT: return "ARMISD::VCGT";
1099 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1100 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1101 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1102 case ARMISD::VTST: return "ARMISD::VTST";
1104 case ARMISD::VSHL: return "ARMISD::VSHL";
1105 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1106 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1107 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1108 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1109 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1110 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1111 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1112 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1113 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1114 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1115 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1116 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1117 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1118 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1119 case ARMISD::VSLI: return "ARMISD::VSLI";
1120 case ARMISD::VSRI: return "ARMISD::VSRI";
1121 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1122 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1123 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1124 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1125 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1126 case ARMISD::VDUP: return "ARMISD::VDUP";
1127 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1128 case ARMISD::VEXT: return "ARMISD::VEXT";
1129 case ARMISD::VREV64: return "ARMISD::VREV64";
1130 case ARMISD::VREV32: return "ARMISD::VREV32";
1131 case ARMISD::VREV16: return "ARMISD::VREV16";
1132 case ARMISD::VZIP: return "ARMISD::VZIP";
1133 case ARMISD::VUZP: return "ARMISD::VUZP";
1134 case ARMISD::VTRN: return "ARMISD::VTRN";
1135 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1136 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1137 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1138 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1139 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1140 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1141 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1142 case ARMISD::FMAX: return "ARMISD::FMAX";
1143 case ARMISD::FMIN: return "ARMISD::FMIN";
1144 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1145 case ARMISD::VMINNM: return "ARMISD::VMIN";
1146 case ARMISD::BFI: return "ARMISD::BFI";
1147 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1148 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1149 case ARMISD::VBSL: return "ARMISD::VBSL";
1150 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1151 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1152 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1153 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1154 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1155 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1156 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1157 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1158 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1159 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1160 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1161 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1162 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1163 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1164 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1165 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1166 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1167 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1168 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1169 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1174 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1177 return getPointerTy(DL);
1178 return VT.changeVectorElementTypeToInteger();
1181 /// getRegClassFor - Return the register class that should be used for the
1182 /// specified value type.
1183 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1184 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1185 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1186 // load / store 4 to 8 consecutive D registers.
1187 if (Subtarget->hasNEON()) {
1188 if (VT == MVT::v4i64)
1189 return &ARM::QQPRRegClass;
1190 if (VT == MVT::v8i64)
1191 return &ARM::QQQQPRRegClass;
1193 return TargetLowering::getRegClassFor(VT);
1196 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1197 // source/dest is aligned and the copy size is large enough. We therefore want
1198 // to align such objects passed to memory intrinsics.
1199 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1200 unsigned &PrefAlign) const {
1201 if (!isa<MemIntrinsic>(CI))
1204 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1205 // cycle faster than 4-byte aligned LDM.
1206 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1210 // Create a fast isel object.
1212 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1213 const TargetLibraryInfo *libInfo) const {
1214 return ARM::createFastISel(funcInfo, libInfo);
1217 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1218 unsigned NumVals = N->getNumValues();
1220 return Sched::RegPressure;
1222 for (unsigned i = 0; i != NumVals; ++i) {
1223 EVT VT = N->getValueType(i);
1224 if (VT == MVT::Glue || VT == MVT::Other)
1226 if (VT.isFloatingPoint() || VT.isVector())
1230 if (!N->isMachineOpcode())
1231 return Sched::RegPressure;
1233 // Load are scheduled for latency even if there instruction itinerary
1234 // is not available.
1235 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1236 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1238 if (MCID.getNumDefs() == 0)
1239 return Sched::RegPressure;
1240 if (!Itins->isEmpty() &&
1241 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1244 return Sched::RegPressure;
1247 //===----------------------------------------------------------------------===//
1249 //===----------------------------------------------------------------------===//
1251 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1252 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1254 default: llvm_unreachable("Unknown condition code!");
1255 case ISD::SETNE: return ARMCC::NE;
1256 case ISD::SETEQ: return ARMCC::EQ;
1257 case ISD::SETGT: return ARMCC::GT;
1258 case ISD::SETGE: return ARMCC::GE;
1259 case ISD::SETLT: return ARMCC::LT;
1260 case ISD::SETLE: return ARMCC::LE;
1261 case ISD::SETUGT: return ARMCC::HI;
1262 case ISD::SETUGE: return ARMCC::HS;
1263 case ISD::SETULT: return ARMCC::LO;
1264 case ISD::SETULE: return ARMCC::LS;
1268 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1269 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1270 ARMCC::CondCodes &CondCode2) {
1271 CondCode2 = ARMCC::AL;
1273 default: llvm_unreachable("Unknown FP condition!");
1275 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1277 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1279 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1280 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1281 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1282 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1283 case ISD::SETO: CondCode = ARMCC::VC; break;
1284 case ISD::SETUO: CondCode = ARMCC::VS; break;
1285 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1286 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1287 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1289 case ISD::SETULT: CondCode = ARMCC::LT; break;
1291 case ISD::SETULE: CondCode = ARMCC::LE; break;
1293 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1297 //===----------------------------------------------------------------------===//
1298 // Calling Convention Implementation
1299 //===----------------------------------------------------------------------===//
1301 #include "ARMGenCallingConv.inc"
1303 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1304 /// account presence of floating point hardware and calling convention
1305 /// limitations, such as support for variadic functions.
1307 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1308 bool isVarArg) const {
1311 llvm_unreachable("Unsupported calling convention");
1312 case CallingConv::ARM_AAPCS:
1313 case CallingConv::ARM_APCS:
1314 case CallingConv::GHC:
1316 case CallingConv::ARM_AAPCS_VFP:
1317 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1318 case CallingConv::C:
1319 if (!Subtarget->isAAPCS_ABI())
1320 return CallingConv::ARM_APCS;
1321 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1322 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1324 return CallingConv::ARM_AAPCS_VFP;
1326 return CallingConv::ARM_AAPCS;
1327 case CallingConv::Fast:
1328 if (!Subtarget->isAAPCS_ABI()) {
1329 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1330 return CallingConv::Fast;
1331 return CallingConv::ARM_APCS;
1332 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1333 return CallingConv::ARM_AAPCS_VFP;
1335 return CallingConv::ARM_AAPCS;
1339 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1340 /// CallingConvention.
1341 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1343 bool isVarArg) const {
1344 switch (getEffectiveCallingConv(CC, isVarArg)) {
1346 llvm_unreachable("Unsupported calling convention");
1347 case CallingConv::ARM_APCS:
1348 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1349 case CallingConv::ARM_AAPCS:
1350 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1351 case CallingConv::ARM_AAPCS_VFP:
1352 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1353 case CallingConv::Fast:
1354 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1355 case CallingConv::GHC:
1356 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1360 /// LowerCallResult - Lower the result values of a call into the
1361 /// appropriate copies out of appropriate physical registers.
1363 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1364 CallingConv::ID CallConv, bool isVarArg,
1365 const SmallVectorImpl<ISD::InputArg> &Ins,
1366 SDLoc dl, SelectionDAG &DAG,
1367 SmallVectorImpl<SDValue> &InVals,
1368 bool isThisReturn, SDValue ThisVal) const {
1370 // Assign locations to each value returned by this call.
1371 SmallVector<CCValAssign, 16> RVLocs;
1372 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1373 *DAG.getContext(), Call);
1374 CCInfo.AnalyzeCallResult(Ins,
1375 CCAssignFnForNode(CallConv, /* Return*/ true,
1378 // Copy all of the result registers out of their specified physreg.
1379 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1380 CCValAssign VA = RVLocs[i];
1382 // Pass 'this' value directly from the argument to return value, to avoid
1383 // reg unit interference
1384 if (i == 0 && isThisReturn) {
1385 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1386 "unexpected return calling convention register assignment");
1387 InVals.push_back(ThisVal);
1392 if (VA.needsCustom()) {
1393 // Handle f64 or half of a v2f64.
1394 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1396 Chain = Lo.getValue(1);
1397 InFlag = Lo.getValue(2);
1398 VA = RVLocs[++i]; // skip ahead to next loc
1399 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1401 Chain = Hi.getValue(1);
1402 InFlag = Hi.getValue(2);
1403 if (!Subtarget->isLittle())
1405 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1407 if (VA.getLocVT() == MVT::v2f64) {
1408 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1409 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1410 DAG.getConstant(0, dl, MVT::i32));
1412 VA = RVLocs[++i]; // skip ahead to next loc
1413 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1414 Chain = Lo.getValue(1);
1415 InFlag = Lo.getValue(2);
1416 VA = RVLocs[++i]; // skip ahead to next loc
1417 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1418 Chain = Hi.getValue(1);
1419 InFlag = Hi.getValue(2);
1420 if (!Subtarget->isLittle())
1422 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1423 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1424 DAG.getConstant(1, dl, MVT::i32));
1427 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1429 Chain = Val.getValue(1);
1430 InFlag = Val.getValue(2);
1433 switch (VA.getLocInfo()) {
1434 default: llvm_unreachable("Unknown loc info!");
1435 case CCValAssign::Full: break;
1436 case CCValAssign::BCvt:
1437 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1441 InVals.push_back(Val);
1447 /// LowerMemOpCallTo - Store the argument to the stack.
1449 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1450 SDValue StackPtr, SDValue Arg,
1451 SDLoc dl, SelectionDAG &DAG,
1452 const CCValAssign &VA,
1453 ISD::ArgFlagsTy Flags) const {
1454 unsigned LocMemOffset = VA.getLocMemOffset();
1455 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1456 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1458 return DAG.getStore(Chain, dl, Arg, PtrOff,
1459 MachinePointerInfo::getStack(LocMemOffset),
1463 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1464 SDValue Chain, SDValue &Arg,
1465 RegsToPassVector &RegsToPass,
1466 CCValAssign &VA, CCValAssign &NextVA,
1468 SmallVectorImpl<SDValue> &MemOpChains,
1469 ISD::ArgFlagsTy Flags) const {
1471 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1472 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1473 unsigned id = Subtarget->isLittle() ? 0 : 1;
1474 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1476 if (NextVA.isRegLoc())
1477 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1479 assert(NextVA.isMemLoc());
1480 if (!StackPtr.getNode())
1481 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1482 getPointerTy(DAG.getDataLayout()));
1484 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1490 /// LowerCall - Lowering a call into a callseq_start <-
1491 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1494 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1495 SmallVectorImpl<SDValue> &InVals) const {
1496 SelectionDAG &DAG = CLI.DAG;
1498 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1499 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1500 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1501 SDValue Chain = CLI.Chain;
1502 SDValue Callee = CLI.Callee;
1503 bool &isTailCall = CLI.IsTailCall;
1504 CallingConv::ID CallConv = CLI.CallConv;
1505 bool doesNotRet = CLI.DoesNotReturn;
1506 bool isVarArg = CLI.IsVarArg;
1508 MachineFunction &MF = DAG.getMachineFunction();
1509 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1510 bool isThisReturn = false;
1511 bool isSibCall = false;
1512 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1514 // Disable tail calls if they're not supported.
1515 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1519 // Check if it's really possible to do a tail call.
1520 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1521 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1522 Outs, OutVals, Ins, DAG);
1523 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1524 report_fatal_error("failed to perform tail call elimination on a call "
1525 "site marked musttail");
1526 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1527 // detected sibcalls.
1534 // Analyze operands of the call, assigning locations to each operand.
1535 SmallVector<CCValAssign, 16> ArgLocs;
1536 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1537 *DAG.getContext(), Call);
1538 CCInfo.AnalyzeCallOperands(Outs,
1539 CCAssignFnForNode(CallConv, /* Return*/ false,
1542 // Get a count of how many bytes are to be pushed on the stack.
1543 unsigned NumBytes = CCInfo.getNextStackOffset();
1545 // For tail calls, memory operands are available in our caller's stack.
1549 // Adjust the stack pointer for the new arguments...
1550 // These operations are automatically eliminated by the prolog/epilog pass
1552 Chain = DAG.getCALLSEQ_START(Chain,
1553 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1556 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1558 RegsToPassVector RegsToPass;
1559 SmallVector<SDValue, 8> MemOpChains;
1561 // Walk the register/memloc assignments, inserting copies/loads. In the case
1562 // of tail call optimization, arguments are handled later.
1563 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1565 ++i, ++realArgIdx) {
1566 CCValAssign &VA = ArgLocs[i];
1567 SDValue Arg = OutVals[realArgIdx];
1568 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1569 bool isByVal = Flags.isByVal();
1571 // Promote the value if needed.
1572 switch (VA.getLocInfo()) {
1573 default: llvm_unreachable("Unknown loc info!");
1574 case CCValAssign::Full: break;
1575 case CCValAssign::SExt:
1576 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1578 case CCValAssign::ZExt:
1579 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1581 case CCValAssign::AExt:
1582 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1584 case CCValAssign::BCvt:
1585 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1589 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1590 if (VA.needsCustom()) {
1591 if (VA.getLocVT() == MVT::v2f64) {
1592 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1593 DAG.getConstant(0, dl, MVT::i32));
1594 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1595 DAG.getConstant(1, dl, MVT::i32));
1597 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1598 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1600 VA = ArgLocs[++i]; // skip ahead to next loc
1601 if (VA.isRegLoc()) {
1602 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1603 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1605 assert(VA.isMemLoc());
1607 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1608 dl, DAG, VA, Flags));
1611 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1612 StackPtr, MemOpChains, Flags);
1614 } else if (VA.isRegLoc()) {
1615 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1616 assert(VA.getLocVT() == MVT::i32 &&
1617 "unexpected calling convention register assignment");
1618 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1619 "unexpected use of 'returned'");
1620 isThisReturn = true;
1622 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1623 } else if (isByVal) {
1624 assert(VA.isMemLoc());
1625 unsigned offset = 0;
1627 // True if this byval aggregate will be split between registers
1629 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1630 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1632 if (CurByValIdx < ByValArgsCount) {
1634 unsigned RegBegin, RegEnd;
1635 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1638 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1640 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1641 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1642 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1643 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1644 MachinePointerInfo(),
1645 false, false, false,
1646 DAG.InferPtrAlignment(AddArg));
1647 MemOpChains.push_back(Load.getValue(1));
1648 RegsToPass.push_back(std::make_pair(j, Load));
1651 // If parameter size outsides register area, "offset" value
1652 // helps us to calculate stack slot for remained part properly.
1653 offset = RegEnd - RegBegin;
1655 CCInfo.nextInRegsParam();
1658 if (Flags.getByValSize() > 4*offset) {
1659 auto PtrVT = getPointerTy(DAG.getDataLayout());
1660 unsigned LocMemOffset = VA.getLocMemOffset();
1661 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1662 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1663 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1664 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1665 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1667 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1670 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1671 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1672 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1675 } else if (!isSibCall) {
1676 assert(VA.isMemLoc());
1678 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1679 dl, DAG, VA, Flags));
1683 if (!MemOpChains.empty())
1684 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1686 // Build a sequence of copy-to-reg nodes chained together with token chain
1687 // and flag operands which copy the outgoing args into the appropriate regs.
1689 // Tail call byval lowering might overwrite argument registers so in case of
1690 // tail call optimization the copies to registers are lowered later.
1692 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1693 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1694 RegsToPass[i].second, InFlag);
1695 InFlag = Chain.getValue(1);
1698 // For tail calls lower the arguments to the 'real' stack slot.
1700 // Force all the incoming stack arguments to be loaded from the stack
1701 // before any new outgoing arguments are stored to the stack, because the
1702 // outgoing stack slots may alias the incoming argument stack slots, and
1703 // the alias isn't otherwise explicit. This is slightly more conservative
1704 // than necessary, because it means that each store effectively depends
1705 // on every argument instead of just those arguments it would clobber.
1707 // Do not flag preceding copytoreg stuff together with the following stuff.
1709 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1710 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1711 RegsToPass[i].second, InFlag);
1712 InFlag = Chain.getValue(1);
1717 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1718 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1719 // node so that legalize doesn't hack it.
1720 bool isDirect = false;
1721 bool isARMFunc = false;
1722 bool isLocalARMFunc = false;
1723 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1724 auto PtrVt = getPointerTy(DAG.getDataLayout());
1726 if (Subtarget->genLongCalls()) {
1727 assert((Subtarget->isTargetWindows() ||
1728 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1729 "long-calls with non-static relocation model!");
1730 // Handle a global address or an external symbol. If it's not one of
1731 // those, the target's already in a register, so we don't need to do
1733 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1734 const GlobalValue *GV = G->getGlobal();
1735 // Create a constant pool entry for the callee address
1736 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1737 ARMConstantPoolValue *CPV =
1738 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1740 // Get the address of the callee into a register
1741 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1742 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1743 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1744 MachinePointerInfo::getConstantPool(), false, false,
1746 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1747 const char *Sym = S->getSymbol();
1749 // Create a constant pool entry for the callee address
1750 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1751 ARMConstantPoolValue *CPV =
1752 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1753 ARMPCLabelIndex, 0);
1754 // Get the address of the callee into a register
1755 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1756 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1757 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1758 MachinePointerInfo::getConstantPool(), false, false,
1761 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1762 const GlobalValue *GV = G->getGlobal();
1764 bool isDef = GV->isStrongDefinitionForLinker();
1765 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1766 getTargetMachine().getRelocationModel() != Reloc::Static;
1767 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1768 // ARM call to a local ARM function is predicable.
1769 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1770 // tBX takes a register source operand.
1771 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1772 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1773 Callee = DAG.getNode(
1774 ARMISD::WrapperPIC, dl, PtrVt,
1775 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1776 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1777 MachinePointerInfo::getGOT(), false, false, true, 0);
1778 } else if (Subtarget->isTargetCOFF()) {
1779 assert(Subtarget->isTargetWindows() &&
1780 "Windows is the only supported COFF target");
1781 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1782 ? ARMII::MO_DLLIMPORT
1783 : ARMII::MO_NO_FLAG;
1785 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1786 if (GV->hasDLLImportStorageClass())
1788 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1789 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1790 MachinePointerInfo::getGOT(), false, false, false, 0);
1792 // On ELF targets for PIC code, direct calls should go through the PLT
1793 unsigned OpFlags = 0;
1794 if (Subtarget->isTargetELF() &&
1795 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1796 OpFlags = ARMII::MO_PLT;
1797 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1799 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1801 bool isStub = Subtarget->isTargetMachO() &&
1802 getTargetMachine().getRelocationModel() != Reloc::Static;
1803 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1804 // tBX takes a register source operand.
1805 const char *Sym = S->getSymbol();
1806 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1807 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1808 ARMConstantPoolValue *CPV =
1809 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1810 ARMPCLabelIndex, 4);
1811 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1812 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1813 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1814 MachinePointerInfo::getConstantPool(), false, false,
1816 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1817 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1819 unsigned OpFlags = 0;
1820 // On ELF targets for PIC code, direct calls should go through the PLT
1821 if (Subtarget->isTargetELF() &&
1822 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1823 OpFlags = ARMII::MO_PLT;
1824 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1828 // FIXME: handle tail calls differently.
1830 bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1831 if (Subtarget->isThumb()) {
1832 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1833 CallOpc = ARMISD::CALL_NOLINK;
1835 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1837 if (!isDirect && !Subtarget->hasV5TOps())
1838 CallOpc = ARMISD::CALL_NOLINK;
1839 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1840 // Emit regular call when code size is the priority
1842 // "mov lr, pc; b _foo" to avoid confusing the RSP
1843 CallOpc = ARMISD::CALL_NOLINK;
1845 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1848 std::vector<SDValue> Ops;
1849 Ops.push_back(Chain);
1850 Ops.push_back(Callee);
1852 // Add argument registers to the end of the list so that they are known live
1854 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1855 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1856 RegsToPass[i].second.getValueType()));
1858 // Add a register mask operand representing the call-preserved registers.
1860 const uint32_t *Mask;
1861 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1863 // For 'this' returns, use the R0-preserving mask if applicable
1864 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1866 // Set isThisReturn to false if the calling convention is not one that
1867 // allows 'returned' to be modeled in this way, so LowerCallResult does
1868 // not try to pass 'this' straight through
1869 isThisReturn = false;
1870 Mask = ARI->getCallPreservedMask(MF, CallConv);
1873 Mask = ARI->getCallPreservedMask(MF, CallConv);
1875 assert(Mask && "Missing call preserved mask for calling convention");
1876 Ops.push_back(DAG.getRegisterMask(Mask));
1879 if (InFlag.getNode())
1880 Ops.push_back(InFlag);
1882 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1884 MF.getFrameInfo()->setHasTailCall();
1885 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1888 // Returns a chain and a flag for retval copy to use.
1889 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1890 InFlag = Chain.getValue(1);
1892 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1893 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1895 InFlag = Chain.getValue(1);
1897 // Handle result values, copying them out of physregs into vregs that we
1899 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1900 InVals, isThisReturn,
1901 isThisReturn ? OutVals[0] : SDValue());
1904 /// HandleByVal - Every parameter *after* a byval parameter is passed
1905 /// on the stack. Remember the next parameter register to allocate,
1906 /// and then confiscate the rest of the parameter registers to insure
1908 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1909 unsigned Align) const {
1910 assert((State->getCallOrPrologue() == Prologue ||
1911 State->getCallOrPrologue() == Call) &&
1912 "unhandled ParmContext");
1914 // Byval (as with any stack) slots are always at least 4 byte aligned.
1915 Align = std::max(Align, 4U);
1917 unsigned Reg = State->AllocateReg(GPRArgRegs);
1921 unsigned AlignInRegs = Align / 4;
1922 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1923 for (unsigned i = 0; i < Waste; ++i)
1924 Reg = State->AllocateReg(GPRArgRegs);
1929 unsigned Excess = 4 * (ARM::R4 - Reg);
1931 // Special case when NSAA != SP and parameter size greater than size of
1932 // all remained GPR regs. In that case we can't split parameter, we must
1933 // send it to stack. We also must set NCRN to R4, so waste all
1934 // remained registers.
1935 const unsigned NSAAOffset = State->getNextStackOffset();
1936 if (NSAAOffset != 0 && Size > Excess) {
1937 while (State->AllocateReg(GPRArgRegs))
1942 // First register for byval parameter is the first register that wasn't
1943 // allocated before this method call, so it would be "reg".
1944 // If parameter is small enough to be saved in range [reg, r4), then
1945 // the end (first after last) register would be reg + param-size-in-regs,
1946 // else parameter would be splitted between registers and stack,
1947 // end register would be r4 in this case.
1948 unsigned ByValRegBegin = Reg;
1949 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1950 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1951 // Note, first register is allocated in the beginning of function already,
1952 // allocate remained amount of registers we need.
1953 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1954 State->AllocateReg(GPRArgRegs);
1955 // A byval parameter that is split between registers and memory needs its
1956 // size truncated here.
1957 // In the case where the entire structure fits in registers, we set the
1958 // size in memory to zero.
1959 Size = std::max<int>(Size - Excess, 0);
1962 /// MatchingStackOffset - Return true if the given stack call argument is
1963 /// already available in the same position (relatively) of the caller's
1964 /// incoming argument stack.
1966 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1967 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1968 const TargetInstrInfo *TII) {
1969 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1971 if (Arg.getOpcode() == ISD::CopyFromReg) {
1972 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1973 if (!TargetRegisterInfo::isVirtualRegister(VR))
1975 MachineInstr *Def = MRI->getVRegDef(VR);
1978 if (!Flags.isByVal()) {
1979 if (!TII->isLoadFromStackSlot(Def, FI))
1984 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1985 if (Flags.isByVal())
1986 // ByVal argument is passed in as a pointer but it's now being
1987 // dereferenced. e.g.
1988 // define @foo(%struct.X* %A) {
1989 // tail call @bar(%struct.X* byval %A)
1992 SDValue Ptr = Ld->getBasePtr();
1993 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1996 FI = FINode->getIndex();
2000 assert(FI != INT_MAX);
2001 if (!MFI->isFixedObjectIndex(FI))
2003 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2006 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2007 /// for tail call optimization. Targets which want to do tail call
2008 /// optimization should implement this function.
2010 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2011 CallingConv::ID CalleeCC,
2013 bool isCalleeStructRet,
2014 bool isCallerStructRet,
2015 const SmallVectorImpl<ISD::OutputArg> &Outs,
2016 const SmallVectorImpl<SDValue> &OutVals,
2017 const SmallVectorImpl<ISD::InputArg> &Ins,
2018 SelectionDAG& DAG) const {
2019 const Function *CallerF = DAG.getMachineFunction().getFunction();
2020 CallingConv::ID CallerCC = CallerF->getCallingConv();
2021 bool CCMatch = CallerCC == CalleeCC;
2023 // Look for obvious safe cases to perform tail call optimization that do not
2024 // require ABI changes. This is what gcc calls sibcall.
2026 // Do not sibcall optimize vararg calls unless the call site is not passing
2028 if (isVarArg && !Outs.empty())
2031 // Exception-handling functions need a special set of instructions to indicate
2032 // a return to the hardware. Tail-calling another function would probably
2034 if (CallerF->hasFnAttribute("interrupt"))
2037 // Also avoid sibcall optimization if either caller or callee uses struct
2038 // return semantics.
2039 if (isCalleeStructRet || isCallerStructRet)
2042 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2043 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2044 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2045 // support in the assembler and linker to be used. This would need to be
2046 // fixed to fully support tail calls in Thumb1.
2048 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2049 // LR. This means if we need to reload LR, it takes an extra instructions,
2050 // which outweighs the value of the tail call; but here we don't know yet
2051 // whether LR is going to be used. Probably the right approach is to
2052 // generate the tail call here and turn it back into CALL/RET in
2053 // emitEpilogue if LR is used.
2055 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2056 // but we need to make sure there are enough registers; the only valid
2057 // registers are the 4 used for parameters. We don't currently do this
2059 if (Subtarget->isThumb1Only())
2062 // Externally-defined functions with weak linkage should not be
2063 // tail-called on ARM when the OS does not support dynamic
2064 // pre-emption of symbols, as the AAELF spec requires normal calls
2065 // to undefined weak functions to be replaced with a NOP or jump to the
2066 // next instruction. The behaviour of branch instructions in this
2067 // situation (as used for tail calls) is implementation-defined, so we
2068 // cannot rely on the linker replacing the tail call with a return.
2069 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2070 const GlobalValue *GV = G->getGlobal();
2071 const Triple &TT = getTargetMachine().getTargetTriple();
2072 if (GV->hasExternalWeakLinkage() &&
2073 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2077 // If the calling conventions do not match, then we'd better make sure the
2078 // results are returned in the same way as what the caller expects.
2080 SmallVector<CCValAssign, 16> RVLocs1;
2081 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2082 *DAG.getContext(), Call);
2083 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2085 SmallVector<CCValAssign, 16> RVLocs2;
2086 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2087 *DAG.getContext(), Call);
2088 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2090 if (RVLocs1.size() != RVLocs2.size())
2092 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2093 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2095 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2097 if (RVLocs1[i].isRegLoc()) {
2098 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2101 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2107 // If Caller's vararg or byval argument has been split between registers and
2108 // stack, do not perform tail call, since part of the argument is in caller's
2110 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2111 getInfo<ARMFunctionInfo>();
2112 if (AFI_Caller->getArgRegsSaveSize())
2115 // If the callee takes no arguments then go on to check the results of the
2117 if (!Outs.empty()) {
2118 // Check if stack adjustment is needed. For now, do not do this if any
2119 // argument is passed on the stack.
2120 SmallVector<CCValAssign, 16> ArgLocs;
2121 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2122 *DAG.getContext(), Call);
2123 CCInfo.AnalyzeCallOperands(Outs,
2124 CCAssignFnForNode(CalleeCC, false, isVarArg));
2125 if (CCInfo.getNextStackOffset()) {
2126 MachineFunction &MF = DAG.getMachineFunction();
2128 // Check if the arguments are already laid out in the right way as
2129 // the caller's fixed stack objects.
2130 MachineFrameInfo *MFI = MF.getFrameInfo();
2131 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2132 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2133 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2135 ++i, ++realArgIdx) {
2136 CCValAssign &VA = ArgLocs[i];
2137 EVT RegVT = VA.getLocVT();
2138 SDValue Arg = OutVals[realArgIdx];
2139 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2140 if (VA.getLocInfo() == CCValAssign::Indirect)
2142 if (VA.needsCustom()) {
2143 // f64 and vector types are split into multiple registers or
2144 // register/stack-slot combinations. The types will not match
2145 // the registers; give up on memory f64 refs until we figure
2146 // out what to do about this.
2149 if (!ArgLocs[++i].isRegLoc())
2151 if (RegVT == MVT::v2f64) {
2152 if (!ArgLocs[++i].isRegLoc())
2154 if (!ArgLocs[++i].isRegLoc())
2157 } else if (!VA.isRegLoc()) {
2158 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2170 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2171 MachineFunction &MF, bool isVarArg,
2172 const SmallVectorImpl<ISD::OutputArg> &Outs,
2173 LLVMContext &Context) const {
2174 SmallVector<CCValAssign, 16> RVLocs;
2175 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2176 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2180 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2181 SDLoc DL, SelectionDAG &DAG) {
2182 const MachineFunction &MF = DAG.getMachineFunction();
2183 const Function *F = MF.getFunction();
2185 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2187 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2188 // version of the "preferred return address". These offsets affect the return
2189 // instruction if this is a return from PL1 without hypervisor extensions.
2190 // IRQ/FIQ: +4 "subs pc, lr, #4"
2191 // SWI: 0 "subs pc, lr, #0"
2192 // ABORT: +4 "subs pc, lr, #4"
2193 // UNDEF: +4/+2 "subs pc, lr, #0"
2194 // UNDEF varies depending on where the exception came from ARM or Thumb
2195 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2198 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2201 else if (IntKind == "SWI" || IntKind == "UNDEF")
2204 report_fatal_error("Unsupported interrupt attribute. If present, value "
2205 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2207 RetOps.insert(RetOps.begin() + 1,
2208 DAG.getConstant(LROffset, DL, MVT::i32, false));
2210 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2214 ARMTargetLowering::LowerReturn(SDValue Chain,
2215 CallingConv::ID CallConv, bool isVarArg,
2216 const SmallVectorImpl<ISD::OutputArg> &Outs,
2217 const SmallVectorImpl<SDValue> &OutVals,
2218 SDLoc dl, SelectionDAG &DAG) const {
2220 // CCValAssign - represent the assignment of the return value to a location.
2221 SmallVector<CCValAssign, 16> RVLocs;
2223 // CCState - Info about the registers and stack slots.
2224 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2225 *DAG.getContext(), Call);
2227 // Analyze outgoing return values.
2228 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2232 SmallVector<SDValue, 4> RetOps;
2233 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2234 bool isLittleEndian = Subtarget->isLittle();
2236 MachineFunction &MF = DAG.getMachineFunction();
2237 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2238 AFI->setReturnRegsCount(RVLocs.size());
2240 // Copy the result values into the output registers.
2241 for (unsigned i = 0, realRVLocIdx = 0;
2243 ++i, ++realRVLocIdx) {
2244 CCValAssign &VA = RVLocs[i];
2245 assert(VA.isRegLoc() && "Can only return in registers!");
2247 SDValue Arg = OutVals[realRVLocIdx];
2249 switch (VA.getLocInfo()) {
2250 default: llvm_unreachable("Unknown loc info!");
2251 case CCValAssign::Full: break;
2252 case CCValAssign::BCvt:
2253 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2257 if (VA.needsCustom()) {
2258 if (VA.getLocVT() == MVT::v2f64) {
2259 // Extract the first half and return it in two registers.
2260 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2261 DAG.getConstant(0, dl, MVT::i32));
2262 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2263 DAG.getVTList(MVT::i32, MVT::i32), Half);
2265 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2266 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2268 Flag = Chain.getValue(1);
2269 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2270 VA = RVLocs[++i]; // skip ahead to next loc
2271 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2272 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2274 Flag = Chain.getValue(1);
2275 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2276 VA = RVLocs[++i]; // skip ahead to next loc
2278 // Extract the 2nd half and fall through to handle it as an f64 value.
2279 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2280 DAG.getConstant(1, dl, MVT::i32));
2282 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2284 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2285 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2286 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2287 fmrrd.getValue(isLittleEndian ? 0 : 1),
2289 Flag = Chain.getValue(1);
2290 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2291 VA = RVLocs[++i]; // skip ahead to next loc
2292 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2293 fmrrd.getValue(isLittleEndian ? 1 : 0),
2296 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2298 // Guarantee that all emitted copies are
2299 // stuck together, avoiding something bad.
2300 Flag = Chain.getValue(1);
2301 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2304 // Update chain and glue.
2307 RetOps.push_back(Flag);
2309 // CPUs which aren't M-class use a special sequence to return from
2310 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2311 // though we use "subs pc, lr, #N").
2313 // M-class CPUs actually use a normal return sequence with a special
2314 // (hardware-provided) value in LR, so the normal code path works.
2315 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2316 !Subtarget->isMClass()) {
2317 if (Subtarget->isThumb1Only())
2318 report_fatal_error("interrupt attribute is not supported in Thumb1");
2319 return LowerInterruptReturn(RetOps, dl, DAG);
2322 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2325 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2326 if (N->getNumValues() != 1)
2328 if (!N->hasNUsesOfValue(1, 0))
2331 SDValue TCChain = Chain;
2332 SDNode *Copy = *N->use_begin();
2333 if (Copy->getOpcode() == ISD::CopyToReg) {
2334 // If the copy has a glue operand, we conservatively assume it isn't safe to
2335 // perform a tail call.
2336 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2338 TCChain = Copy->getOperand(0);
2339 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2340 SDNode *VMov = Copy;
2341 // f64 returned in a pair of GPRs.
2342 SmallPtrSet<SDNode*, 2> Copies;
2343 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2345 if (UI->getOpcode() != ISD::CopyToReg)
2349 if (Copies.size() > 2)
2352 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2354 SDValue UseChain = UI->getOperand(0);
2355 if (Copies.count(UseChain.getNode()))
2359 // We are at the top of this chain.
2360 // If the copy has a glue operand, we conservatively assume it
2361 // isn't safe to perform a tail call.
2362 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2368 } else if (Copy->getOpcode() == ISD::BITCAST) {
2369 // f32 returned in a single GPR.
2370 if (!Copy->hasOneUse())
2372 Copy = *Copy->use_begin();
2373 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2375 // If the copy has a glue operand, we conservatively assume it isn't safe to
2376 // perform a tail call.
2377 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2379 TCChain = Copy->getOperand(0);
2384 bool HasRet = false;
2385 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2387 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2388 UI->getOpcode() != ARMISD::INTRET_FLAG)
2400 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2401 if (!Subtarget->supportsTailCall())
2405 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2406 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2409 return !Subtarget->isThumb1Only();
2412 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2413 // and pass the lower and high parts through.
2414 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2416 SDValue WriteValue = Op->getOperand(2);
2418 // This function is only supposed to be called for i64 type argument.
2419 assert(WriteValue.getValueType() == MVT::i64
2420 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2422 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2423 DAG.getConstant(0, DL, MVT::i32));
2424 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2425 DAG.getConstant(1, DL, MVT::i32));
2426 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2427 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2430 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2431 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2432 // one of the above mentioned nodes. It has to be wrapped because otherwise
2433 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2434 // be used to form addressing mode. These wrapped nodes will be selected
2436 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2437 EVT PtrVT = Op.getValueType();
2438 // FIXME there is no actual debug info here
2440 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2442 if (CP->isMachineConstantPoolEntry())
2443 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2444 CP->getAlignment());
2446 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2447 CP->getAlignment());
2448 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2451 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2452 return MachineJumpTableInfo::EK_Inline;
2455 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2456 SelectionDAG &DAG) const {
2457 MachineFunction &MF = DAG.getMachineFunction();
2458 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2459 unsigned ARMPCLabelIndex = 0;
2461 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2462 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2463 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2465 if (RelocM == Reloc::Static) {
2466 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2468 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2469 ARMPCLabelIndex = AFI->createPICLabelUId();
2470 ARMConstantPoolValue *CPV =
2471 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2472 ARMCP::CPBlockAddress, PCAdj);
2473 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2475 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2476 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2477 MachinePointerInfo::getConstantPool(),
2478 false, false, false, 0);
2479 if (RelocM == Reloc::Static)
2481 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2482 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2485 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2487 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2488 SelectionDAG &DAG) const {
2490 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2491 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2492 MachineFunction &MF = DAG.getMachineFunction();
2493 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2494 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2495 ARMConstantPoolValue *CPV =
2496 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2497 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2498 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2499 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2500 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2501 MachinePointerInfo::getConstantPool(),
2502 false, false, false, 0);
2503 SDValue Chain = Argument.getValue(1);
2505 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2506 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2508 // call __tls_get_addr.
2511 Entry.Node = Argument;
2512 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2513 Args.push_back(Entry);
2515 // FIXME: is there useful debug info available here?
2516 TargetLowering::CallLoweringInfo CLI(DAG);
2517 CLI.setDebugLoc(dl).setChain(Chain)
2518 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2519 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2522 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2523 return CallResult.first;
2526 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2527 // "local exec" model.
2529 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2531 TLSModel::Model model) const {
2532 const GlobalValue *GV = GA->getGlobal();
2535 SDValue Chain = DAG.getEntryNode();
2536 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2537 // Get the Thread Pointer
2538 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2540 if (model == TLSModel::InitialExec) {
2541 MachineFunction &MF = DAG.getMachineFunction();
2542 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2543 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2544 // Initial exec model.
2545 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2546 ARMConstantPoolValue *CPV =
2547 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2548 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2550 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2551 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2552 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2553 MachinePointerInfo::getConstantPool(),
2554 false, false, false, 0);
2555 Chain = Offset.getValue(1);
2557 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2558 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2560 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2561 MachinePointerInfo::getConstantPool(),
2562 false, false, false, 0);
2565 assert(model == TLSModel::LocalExec);
2566 ARMConstantPoolValue *CPV =
2567 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2568 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2569 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2570 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2571 MachinePointerInfo::getConstantPool(),
2572 false, false, false, 0);
2575 // The address of the thread local variable is the add of the thread
2576 // pointer with the offset of the variable.
2577 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2581 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2582 // TODO: implement the "local dynamic" model
2583 assert(Subtarget->isTargetELF() &&
2584 "TLS not implemented for non-ELF targets");
2585 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2587 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2590 case TLSModel::GeneralDynamic:
2591 case TLSModel::LocalDynamic:
2592 return LowerToTLSGeneralDynamicModel(GA, DAG);
2593 case TLSModel::InitialExec:
2594 case TLSModel::LocalExec:
2595 return LowerToTLSExecModels(GA, DAG, model);
2597 llvm_unreachable("bogus TLS model");
2600 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2601 SelectionDAG &DAG) const {
2602 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2604 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2605 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2606 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2607 ARMConstantPoolValue *CPV =
2608 ARMConstantPoolConstant::Create(GV,
2609 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2610 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2611 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2612 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2614 MachinePointerInfo::getConstantPool(),
2615 false, false, false, 0);
2616 SDValue Chain = Result.getValue(1);
2617 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2618 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2620 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2621 MachinePointerInfo::getGOT(),
2622 false, false, false, 0);
2626 // If we have T2 ops, we can materialize the address directly via movt/movw
2627 // pair. This is always cheaper.
2628 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2630 // FIXME: Once remat is capable of dealing with instructions with register
2631 // operands, expand this into two nodes.
2632 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2633 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2635 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2636 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2637 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2638 MachinePointerInfo::getConstantPool(),
2639 false, false, false, 0);
2643 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2644 SelectionDAG &DAG) const {
2645 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2647 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2648 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2650 if (Subtarget->useMovt(DAG.getMachineFunction()))
2653 // FIXME: Once remat is capable of dealing with instructions with register
2654 // operands, expand this into multiple nodes
2656 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2658 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2659 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2661 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2662 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2663 MachinePointerInfo::getGOT(), false, false, false, 0);
2667 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2668 SelectionDAG &DAG) const {
2669 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2670 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2671 "Windows on ARM expects to use movw/movt");
2673 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2674 const ARMII::TOF TargetFlags =
2675 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2676 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2682 // FIXME: Once remat is capable of dealing with instructions with register
2683 // operands, expand this into two nodes.
2684 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2685 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2687 if (GV->hasDLLImportStorageClass())
2688 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2689 MachinePointerInfo::getGOT(), false, false, false, 0);
2693 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2694 SelectionDAG &DAG) const {
2695 assert(Subtarget->isTargetELF() &&
2696 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2697 MachineFunction &MF = DAG.getMachineFunction();
2698 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2699 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2700 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2702 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2703 ARMConstantPoolValue *CPV =
2704 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2705 ARMPCLabelIndex, PCAdj);
2706 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2707 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2708 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2709 MachinePointerInfo::getConstantPool(),
2710 false, false, false, 0);
2711 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2712 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2716 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2718 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2719 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2720 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2721 Op.getOperand(1), Val);
2725 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2727 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2728 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2731 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2732 SelectionDAG &DAG) const {
2734 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2739 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2740 const ARMSubtarget *Subtarget) const {
2741 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2744 default: return SDValue(); // Don't custom lower most intrinsics.
2745 case Intrinsic::arm_rbit: {
2746 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2747 "RBIT intrinsic must have i32 type!");
2748 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2750 case Intrinsic::arm_thread_pointer: {
2751 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2752 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2754 case Intrinsic::eh_sjlj_lsda: {
2755 MachineFunction &MF = DAG.getMachineFunction();
2756 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2757 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2758 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2759 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2761 unsigned PCAdj = (RelocM != Reloc::PIC_)
2762 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2763 ARMConstantPoolValue *CPV =
2764 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2765 ARMCP::CPLSDA, PCAdj);
2766 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2767 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2769 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2770 MachinePointerInfo::getConstantPool(),
2771 false, false, false, 0);
2773 if (RelocM == Reloc::PIC_) {
2774 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2775 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2779 case Intrinsic::arm_neon_vmulls:
2780 case Intrinsic::arm_neon_vmullu: {
2781 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2782 ? ARMISD::VMULLs : ARMISD::VMULLu;
2783 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2784 Op.getOperand(1), Op.getOperand(2));
2789 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2790 const ARMSubtarget *Subtarget) {
2791 // FIXME: handle "fence singlethread" more efficiently.
2793 if (!Subtarget->hasDataBarrier()) {
2794 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2795 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2797 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2798 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2799 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2800 DAG.getConstant(0, dl, MVT::i32));
2803 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2804 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2805 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2806 if (Subtarget->isMClass()) {
2807 // Only a full system barrier exists in the M-class architectures.
2808 Domain = ARM_MB::SY;
2809 } else if (Subtarget->isSwift() && Ord == Release) {
2810 // Swift happens to implement ISHST barriers in a way that's compatible with
2811 // Release semantics but weaker than ISH so we'd be fools not to use
2812 // it. Beware: other processors probably don't!
2813 Domain = ARM_MB::ISHST;
2816 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2817 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2818 DAG.getConstant(Domain, dl, MVT::i32));
2821 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2822 const ARMSubtarget *Subtarget) {
2823 // ARM pre v5TE and Thumb1 does not have preload instructions.
2824 if (!(Subtarget->isThumb2() ||
2825 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2826 // Just preserve the chain.
2827 return Op.getOperand(0);
2830 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2832 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2833 // ARMv7 with MP extension has PLDW.
2834 return Op.getOperand(0);
2836 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2837 if (Subtarget->isThumb()) {
2839 isRead = ~isRead & 1;
2840 isData = ~isData & 1;
2843 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2844 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2845 DAG.getConstant(isData, dl, MVT::i32));
2848 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2849 MachineFunction &MF = DAG.getMachineFunction();
2850 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2852 // vastart just stores the address of the VarArgsFrameIndex slot into the
2853 // memory location argument.
2855 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2856 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2857 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2858 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2859 MachinePointerInfo(SV), false, false, 0);
2863 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2864 SDValue &Root, SelectionDAG &DAG,
2866 MachineFunction &MF = DAG.getMachineFunction();
2867 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2869 const TargetRegisterClass *RC;
2870 if (AFI->isThumb1OnlyFunction())
2871 RC = &ARM::tGPRRegClass;
2873 RC = &ARM::GPRRegClass;
2875 // Transform the arguments stored in physical registers into virtual ones.
2876 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2877 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2880 if (NextVA.isMemLoc()) {
2881 MachineFrameInfo *MFI = MF.getFrameInfo();
2882 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2884 // Create load node to retrieve arguments from the stack.
2885 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2886 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2887 MachinePointerInfo::getFixedStack(FI),
2888 false, false, false, 0);
2890 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2891 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2893 if (!Subtarget->isLittle())
2894 std::swap (ArgValue, ArgValue2);
2895 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2898 // The remaining GPRs hold either the beginning of variable-argument
2899 // data, or the beginning of an aggregate passed by value (usually
2900 // byval). Either way, we allocate stack slots adjacent to the data
2901 // provided by our caller, and store the unallocated registers there.
2902 // If this is a variadic function, the va_list pointer will begin with
2903 // these values; otherwise, this reassembles a (byval) structure that
2904 // was split between registers and memory.
2905 // Return: The frame index registers were stored into.
2907 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2908 SDLoc dl, SDValue &Chain,
2909 const Value *OrigArg,
2910 unsigned InRegsParamRecordIdx,
2912 unsigned ArgSize) const {
2913 // Currently, two use-cases possible:
2914 // Case #1. Non-var-args function, and we meet first byval parameter.
2915 // Setup first unallocated register as first byval register;
2916 // eat all remained registers
2917 // (these two actions are performed by HandleByVal method).
2918 // Then, here, we initialize stack frame with
2919 // "store-reg" instructions.
2920 // Case #2. Var-args function, that doesn't contain byval parameters.
2921 // The same: eat all remained unallocated registers,
2922 // initialize stack frame.
2924 MachineFunction &MF = DAG.getMachineFunction();
2925 MachineFrameInfo *MFI = MF.getFrameInfo();
2926 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2927 unsigned RBegin, REnd;
2928 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2929 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2931 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2932 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2937 ArgOffset = -4 * (ARM::R4 - RBegin);
2939 auto PtrVT = getPointerTy(DAG.getDataLayout());
2940 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2941 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2943 SmallVector<SDValue, 4> MemOps;
2944 const TargetRegisterClass *RC =
2945 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2947 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2948 unsigned VReg = MF.addLiveIn(Reg, RC);
2949 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2951 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2952 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2953 MemOps.push_back(Store);
2954 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2957 if (!MemOps.empty())
2958 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2962 // Setup stack frame, the va_list pointer will start from.
2964 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2965 SDLoc dl, SDValue &Chain,
2967 unsigned TotalArgRegsSaveSize,
2968 bool ForceMutable) const {
2969 MachineFunction &MF = DAG.getMachineFunction();
2970 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2972 // Try to store any remaining integer argument regs
2973 // to their spots on the stack so that they may be loaded by deferencing
2974 // the result of va_next.
2975 // If there is no regs to be stored, just point address after last
2976 // argument passed via stack.
2977 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2978 CCInfo.getInRegsParamsCount(),
2979 CCInfo.getNextStackOffset(), 4);
2980 AFI->setVarArgsFrameIndex(FrameIndex);
2984 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2985 CallingConv::ID CallConv, bool isVarArg,
2986 const SmallVectorImpl<ISD::InputArg>
2988 SDLoc dl, SelectionDAG &DAG,
2989 SmallVectorImpl<SDValue> &InVals)
2991 MachineFunction &MF = DAG.getMachineFunction();
2992 MachineFrameInfo *MFI = MF.getFrameInfo();
2994 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2996 // Assign locations to all of the incoming arguments.
2997 SmallVector<CCValAssign, 16> ArgLocs;
2998 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2999 *DAG.getContext(), Prologue);
3000 CCInfo.AnalyzeFormalArguments(Ins,
3001 CCAssignFnForNode(CallConv, /* Return*/ false,
3004 SmallVector<SDValue, 16> ArgValues;
3006 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3007 unsigned CurArgIdx = 0;
3009 // Initially ArgRegsSaveSize is zero.
3010 // Then we increase this value each time we meet byval parameter.
3011 // We also increase this value in case of varargs function.
3012 AFI->setArgRegsSaveSize(0);
3014 // Calculate the amount of stack space that we need to allocate to store
3015 // byval and variadic arguments that are passed in registers.
3016 // We need to know this before we allocate the first byval or variadic
3017 // argument, as they will be allocated a stack slot below the CFA (Canonical
3018 // Frame Address, the stack pointer at entry to the function).
3019 unsigned ArgRegBegin = ARM::R4;
3020 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3021 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3024 CCValAssign &VA = ArgLocs[i];
3025 unsigned Index = VA.getValNo();
3026 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3027 if (!Flags.isByVal())
3030 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3031 unsigned RBegin, REnd;
3032 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3033 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3035 CCInfo.nextInRegsParam();
3037 CCInfo.rewindByValRegsInfo();
3039 int lastInsIndex = -1;
3040 if (isVarArg && MFI->hasVAStart()) {
3041 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3042 if (RegIdx != array_lengthof(GPRArgRegs))
3043 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3046 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3047 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3048 auto PtrVT = getPointerTy(DAG.getDataLayout());
3050 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3051 CCValAssign &VA = ArgLocs[i];
3052 if (Ins[VA.getValNo()].isOrigArg()) {
3053 std::advance(CurOrigArg,
3054 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3055 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3057 // Arguments stored in registers.
3058 if (VA.isRegLoc()) {
3059 EVT RegVT = VA.getLocVT();
3061 if (VA.needsCustom()) {
3062 // f64 and vector types are split up into multiple registers or
3063 // combinations of registers and stack slots.
3064 if (VA.getLocVT() == MVT::v2f64) {
3065 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3067 VA = ArgLocs[++i]; // skip ahead to next loc
3069 if (VA.isMemLoc()) {
3070 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3071 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3072 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3073 MachinePointerInfo::getFixedStack(FI),
3074 false, false, false, 0);
3076 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3079 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3080 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3081 ArgValue, ArgValue1,
3082 DAG.getIntPtrConstant(0, dl));
3083 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3084 ArgValue, ArgValue2,
3085 DAG.getIntPtrConstant(1, dl));
3087 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3090 const TargetRegisterClass *RC;
3092 if (RegVT == MVT::f32)
3093 RC = &ARM::SPRRegClass;
3094 else if (RegVT == MVT::f64)
3095 RC = &ARM::DPRRegClass;
3096 else if (RegVT == MVT::v2f64)
3097 RC = &ARM::QPRRegClass;
3098 else if (RegVT == MVT::i32)
3099 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3100 : &ARM::GPRRegClass;
3102 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3104 // Transform the arguments in physical registers into virtual ones.
3105 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3106 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3109 // If this is an 8 or 16-bit value, it is really passed promoted
3110 // to 32 bits. Insert an assert[sz]ext to capture this, then
3111 // truncate to the right size.
3112 switch (VA.getLocInfo()) {
3113 default: llvm_unreachable("Unknown loc info!");
3114 case CCValAssign::Full: break;
3115 case CCValAssign::BCvt:
3116 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3118 case CCValAssign::SExt:
3119 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3120 DAG.getValueType(VA.getValVT()));
3121 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3123 case CCValAssign::ZExt:
3124 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3125 DAG.getValueType(VA.getValVT()));
3126 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3130 InVals.push_back(ArgValue);
3132 } else { // VA.isRegLoc()
3135 assert(VA.isMemLoc());
3136 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3138 int index = VA.getValNo();
3140 // Some Ins[] entries become multiple ArgLoc[] entries.
3141 // Process them only once.
3142 if (index != lastInsIndex)
3144 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3145 // FIXME: For now, all byval parameter objects are marked mutable.
3146 // This can be changed with more analysis.
3147 // In case of tail call optimization mark all arguments mutable.
3148 // Since they could be overwritten by lowering of arguments in case of
3150 if (Flags.isByVal()) {
3151 assert(Ins[index].isOrigArg() &&
3152 "Byval arguments cannot be implicit");
3153 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3155 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3156 CurByValIndex, VA.getLocMemOffset(),
3157 Flags.getByValSize());
3158 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3159 CCInfo.nextInRegsParam();
3161 unsigned FIOffset = VA.getLocMemOffset();
3162 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3165 // Create load nodes to retrieve arguments from the stack.
3166 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3167 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3168 MachinePointerInfo::getFixedStack(FI),
3169 false, false, false, 0));
3171 lastInsIndex = index;
3177 if (isVarArg && MFI->hasVAStart())
3178 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3179 CCInfo.getNextStackOffset(),
3180 TotalArgRegsSaveSize);
3182 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3187 /// isFloatingPointZero - Return true if this is +0.0.
3188 static bool isFloatingPointZero(SDValue Op) {
3189 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3190 return CFP->getValueAPF().isPosZero();
3191 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3192 // Maybe this has already been legalized into the constant pool?
3193 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3194 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3195 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3196 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3197 return CFP->getValueAPF().isPosZero();
3199 } else if (Op->getOpcode() == ISD::BITCAST &&
3200 Op->getValueType(0) == MVT::f64) {
3201 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3202 // created by LowerConstantFP().
3203 SDValue BitcastOp = Op->getOperand(0);
3204 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3205 SDValue MoveOp = BitcastOp->getOperand(0);
3206 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3207 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3215 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3216 /// the given operands.
3218 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3219 SDValue &ARMcc, SelectionDAG &DAG,
3221 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3222 unsigned C = RHSC->getZExtValue();
3223 if (!isLegalICmpImmediate(C)) {
3224 // Constant does not fit, try adjusting it by one?
3229 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3230 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3231 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3236 if (C != 0 && isLegalICmpImmediate(C-1)) {
3237 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3238 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3243 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3244 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3245 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3250 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3251 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3252 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3259 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3260 ARMISD::NodeType CompareType;
3263 CompareType = ARMISD::CMP;
3268 CompareType = ARMISD::CMPZ;
3271 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3272 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3275 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3277 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3279 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3281 if (!isFloatingPointZero(RHS))
3282 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3284 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3285 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3288 /// duplicateCmp - Glue values can have only one use, so this function
3289 /// duplicates a comparison node.
3291 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3292 unsigned Opc = Cmp.getOpcode();
3294 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3295 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3297 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3298 Cmp = Cmp.getOperand(0);
3299 Opc = Cmp.getOpcode();
3300 if (Opc == ARMISD::CMPFP)
3301 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3303 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3304 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3306 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3309 std::pair<SDValue, SDValue>
3310 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3311 SDValue &ARMcc) const {
3312 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3314 SDValue Value, OverflowCmp;
3315 SDValue LHS = Op.getOperand(0);
3316 SDValue RHS = Op.getOperand(1);
3319 // FIXME: We are currently always generating CMPs because we don't support
3320 // generating CMN through the backend. This is not as good as the natural
3321 // CMP case because it causes a register dependency and cannot be folded
3324 switch (Op.getOpcode()) {
3326 llvm_unreachable("Unknown overflow instruction!");
3328 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3329 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3330 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3333 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3334 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3335 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3338 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3339 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3340 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3343 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3344 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3345 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3349 return std::make_pair(Value, OverflowCmp);
3354 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3355 // Let legalize expand this if it isn't a legal type yet.
3356 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3359 SDValue Value, OverflowCmp;
3361 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3362 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3364 // We use 0 and 1 as false and true values.
3365 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3366 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3367 EVT VT = Op.getValueType();
3369 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3370 ARMcc, CCR, OverflowCmp);
3372 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3373 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3377 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3378 SDValue Cond = Op.getOperand(0);
3379 SDValue SelectTrue = Op.getOperand(1);
3380 SDValue SelectFalse = Op.getOperand(2);
3382 unsigned Opc = Cond.getOpcode();
3384 if (Cond.getResNo() == 1 &&
3385 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3386 Opc == ISD::USUBO)) {
3387 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3390 SDValue Value, OverflowCmp;
3392 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3393 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3394 EVT VT = Op.getValueType();
3396 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3402 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3403 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3405 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3406 const ConstantSDNode *CMOVTrue =
3407 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3408 const ConstantSDNode *CMOVFalse =
3409 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3411 if (CMOVTrue && CMOVFalse) {
3412 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3413 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3417 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3419 False = SelectFalse;
3420 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3425 if (True.getNode() && False.getNode()) {
3426 EVT VT = Op.getValueType();
3427 SDValue ARMcc = Cond.getOperand(2);
3428 SDValue CCR = Cond.getOperand(3);
3429 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3430 assert(True.getValueType() == VT);
3431 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3436 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3437 // undefined bits before doing a full-word comparison with zero.
3438 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3439 DAG.getConstant(1, dl, Cond.getValueType()));
3441 return DAG.getSelectCC(dl, Cond,
3442 DAG.getConstant(0, dl, Cond.getValueType()),
3443 SelectTrue, SelectFalse, ISD::SETNE);
3446 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3447 bool &swpCmpOps, bool &swpVselOps) {
3448 // Start by selecting the GE condition code for opcodes that return true for
3450 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3452 CondCode = ARMCC::GE;
3454 // and GT for opcodes that return false for 'equality'.
3455 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3457 CondCode = ARMCC::GT;
3459 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3460 // to swap the compare operands.
3461 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3465 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3466 // If we have an unordered opcode, we need to swap the operands to the VSEL
3467 // instruction (effectively negating the condition).
3469 // This also has the effect of swapping which one of 'less' or 'greater'
3470 // returns true, so we also swap the compare operands. It also switches
3471 // whether we return true for 'equality', so we compensate by picking the
3472 // opposite condition code to our original choice.
3473 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3474 CC == ISD::SETUGT) {
3475 swpCmpOps = !swpCmpOps;
3476 swpVselOps = !swpVselOps;
3477 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3480 // 'ordered' is 'anything but unordered', so use the VS condition code and
3481 // swap the VSEL operands.
3482 if (CC == ISD::SETO) {
3483 CondCode = ARMCC::VS;
3487 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3488 // code and swap the VSEL operands.
3489 if (CC == ISD::SETUNE) {
3490 CondCode = ARMCC::EQ;
3495 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3496 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3497 SDValue Cmp, SelectionDAG &DAG) const {
3498 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3499 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3500 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3501 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3502 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3504 SDValue TrueLow = TrueVal.getValue(0);
3505 SDValue TrueHigh = TrueVal.getValue(1);
3506 SDValue FalseLow = FalseVal.getValue(0);
3507 SDValue FalseHigh = FalseVal.getValue(1);
3509 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3511 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3512 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3514 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3516 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3521 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3522 EVT VT = Op.getValueType();
3523 SDValue LHS = Op.getOperand(0);
3524 SDValue RHS = Op.getOperand(1);
3525 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3526 SDValue TrueVal = Op.getOperand(2);
3527 SDValue FalseVal = Op.getOperand(3);
3530 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3531 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3534 // If softenSetCCOperands only returned one value, we should compare it to
3536 if (!RHS.getNode()) {
3537 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3542 if (LHS.getValueType() == MVT::i32) {
3543 // Try to generate VSEL on ARMv8.
3544 // The VSEL instruction can't use all the usual ARM condition
3545 // codes: it only has two bits to select the condition code, so it's
3546 // constrained to use only GE, GT, VS and EQ.
3548 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3549 // swap the operands of the previous compare instruction (effectively
3550 // inverting the compare condition, swapping 'less' and 'greater') and
3551 // sometimes need to swap the operands to the VSEL (which inverts the
3552 // condition in the sense of firing whenever the previous condition didn't)
3553 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3554 TrueVal.getValueType() == MVT::f64)) {
3555 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3556 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3557 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3558 CC = ISD::getSetCCInverse(CC, true);
3559 std::swap(TrueVal, FalseVal);
3564 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3565 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3566 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3569 ARMCC::CondCodes CondCode, CondCode2;
3570 FPCCToARMCC(CC, CondCode, CondCode2);
3572 // Try to generate VMAXNM/VMINNM on ARMv8.
3573 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3574 TrueVal.getValueType() == MVT::f64)) {
3575 // We can use VMAXNM/VMINNM for a compare followed by a select with the
3576 // same operands, as follows:
3577 // c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3579 // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3580 bool swapSides = false;
3581 if (!getTargetMachine().Options.NoNaNsFPMath) {
3582 // transformability may depend on which way around we compare
3590 // the non-NaN should be RHS
3591 swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3597 // the non-NaN should be LHS
3598 swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3602 swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3604 CC = ISD::getSetCCSwappedOperands(CC);
3605 std::swap(LHS, RHS);
3607 if (LHS == TrueVal && RHS == FalseVal) {
3608 bool canTransform = true;
3609 // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3610 if (!getTargetMachine().Options.UnsafeFPMath &&
3611 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3612 const ConstantFPSDNode *Zero;
3619 // RHS must not be -0
3620 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3621 !Zero->isNegative();
3626 // LHS must not be -0
3627 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3628 !Zero->isNegative();
3633 // RHS must not be +0
3634 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3640 // LHS must not be +0
3641 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3647 // Note: If one of the elements in a pair is a number and the other
3648 // element is NaN, the corresponding result element is the number.
3649 // This is consistent with the IEEE 754-2008 standard.
3650 // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3656 if (!DAG.isKnownNeverNaN(RHS))
3658 return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3661 if (!DAG.isKnownNeverNaN(LHS))
3665 return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3668 if (!DAG.isKnownNeverNaN(RHS))
3670 return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3673 if (!DAG.isKnownNeverNaN(LHS))
3677 return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3682 bool swpCmpOps = false;
3683 bool swpVselOps = false;
3684 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3686 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3687 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3689 std::swap(LHS, RHS);
3691 std::swap(TrueVal, FalseVal);
3695 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3696 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3697 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3698 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3699 if (CondCode2 != ARMCC::AL) {
3700 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3701 // FIXME: Needs another CMP because flag can have but one use.
3702 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3703 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3708 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3709 /// to morph to an integer compare sequence.
3710 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3711 const ARMSubtarget *Subtarget) {
3712 SDNode *N = Op.getNode();
3713 if (!N->hasOneUse())
3714 // Otherwise it requires moving the value from fp to integer registers.
3716 if (!N->getNumValues())
3718 EVT VT = Op.getValueType();
3719 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3720 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3721 // vmrs are very slow, e.g. cortex-a8.
3724 if (isFloatingPointZero(Op)) {
3728 return ISD::isNormalLoad(N);
3731 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3732 if (isFloatingPointZero(Op))
3733 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3735 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3736 return DAG.getLoad(MVT::i32, SDLoc(Op),
3737 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3738 Ld->isVolatile(), Ld->isNonTemporal(),
3739 Ld->isInvariant(), Ld->getAlignment());
3741 llvm_unreachable("Unknown VFP cmp argument!");
3744 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3745 SDValue &RetVal1, SDValue &RetVal2) {
3748 if (isFloatingPointZero(Op)) {
3749 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3750 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3754 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3755 SDValue Ptr = Ld->getBasePtr();
3756 RetVal1 = DAG.getLoad(MVT::i32, dl,
3757 Ld->getChain(), Ptr,
3758 Ld->getPointerInfo(),
3759 Ld->isVolatile(), Ld->isNonTemporal(),
3760 Ld->isInvariant(), Ld->getAlignment());
3762 EVT PtrType = Ptr.getValueType();
3763 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3764 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3765 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3766 RetVal2 = DAG.getLoad(MVT::i32, dl,
3767 Ld->getChain(), NewPtr,
3768 Ld->getPointerInfo().getWithOffset(4),
3769 Ld->isVolatile(), Ld->isNonTemporal(),
3770 Ld->isInvariant(), NewAlign);
3774 llvm_unreachable("Unknown VFP cmp argument!");
3777 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3778 /// f32 and even f64 comparisons to integer ones.
3780 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3781 SDValue Chain = Op.getOperand(0);
3782 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3783 SDValue LHS = Op.getOperand(2);
3784 SDValue RHS = Op.getOperand(3);
3785 SDValue Dest = Op.getOperand(4);
3788 bool LHSSeenZero = false;
3789 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3790 bool RHSSeenZero = false;
3791 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3792 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3793 // If unsafe fp math optimization is enabled and there are no other uses of
3794 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3795 // to an integer comparison.
3796 if (CC == ISD::SETOEQ)
3798 else if (CC == ISD::SETUNE)
3801 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3803 if (LHS.getValueType() == MVT::f32) {
3804 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3805 bitcastf32Toi32(LHS, DAG), Mask);
3806 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3807 bitcastf32Toi32(RHS, DAG), Mask);
3808 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3809 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3810 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3811 Chain, Dest, ARMcc, CCR, Cmp);
3816 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3817 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3818 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3819 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3820 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3821 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3822 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3823 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3824 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3830 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3831 SDValue Chain = Op.getOperand(0);
3832 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3833 SDValue LHS = Op.getOperand(2);
3834 SDValue RHS = Op.getOperand(3);
3835 SDValue Dest = Op.getOperand(4);
3838 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3839 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3842 // If softenSetCCOperands only returned one value, we should compare it to
3844 if (!RHS.getNode()) {
3845 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3850 if (LHS.getValueType() == MVT::i32) {
3852 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3853 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3854 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3855 Chain, Dest, ARMcc, CCR, Cmp);
3858 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3860 if (getTargetMachine().Options.UnsafeFPMath &&
3861 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3862 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3863 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3864 if (Result.getNode())
3868 ARMCC::CondCodes CondCode, CondCode2;
3869 FPCCToARMCC(CC, CondCode, CondCode2);
3871 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3872 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3873 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3874 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3875 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3876 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3877 if (CondCode2 != ARMCC::AL) {
3878 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3879 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3880 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3885 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3886 SDValue Chain = Op.getOperand(0);
3887 SDValue Table = Op.getOperand(1);
3888 SDValue Index = Op.getOperand(2);
3891 EVT PTy = getPointerTy(DAG.getDataLayout());
3892 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3893 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3894 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3895 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3896 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3897 if (Subtarget->isThumb2()) {
3898 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3899 // which does another jump to the destination. This also makes it easier
3900 // to translate it to TBB / TBH later.
3901 // FIXME: This might not work if the function is extremely large.
3902 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3903 Addr, Op.getOperand(2), JTI);
3905 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3906 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3907 MachinePointerInfo::getJumpTable(),
3908 false, false, false, 0);
3909 Chain = Addr.getValue(1);
3910 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3911 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3913 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3914 MachinePointerInfo::getJumpTable(),
3915 false, false, false, 0);
3916 Chain = Addr.getValue(1);
3917 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3921 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3922 EVT VT = Op.getValueType();
3925 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3926 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3928 return DAG.UnrollVectorOp(Op.getNode());
3931 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3932 "Invalid type for custom lowering!");
3933 if (VT != MVT::v4i16)
3934 return DAG.UnrollVectorOp(Op.getNode());
3936 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3937 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3940 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3941 EVT VT = Op.getValueType();
3943 return LowerVectorFP_TO_INT(Op, DAG);
3944 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3946 if (Op.getOpcode() == ISD::FP_TO_SINT)
3947 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3950 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3952 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3953 /*isSigned*/ false, SDLoc(Op)).first;
3959 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3960 EVT VT = Op.getValueType();
3963 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3964 if (VT.getVectorElementType() == MVT::f32)
3966 return DAG.UnrollVectorOp(Op.getNode());
3969 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3970 "Invalid type for custom lowering!");
3971 if (VT != MVT::v4f32)
3972 return DAG.UnrollVectorOp(Op.getNode());
3976 switch (Op.getOpcode()) {
3977 default: llvm_unreachable("Invalid opcode!");
3978 case ISD::SINT_TO_FP:
3979 CastOpc = ISD::SIGN_EXTEND;
3980 Opc = ISD::SINT_TO_FP;
3982 case ISD::UINT_TO_FP:
3983 CastOpc = ISD::ZERO_EXTEND;
3984 Opc = ISD::UINT_TO_FP;
3988 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3989 return DAG.getNode(Opc, dl, VT, Op);
3992 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3993 EVT VT = Op.getValueType();
3995 return LowerVectorINT_TO_FP(Op, DAG);
3996 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3998 if (Op.getOpcode() == ISD::SINT_TO_FP)
3999 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4002 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4004 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4005 /*isSigned*/ false, SDLoc(Op)).first;
4011 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4012 // Implement fcopysign with a fabs and a conditional fneg.
4013 SDValue Tmp0 = Op.getOperand(0);
4014 SDValue Tmp1 = Op.getOperand(1);
4016 EVT VT = Op.getValueType();
4017 EVT SrcVT = Tmp1.getValueType();
4018 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4019 Tmp0.getOpcode() == ARMISD::VMOVDRR;
4020 bool UseNEON = !InGPR && Subtarget->hasNEON();
4023 // Use VBSL to copy the sign bit.
4024 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4025 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4026 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4027 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4029 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4030 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4031 DAG.getConstant(32, dl, MVT::i32));
4032 else /*if (VT == MVT::f32)*/
4033 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4034 if (SrcVT == MVT::f32) {
4035 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4037 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4038 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4039 DAG.getConstant(32, dl, MVT::i32));
4040 } else if (VT == MVT::f32)
4041 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4042 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4043 DAG.getConstant(32, dl, MVT::i32));
4044 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4045 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4047 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4049 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4050 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4051 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4053 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4054 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4055 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4056 if (VT == MVT::f32) {
4057 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4058 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4059 DAG.getConstant(0, dl, MVT::i32));
4061 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4067 // Bitcast operand 1 to i32.
4068 if (SrcVT == MVT::f64)
4069 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4071 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4073 // Or in the signbit with integer operations.
4074 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4075 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4076 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4077 if (VT == MVT::f32) {
4078 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4079 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4080 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4081 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4084 // f64: Or the high part with signbit and then combine two parts.
4085 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4087 SDValue Lo = Tmp0.getValue(0);
4088 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4089 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4090 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4093 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4094 MachineFunction &MF = DAG.getMachineFunction();
4095 MachineFrameInfo *MFI = MF.getFrameInfo();
4096 MFI->setReturnAddressIsTaken(true);
4098 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4101 EVT VT = Op.getValueType();
4103 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4105 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4106 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4107 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4108 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4109 MachinePointerInfo(), false, false, false, 0);
4112 // Return LR, which contains the return address. Mark it an implicit live-in.
4113 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4114 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4117 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4118 const ARMBaseRegisterInfo &ARI =
4119 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4120 MachineFunction &MF = DAG.getMachineFunction();
4121 MachineFrameInfo *MFI = MF.getFrameInfo();
4122 MFI->setFrameAddressIsTaken(true);
4124 EVT VT = Op.getValueType();
4125 SDLoc dl(Op); // FIXME probably not meaningful
4126 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4127 unsigned FrameReg = ARI.getFrameRegister(MF);
4128 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4130 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4131 MachinePointerInfo(),
4132 false, false, false, 0);
4136 // FIXME? Maybe this could be a TableGen attribute on some registers and
4137 // this table could be generated automatically from RegInfo.
4138 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4139 SelectionDAG &DAG) const {
4140 unsigned Reg = StringSwitch<unsigned>(RegName)
4141 .Case("sp", ARM::SP)
4145 report_fatal_error(Twine("Invalid register name \""
4146 + StringRef(RegName) + "\"."));
4149 // Result is 64 bit value so split into two 32 bit values and return as a
4151 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4152 SelectionDAG &DAG) {
4155 // This function is only supposed to be called for i64 type destination.
4156 assert(N->getValueType(0) == MVT::i64
4157 && "ExpandREAD_REGISTER called for non-i64 type result.");
4159 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4160 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4164 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4166 Results.push_back(Read.getOperand(0));
4169 /// ExpandBITCAST - If the target supports VFP, this function is called to
4170 /// expand a bit convert where either the source or destination type is i64 to
4171 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4172 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4173 /// vectors), since the legalizer won't know what to do with that.
4174 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4175 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4177 SDValue Op = N->getOperand(0);
4179 // This function is only supposed to be called for i64 types, either as the
4180 // source or destination of the bit convert.
4181 EVT SrcVT = Op.getValueType();
4182 EVT DstVT = N->getValueType(0);
4183 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4184 "ExpandBITCAST called for non-i64 type");
4186 // Turn i64->f64 into VMOVDRR.
4187 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4188 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4189 DAG.getConstant(0, dl, MVT::i32));
4190 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4191 DAG.getConstant(1, dl, MVT::i32));
4192 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4193 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4196 // Turn f64->i64 into VMOVRRD.
4197 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4199 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4200 SrcVT.getVectorNumElements() > 1)
4201 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4202 DAG.getVTList(MVT::i32, MVT::i32),
4203 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4205 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4206 DAG.getVTList(MVT::i32, MVT::i32), Op);
4207 // Merge the pieces into a single i64 value.
4208 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4214 /// getZeroVector - Returns a vector of specified type with all zero elements.
4215 /// Zero vectors are used to represent vector negation and in those cases
4216 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4217 /// not support i64 elements, so sometimes the zero vectors will need to be
4218 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4220 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4221 assert(VT.isVector() && "Expected a vector type");
4222 // The canonical modified immediate encoding of a zero vector is....0!
4223 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4224 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4225 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4226 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4229 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4230 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4231 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4232 SelectionDAG &DAG) const {
4233 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4234 EVT VT = Op.getValueType();
4235 unsigned VTBits = VT.getSizeInBits();
4237 SDValue ShOpLo = Op.getOperand(0);
4238 SDValue ShOpHi = Op.getOperand(1);
4239 SDValue ShAmt = Op.getOperand(2);
4241 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4243 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4245 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4246 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4247 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4248 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4249 DAG.getConstant(VTBits, dl, MVT::i32));
4250 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4251 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4252 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4254 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4255 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4256 ISD::SETGE, ARMcc, DAG, dl);
4257 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4258 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4261 SDValue Ops[2] = { Lo, Hi };
4262 return DAG.getMergeValues(Ops, dl);
4265 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4266 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4267 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4268 SelectionDAG &DAG) const {
4269 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4270 EVT VT = Op.getValueType();
4271 unsigned VTBits = VT.getSizeInBits();
4273 SDValue ShOpLo = Op.getOperand(0);
4274 SDValue ShOpHi = Op.getOperand(1);
4275 SDValue ShAmt = Op.getOperand(2);
4278 assert(Op.getOpcode() == ISD::SHL_PARTS);
4279 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4280 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4281 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4282 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4283 DAG.getConstant(VTBits, dl, MVT::i32));
4284 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4285 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4287 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4288 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4289 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4290 ISD::SETGE, ARMcc, DAG, dl);
4291 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4292 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4295 SDValue Ops[2] = { Lo, Hi };
4296 return DAG.getMergeValues(Ops, dl);
4299 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4300 SelectionDAG &DAG) const {
4301 // The rounding mode is in bits 23:22 of the FPSCR.
4302 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4303 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4304 // so that the shift + and get folded into a bitfield extract.
4306 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4307 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4309 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4310 DAG.getConstant(1U << 22, dl, MVT::i32));
4311 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4312 DAG.getConstant(22, dl, MVT::i32));
4313 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4314 DAG.getConstant(3, dl, MVT::i32));
4317 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4318 const ARMSubtarget *ST) {
4320 EVT VT = N->getValueType(0);
4321 if (VT.isVector()) {
4322 assert(ST->hasNEON());
4324 // Compute the least significant set bit: LSB = X & -X
4325 SDValue X = N->getOperand(0);
4326 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4327 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4329 EVT ElemTy = VT.getVectorElementType();
4331 if (ElemTy == MVT::i8) {
4332 // Compute with: cttz(x) = ctpop(lsb - 1)
4333 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4334 DAG.getTargetConstant(1, dl, ElemTy));
4335 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4336 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4339 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4340 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4341 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4342 unsigned NumBits = ElemTy.getSizeInBits();
4343 SDValue WidthMinus1 =
4344 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4345 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4346 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4347 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4350 // Compute with: cttz(x) = ctpop(lsb - 1)
4352 // Since we can only compute the number of bits in a byte with vcnt.8, we
4353 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4358 if (ElemTy == MVT::i64) {
4359 // Load constant 0xffff'ffff'ffff'ffff to register.
4360 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4361 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4362 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4364 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4365 DAG.getTargetConstant(1, dl, ElemTy));
4366 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4369 // Count #bits with vcnt.8.
4370 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4371 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4372 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4374 // Gather the #bits with vpaddl (pairwise add.)
4375 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4376 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4377 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4379 if (ElemTy == MVT::i16)
4382 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4383 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4384 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4386 if (ElemTy == MVT::i32)
4389 assert(ElemTy == MVT::i64);
4390 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4391 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4396 if (!ST->hasV6T2Ops())
4399 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4400 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4403 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4404 /// for each 16-bit element from operand, repeated. The basic idea is to
4405 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4407 /// Trace for v4i16:
4408 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4409 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4410 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4411 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4412 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4413 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4414 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4415 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4416 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4417 EVT VT = N->getValueType(0);
4420 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4421 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4422 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4423 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4424 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4425 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4428 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4429 /// bit-count for each 16-bit element from the operand. We need slightly
4430 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4431 /// 64/128-bit registers.
4433 /// Trace for v4i16:
4434 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4435 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4436 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4437 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4438 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4439 EVT VT = N->getValueType(0);
4442 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4443 if (VT.is64BitVector()) {
4444 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4445 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4446 DAG.getIntPtrConstant(0, DL));
4448 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4449 BitCounts, DAG.getIntPtrConstant(0, DL));
4450 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4454 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4455 /// bit-count for each 32-bit element from the operand. The idea here is
4456 /// to split the vector into 16-bit elements, leverage the 16-bit count
4457 /// routine, and then combine the results.
4459 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4460 /// input = [v0 v1 ] (vi: 32-bit elements)
4461 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4462 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4463 /// vrev: N0 = [k1 k0 k3 k2 ]
4465 /// N1 =+[k1 k0 k3 k2 ]
4467 /// N2 =+[k1 k3 k0 k2 ]
4469 /// Extended =+[k1 k3 k0 k2 ]
4471 /// Extracted=+[k1 k3 ]
4473 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4474 EVT VT = N->getValueType(0);
4477 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4479 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4480 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4481 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4482 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4483 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4485 if (VT.is64BitVector()) {
4486 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4487 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4488 DAG.getIntPtrConstant(0, DL));
4490 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4491 DAG.getIntPtrConstant(0, DL));
4492 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4496 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4497 const ARMSubtarget *ST) {
4498 EVT VT = N->getValueType(0);
4500 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4501 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4502 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4503 "Unexpected type for custom ctpop lowering");
4505 if (VT.getVectorElementType() == MVT::i32)
4506 return lowerCTPOP32BitElements(N, DAG);
4508 return lowerCTPOP16BitElements(N, DAG);
4511 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4512 const ARMSubtarget *ST) {
4513 EVT VT = N->getValueType(0);
4519 // Lower vector shifts on NEON to use VSHL.
4520 assert(ST->hasNEON() && "unexpected vector shift");
4522 // Left shifts translate directly to the vshiftu intrinsic.
4523 if (N->getOpcode() == ISD::SHL)
4524 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4525 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4527 N->getOperand(0), N->getOperand(1));
4529 assert((N->getOpcode() == ISD::SRA ||
4530 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4532 // NEON uses the same intrinsics for both left and right shifts. For
4533 // right shifts, the shift amounts are negative, so negate the vector of
4535 EVT ShiftVT = N->getOperand(1).getValueType();
4536 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4537 getZeroVector(ShiftVT, DAG, dl),
4539 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4540 Intrinsic::arm_neon_vshifts :
4541 Intrinsic::arm_neon_vshiftu);
4542 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4543 DAG.getConstant(vshiftInt, dl, MVT::i32),
4544 N->getOperand(0), NegatedCount);
4547 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4548 const ARMSubtarget *ST) {
4549 EVT VT = N->getValueType(0);
4552 // We can get here for a node like i32 = ISD::SHL i32, i64
4556 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4557 "Unknown shift to lower!");
4559 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4560 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4561 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4564 // If we are in thumb mode, we don't have RRX.
4565 if (ST->isThumb1Only()) return SDValue();
4567 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4568 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4569 DAG.getConstant(0, dl, MVT::i32));
4570 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4571 DAG.getConstant(1, dl, MVT::i32));
4573 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4574 // captures the result into a carry flag.
4575 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4576 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4578 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4579 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4581 // Merge the pieces into a single i64 value.
4582 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4585 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4586 SDValue TmpOp0, TmpOp1;
4587 bool Invert = false;
4591 SDValue Op0 = Op.getOperand(0);
4592 SDValue Op1 = Op.getOperand(1);
4593 SDValue CC = Op.getOperand(2);
4594 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4595 EVT VT = Op.getValueType();
4596 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4599 if (Op1.getValueType().isFloatingPoint()) {
4600 switch (SetCCOpcode) {
4601 default: llvm_unreachable("Illegal FP comparison");
4603 case ISD::SETNE: Invert = true; // Fallthrough
4605 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4607 case ISD::SETLT: Swap = true; // Fallthrough
4609 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4611 case ISD::SETLE: Swap = true; // Fallthrough
4613 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4614 case ISD::SETUGE: Swap = true; // Fallthrough
4615 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4616 case ISD::SETUGT: Swap = true; // Fallthrough
4617 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4618 case ISD::SETUEQ: Invert = true; // Fallthrough
4620 // Expand this to (OLT | OGT).
4624 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4625 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4627 case ISD::SETUO: Invert = true; // Fallthrough
4629 // Expand this to (OLT | OGE).
4633 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4634 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4638 // Integer comparisons.
4639 switch (SetCCOpcode) {
4640 default: llvm_unreachable("Illegal integer comparison");
4641 case ISD::SETNE: Invert = true;
4642 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4643 case ISD::SETLT: Swap = true;
4644 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4645 case ISD::SETLE: Swap = true;
4646 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4647 case ISD::SETULT: Swap = true;
4648 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4649 case ISD::SETULE: Swap = true;
4650 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4653 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4654 if (Opc == ARMISD::VCEQ) {
4657 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4659 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4662 // Ignore bitconvert.
4663 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4664 AndOp = AndOp.getOperand(0);
4666 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4668 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4669 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4676 std::swap(Op0, Op1);
4678 // If one of the operands is a constant vector zero, attempt to fold the
4679 // comparison to a specialized compare-against-zero form.
4681 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4683 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4684 if (Opc == ARMISD::VCGE)
4685 Opc = ARMISD::VCLEZ;
4686 else if (Opc == ARMISD::VCGT)
4687 Opc = ARMISD::VCLTZ;
4692 if (SingleOp.getNode()) {
4695 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4697 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4699 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4701 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4703 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4705 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4708 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4711 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4714 Result = DAG.getNOT(dl, Result, VT);
4719 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4720 /// valid vector constant for a NEON instruction with a "modified immediate"
4721 /// operand (e.g., VMOV). If so, return the encoded value.
4722 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4723 unsigned SplatBitSize, SelectionDAG &DAG,
4724 SDLoc dl, EVT &VT, bool is128Bits,
4725 NEONModImmType type) {
4726 unsigned OpCmode, Imm;
4728 // SplatBitSize is set to the smallest size that splats the vector, so a
4729 // zero vector will always have SplatBitSize == 8. However, NEON modified
4730 // immediate instructions others than VMOV do not support the 8-bit encoding
4731 // of a zero vector, and the default encoding of zero is supposed to be the
4736 switch (SplatBitSize) {
4738 if (type != VMOVModImm)
4740 // Any 1-byte value is OK. Op=0, Cmode=1110.
4741 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4744 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4748 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4749 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4750 if ((SplatBits & ~0xff) == 0) {
4751 // Value = 0x00nn: Op=x, Cmode=100x.
4756 if ((SplatBits & ~0xff00) == 0) {
4757 // Value = 0xnn00: Op=x, Cmode=101x.
4759 Imm = SplatBits >> 8;
4765 // NEON's 32-bit VMOV supports splat values where:
4766 // * only one byte is nonzero, or
4767 // * the least significant byte is 0xff and the second byte is nonzero, or
4768 // * the least significant 2 bytes are 0xff and the third is nonzero.
4769 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4770 if ((SplatBits & ~0xff) == 0) {
4771 // Value = 0x000000nn: Op=x, Cmode=000x.
4776 if ((SplatBits & ~0xff00) == 0) {
4777 // Value = 0x0000nn00: Op=x, Cmode=001x.
4779 Imm = SplatBits >> 8;
4782 if ((SplatBits & ~0xff0000) == 0) {
4783 // Value = 0x00nn0000: Op=x, Cmode=010x.
4785 Imm = SplatBits >> 16;
4788 if ((SplatBits & ~0xff000000) == 0) {
4789 // Value = 0xnn000000: Op=x, Cmode=011x.
4791 Imm = SplatBits >> 24;
4795 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4796 if (type == OtherModImm) return SDValue();
4798 if ((SplatBits & ~0xffff) == 0 &&
4799 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4800 // Value = 0x0000nnff: Op=x, Cmode=1100.
4802 Imm = SplatBits >> 8;
4806 if ((SplatBits & ~0xffffff) == 0 &&
4807 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4808 // Value = 0x00nnffff: Op=x, Cmode=1101.
4810 Imm = SplatBits >> 16;
4814 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4815 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4816 // VMOV.I32. A (very) minor optimization would be to replicate the value
4817 // and fall through here to test for a valid 64-bit splat. But, then the
4818 // caller would also need to check and handle the change in size.
4822 if (type != VMOVModImm)
4824 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4825 uint64_t BitMask = 0xff;
4827 unsigned ImmMask = 1;
4829 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4830 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4833 } else if ((SplatBits & BitMask) != 0) {
4840 if (DAG.getDataLayout().isBigEndian())
4841 // swap higher and lower 32 bit word
4842 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4844 // Op=1, Cmode=1110.
4846 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4851 llvm_unreachable("unexpected size for isNEONModifiedImm");
4854 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4855 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4858 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4859 const ARMSubtarget *ST) const {
4863 bool IsDouble = Op.getValueType() == MVT::f64;
4864 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4866 // Use the default (constant pool) lowering for double constants when we have
4868 if (IsDouble && Subtarget->isFPOnlySP())
4871 // Try splatting with a VMOV.f32...
4872 APFloat FPVal = CFP->getValueAPF();
4873 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4876 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4877 // We have code in place to select a valid ConstantFP already, no need to
4882 // It's a float and we are trying to use NEON operations where
4883 // possible. Lower it to a splat followed by an extract.
4885 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4886 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4888 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4889 DAG.getConstant(0, DL, MVT::i32));
4892 // The rest of our options are NEON only, make sure that's allowed before
4894 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4898 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4900 // It wouldn't really be worth bothering for doubles except for one very
4901 // important value, which does happen to match: 0.0. So make sure we don't do
4903 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4906 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4907 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4908 VMovVT, false, VMOVModImm);
4909 if (NewVal != SDValue()) {
4911 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4914 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4916 // It's a float: cast and extract a vector element.
4917 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4919 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4920 DAG.getConstant(0, DL, MVT::i32));
4923 // Finally, try a VMVN.i32
4924 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4926 if (NewVal != SDValue()) {
4928 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4931 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4933 // It's a float: cast and extract a vector element.
4934 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4936 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4937 DAG.getConstant(0, DL, MVT::i32));
4943 // check if an VEXT instruction can handle the shuffle mask when the
4944 // vector sources of the shuffle are the same.
4945 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4946 unsigned NumElts = VT.getVectorNumElements();
4948 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4954 // If this is a VEXT shuffle, the immediate value is the index of the first
4955 // element. The other shuffle indices must be the successive elements after
4957 unsigned ExpectedElt = Imm;
4958 for (unsigned i = 1; i < NumElts; ++i) {
4959 // Increment the expected index. If it wraps around, just follow it
4960 // back to index zero and keep going.
4962 if (ExpectedElt == NumElts)
4965 if (M[i] < 0) continue; // ignore UNDEF indices
4966 if (ExpectedElt != static_cast<unsigned>(M[i]))
4974 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4975 bool &ReverseVEXT, unsigned &Imm) {
4976 unsigned NumElts = VT.getVectorNumElements();
4977 ReverseVEXT = false;
4979 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4985 // If this is a VEXT shuffle, the immediate value is the index of the first
4986 // element. The other shuffle indices must be the successive elements after
4988 unsigned ExpectedElt = Imm;
4989 for (unsigned i = 1; i < NumElts; ++i) {
4990 // Increment the expected index. If it wraps around, it may still be
4991 // a VEXT but the source vectors must be swapped.
4993 if (ExpectedElt == NumElts * 2) {
4998 if (M[i] < 0) continue; // ignore UNDEF indices
4999 if (ExpectedElt != static_cast<unsigned>(M[i]))
5003 // Adjust the index value if the source operands will be swapped.
5010 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5011 /// instruction with the specified blocksize. (The order of the elements
5012 /// within each block of the vector is reversed.)
5013 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5014 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5015 "Only possible block sizes for VREV are: 16, 32, 64");
5017 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5021 unsigned NumElts = VT.getVectorNumElements();
5022 unsigned BlockElts = M[0] + 1;
5023 // If the first shuffle index is UNDEF, be optimistic.
5025 BlockElts = BlockSize / EltSz;
5027 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5030 for (unsigned i = 0; i < NumElts; ++i) {
5031 if (M[i] < 0) continue; // ignore UNDEF indices
5032 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5039 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5040 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5041 // range, then 0 is placed into the resulting vector. So pretty much any mask
5042 // of 8 elements can work here.
5043 return VT == MVT::v8i8 && M.size() == 8;
5046 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5047 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5051 unsigned NumElts = VT.getVectorNumElements();
5052 WhichResult = (M[0] == 0 ? 0 : 1);
5053 for (unsigned i = 0; i < NumElts; i += 2) {
5054 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
5055 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
5061 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5062 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5063 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5064 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5065 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5069 unsigned NumElts = VT.getVectorNumElements();
5070 WhichResult = (M[0] == 0 ? 0 : 1);
5071 for (unsigned i = 0; i < NumElts; i += 2) {
5072 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
5073 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
5079 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5080 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5084 unsigned NumElts = VT.getVectorNumElements();
5085 WhichResult = (M[0] == 0 ? 0 : 1);
5086 for (unsigned i = 0; i != NumElts; ++i) {
5087 if (M[i] < 0) continue; // ignore UNDEF indices
5088 if ((unsigned) M[i] != 2 * i + WhichResult)
5092 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5093 if (VT.is64BitVector() && EltSz == 32)
5099 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5100 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5101 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5102 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5103 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5107 unsigned Half = VT.getVectorNumElements() / 2;
5108 WhichResult = (M[0] == 0 ? 0 : 1);
5109 for (unsigned j = 0; j != 2; ++j) {
5110 unsigned Idx = WhichResult;
5111 for (unsigned i = 0; i != Half; ++i) {
5112 int MIdx = M[i + j * Half];
5113 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5119 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5120 if (VT.is64BitVector() && EltSz == 32)
5126 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5127 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5131 unsigned NumElts = VT.getVectorNumElements();
5132 WhichResult = (M[0] == 0 ? 0 : 1);
5133 unsigned Idx = WhichResult * NumElts / 2;
5134 for (unsigned i = 0; i != NumElts; i += 2) {
5135 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5136 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5141 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5142 if (VT.is64BitVector() && EltSz == 32)
5148 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5149 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5150 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5151 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5152 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5156 unsigned NumElts = VT.getVectorNumElements();
5157 WhichResult = (M[0] == 0 ? 0 : 1);
5158 unsigned Idx = WhichResult * NumElts / 2;
5159 for (unsigned i = 0; i != NumElts; i += 2) {
5160 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5161 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5166 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5167 if (VT.is64BitVector() && EltSz == 32)
5173 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5174 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5175 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5176 unsigned &WhichResult,
5179 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5180 return ARMISD::VTRN;
5181 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5182 return ARMISD::VUZP;
5183 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5184 return ARMISD::VZIP;
5187 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5188 return ARMISD::VTRN;
5189 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5190 return ARMISD::VUZP;
5191 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5192 return ARMISD::VZIP;
5197 /// \return true if this is a reverse operation on an vector.
5198 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5199 unsigned NumElts = VT.getVectorNumElements();
5200 // Make sure the mask has the right size.
5201 if (NumElts != M.size())
5204 // Look for <15, ..., 3, -1, 1, 0>.
5205 for (unsigned i = 0; i != NumElts; ++i)
5206 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5212 // If N is an integer constant that can be moved into a register in one
5213 // instruction, return an SDValue of such a constant (will become a MOV
5214 // instruction). Otherwise return null.
5215 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5216 const ARMSubtarget *ST, SDLoc dl) {
5218 if (!isa<ConstantSDNode>(N))
5220 Val = cast<ConstantSDNode>(N)->getZExtValue();
5222 if (ST->isThumb1Only()) {
5223 if (Val <= 255 || ~Val <= 255)
5224 return DAG.getConstant(Val, dl, MVT::i32);
5226 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5227 return DAG.getConstant(Val, dl, MVT::i32);
5232 // If this is a case we can't handle, return null and let the default
5233 // expansion code take care of it.
5234 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5235 const ARMSubtarget *ST) const {
5236 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5238 EVT VT = Op.getValueType();
5240 APInt SplatBits, SplatUndef;
5241 unsigned SplatBitSize;
5243 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5244 if (SplatBitSize <= 64) {
5245 // Check if an immediate VMOV works.
5247 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5248 SplatUndef.getZExtValue(), SplatBitSize,
5249 DAG, dl, VmovVT, VT.is128BitVector(),
5251 if (Val.getNode()) {
5252 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5253 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5256 // Try an immediate VMVN.
5257 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5258 Val = isNEONModifiedImm(NegatedImm,
5259 SplatUndef.getZExtValue(), SplatBitSize,
5260 DAG, dl, VmovVT, VT.is128BitVector(),
5262 if (Val.getNode()) {
5263 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5264 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5267 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5268 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5269 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5271 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5272 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5278 // Scan through the operands to see if only one value is used.
5280 // As an optimisation, even if more than one value is used it may be more
5281 // profitable to splat with one value then change some lanes.
5283 // Heuristically we decide to do this if the vector has a "dominant" value,
5284 // defined as splatted to more than half of the lanes.
5285 unsigned NumElts = VT.getVectorNumElements();
5286 bool isOnlyLowElement = true;
5287 bool usesOnlyOneValue = true;
5288 bool hasDominantValue = false;
5289 bool isConstant = true;
5291 // Map of the number of times a particular SDValue appears in the
5293 DenseMap<SDValue, unsigned> ValueCounts;
5295 for (unsigned i = 0; i < NumElts; ++i) {
5296 SDValue V = Op.getOperand(i);
5297 if (V.getOpcode() == ISD::UNDEF)
5300 isOnlyLowElement = false;
5301 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5304 ValueCounts.insert(std::make_pair(V, 0));
5305 unsigned &Count = ValueCounts[V];
5307 // Is this value dominant? (takes up more than half of the lanes)
5308 if (++Count > (NumElts / 2)) {
5309 hasDominantValue = true;
5313 if (ValueCounts.size() != 1)
5314 usesOnlyOneValue = false;
5315 if (!Value.getNode() && ValueCounts.size() > 0)
5316 Value = ValueCounts.begin()->first;
5318 if (ValueCounts.size() == 0)
5319 return DAG.getUNDEF(VT);
5321 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5322 // Keep going if we are hitting this case.
5323 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5324 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5326 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5328 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5329 // i32 and try again.
5330 if (hasDominantValue && EltSize <= 32) {
5334 // If we are VDUPing a value that comes directly from a vector, that will
5335 // cause an unnecessary move to and from a GPR, where instead we could
5336 // just use VDUPLANE. We can only do this if the lane being extracted
5337 // is at a constant index, as the VDUP from lane instructions only have
5338 // constant-index forms.
5339 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5340 isa<ConstantSDNode>(Value->getOperand(1))) {
5341 // We need to create a new undef vector to use for the VDUPLANE if the
5342 // size of the vector from which we get the value is different than the
5343 // size of the vector that we need to create. We will insert the element
5344 // such that the register coalescer will remove unnecessary copies.
5345 if (VT != Value->getOperand(0).getValueType()) {
5346 ConstantSDNode *constIndex;
5347 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5348 assert(constIndex && "The index is not a constant!");
5349 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5350 VT.getVectorNumElements();
5351 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5352 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5353 Value, DAG.getConstant(index, dl, MVT::i32)),
5354 DAG.getConstant(index, dl, MVT::i32));
5356 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5357 Value->getOperand(0), Value->getOperand(1));
5359 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5361 if (!usesOnlyOneValue) {
5362 // The dominant value was splatted as 'N', but we now have to insert
5363 // all differing elements.
5364 for (unsigned I = 0; I < NumElts; ++I) {
5365 if (Op.getOperand(I) == Value)
5367 SmallVector<SDValue, 3> Ops;
5369 Ops.push_back(Op.getOperand(I));
5370 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5371 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5376 if (VT.getVectorElementType().isFloatingPoint()) {
5377 SmallVector<SDValue, 8> Ops;
5378 for (unsigned i = 0; i < NumElts; ++i)
5379 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5381 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5382 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5383 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5385 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5387 if (usesOnlyOneValue) {
5388 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5389 if (isConstant && Val.getNode())
5390 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5394 // If all elements are constants and the case above didn't get hit, fall back
5395 // to the default expansion, which will generate a load from the constant
5400 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5402 SDValue shuffle = ReconstructShuffle(Op, DAG);
5403 if (shuffle != SDValue())
5407 // Vectors with 32- or 64-bit elements can be built by directly assigning
5408 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5409 // will be legalized.
5410 if (EltSize >= 32) {
5411 // Do the expansion with floating-point types, since that is what the VFP
5412 // registers are defined to use, and since i64 is not legal.
5413 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5414 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5415 SmallVector<SDValue, 8> Ops;
5416 for (unsigned i = 0; i < NumElts; ++i)
5417 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5418 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5419 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5422 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5423 // know the default expansion would otherwise fall back on something even
5424 // worse. For a vector with one or two non-undef values, that's
5425 // scalar_to_vector for the elements followed by a shuffle (provided the
5426 // shuffle is valid for the target) and materialization element by element
5427 // on the stack followed by a load for everything else.
5428 if (!isConstant && !usesOnlyOneValue) {
5429 SDValue Vec = DAG.getUNDEF(VT);
5430 for (unsigned i = 0 ; i < NumElts; ++i) {
5431 SDValue V = Op.getOperand(i);
5432 if (V.getOpcode() == ISD::UNDEF)
5434 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5435 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5443 // Gather data to see if the operation can be modelled as a
5444 // shuffle in combination with VEXTs.
5445 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5446 SelectionDAG &DAG) const {
5448 EVT VT = Op.getValueType();
5449 unsigned NumElts = VT.getVectorNumElements();
5451 SmallVector<SDValue, 2> SourceVecs;
5452 SmallVector<unsigned, 2> MinElts;
5453 SmallVector<unsigned, 2> MaxElts;
5455 for (unsigned i = 0; i < NumElts; ++i) {
5456 SDValue V = Op.getOperand(i);
5457 if (V.getOpcode() == ISD::UNDEF)
5459 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5460 // A shuffle can only come from building a vector from various
5461 // elements of other vectors.
5463 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5464 VT.getVectorElementType()) {
5465 // This code doesn't know how to handle shuffles where the vector
5466 // element types do not match (this happens because type legalization
5467 // promotes the return type of EXTRACT_VECTOR_ELT).
5468 // FIXME: It might be appropriate to extend this code to handle
5469 // mismatched types.
5473 // Record this extraction against the appropriate vector if possible...
5474 SDValue SourceVec = V.getOperand(0);
5475 // If the element number isn't a constant, we can't effectively
5476 // analyze what's going on.
5477 if (!isa<ConstantSDNode>(V.getOperand(1)))
5479 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5480 bool FoundSource = false;
5481 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5482 if (SourceVecs[j] == SourceVec) {
5483 if (MinElts[j] > EltNo)
5485 if (MaxElts[j] < EltNo)
5492 // Or record a new source if not...
5494 SourceVecs.push_back(SourceVec);
5495 MinElts.push_back(EltNo);
5496 MaxElts.push_back(EltNo);
5500 // Currently only do something sane when at most two source vectors
5502 if (SourceVecs.size() > 2)
5505 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5506 int VEXTOffsets[2] = {0, 0};
5508 // This loop extracts the usage patterns of the source vectors
5509 // and prepares appropriate SDValues for a shuffle if possible.
5510 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5511 if (SourceVecs[i].getValueType() == VT) {
5512 // No VEXT necessary
5513 ShuffleSrcs[i] = SourceVecs[i];
5516 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5517 // It probably isn't worth padding out a smaller vector just to
5518 // break it down again in a shuffle.
5522 // Since only 64-bit and 128-bit vectors are legal on ARM and
5523 // we've eliminated the other cases...
5524 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5525 "unexpected vector sizes in ReconstructShuffle");
5527 if (MaxElts[i] - MinElts[i] >= NumElts) {
5528 // Span too large for a VEXT to cope
5532 if (MinElts[i] >= NumElts) {
5533 // The extraction can just take the second half
5534 VEXTOffsets[i] = NumElts;
5535 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5537 DAG.getIntPtrConstant(NumElts, dl));
5538 } else if (MaxElts[i] < NumElts) {
5539 // The extraction can just take the first half
5541 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5543 DAG.getIntPtrConstant(0, dl));
5545 // An actual VEXT is needed
5546 VEXTOffsets[i] = MinElts[i];
5547 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5549 DAG.getIntPtrConstant(0, dl));
5550 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5552 DAG.getIntPtrConstant(NumElts, dl));
5553 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5554 DAG.getConstant(VEXTOffsets[i], dl,
5559 SmallVector<int, 8> Mask;
5561 for (unsigned i = 0; i < NumElts; ++i) {
5562 SDValue Entry = Op.getOperand(i);
5563 if (Entry.getOpcode() == ISD::UNDEF) {
5568 SDValue ExtractVec = Entry.getOperand(0);
5569 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5570 .getOperand(1))->getSExtValue();
5571 if (ExtractVec == SourceVecs[0]) {
5572 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5574 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5578 // Final check before we try to produce nonsense...
5579 if (isShuffleMaskLegal(Mask, VT))
5580 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5586 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5587 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5588 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5589 /// are assumed to be legal.
5591 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5593 if (VT.getVectorNumElements() == 4 &&
5594 (VT.is128BitVector() || VT.is64BitVector())) {
5595 unsigned PFIndexes[4];
5596 for (unsigned i = 0; i != 4; ++i) {
5600 PFIndexes[i] = M[i];
5603 // Compute the index in the perfect shuffle table.
5604 unsigned PFTableIndex =
5605 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5606 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5607 unsigned Cost = (PFEntry >> 30);
5613 bool ReverseVEXT, isV_UNDEF;
5614 unsigned Imm, WhichResult;
5616 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5617 return (EltSize >= 32 ||
5618 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5619 isVREVMask(M, VT, 64) ||
5620 isVREVMask(M, VT, 32) ||
5621 isVREVMask(M, VT, 16) ||
5622 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5623 isVTBLMask(M, VT) ||
5624 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5625 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5628 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5629 /// the specified operations to build the shuffle.
5630 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5631 SDValue RHS, SelectionDAG &DAG,
5633 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5634 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5635 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5638 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5647 OP_VUZPL, // VUZP, left result
5648 OP_VUZPR, // VUZP, right result
5649 OP_VZIPL, // VZIP, left result
5650 OP_VZIPR, // VZIP, right result
5651 OP_VTRNL, // VTRN, left result
5652 OP_VTRNR // VTRN, right result
5655 if (OpNum == OP_COPY) {
5656 if (LHSID == (1*9+2)*9+3) return LHS;
5657 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5661 SDValue OpLHS, OpRHS;
5662 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5663 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5664 EVT VT = OpLHS.getValueType();
5667 default: llvm_unreachable("Unknown shuffle opcode!");
5669 // VREV divides the vector in half and swaps within the half.
5670 if (VT.getVectorElementType() == MVT::i32 ||
5671 VT.getVectorElementType() == MVT::f32)
5672 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5673 // vrev <4 x i16> -> VREV32
5674 if (VT.getVectorElementType() == MVT::i16)
5675 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5676 // vrev <4 x i8> -> VREV16
5677 assert(VT.getVectorElementType() == MVT::i8);
5678 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5683 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5684 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5688 return DAG.getNode(ARMISD::VEXT, dl, VT,
5690 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5693 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5694 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5697 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5698 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5701 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5702 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5706 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5707 ArrayRef<int> ShuffleMask,
5708 SelectionDAG &DAG) {
5709 // Check to see if we can use the VTBL instruction.
5710 SDValue V1 = Op.getOperand(0);
5711 SDValue V2 = Op.getOperand(1);
5714 SmallVector<SDValue, 8> VTBLMask;
5715 for (ArrayRef<int>::iterator
5716 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5717 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5719 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5720 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5721 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5723 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5724 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5727 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5728 SelectionDAG &DAG) {
5730 SDValue OpLHS = Op.getOperand(0);
5731 EVT VT = OpLHS.getValueType();
5733 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5734 "Expect an v8i16/v16i8 type");
5735 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5736 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5737 // extract the first 8 bytes into the top double word and the last 8 bytes
5738 // into the bottom double word. The v8i16 case is similar.
5739 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5740 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5741 DAG.getConstant(ExtractNum, DL, MVT::i32));
5744 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5745 SDValue V1 = Op.getOperand(0);
5746 SDValue V2 = Op.getOperand(1);
5748 EVT VT = Op.getValueType();
5749 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5751 // Convert shuffles that are directly supported on NEON to target-specific
5752 // DAG nodes, instead of keeping them as shuffles and matching them again
5753 // during code selection. This is more efficient and avoids the possibility
5754 // of inconsistencies between legalization and selection.
5755 // FIXME: floating-point vectors should be canonicalized to integer vectors
5756 // of the same time so that they get CSEd properly.
5757 ArrayRef<int> ShuffleMask = SVN->getMask();
5759 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5760 if (EltSize <= 32) {
5761 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5762 int Lane = SVN->getSplatIndex();
5763 // If this is undef splat, generate it via "just" vdup, if possible.
5764 if (Lane == -1) Lane = 0;
5766 // Test if V1 is a SCALAR_TO_VECTOR.
5767 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5768 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5770 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5771 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5773 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5774 !isa<ConstantSDNode>(V1.getOperand(0))) {
5775 bool IsScalarToVector = true;
5776 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5777 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5778 IsScalarToVector = false;
5781 if (IsScalarToVector)
5782 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5784 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5785 DAG.getConstant(Lane, dl, MVT::i32));
5790 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5793 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5794 DAG.getConstant(Imm, dl, MVT::i32));
5797 if (isVREVMask(ShuffleMask, VT, 64))
5798 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5799 if (isVREVMask(ShuffleMask, VT, 32))
5800 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5801 if (isVREVMask(ShuffleMask, VT, 16))
5802 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5804 if (V2->getOpcode() == ISD::UNDEF &&
5805 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5806 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5807 DAG.getConstant(Imm, dl, MVT::i32));
5810 // Check for Neon shuffles that modify both input vectors in place.
5811 // If both results are used, i.e., if there are two shuffles with the same
5812 // source operands and with masks corresponding to both results of one of
5813 // these operations, DAG memoization will ensure that a single node is
5814 // used for both shuffles.
5815 unsigned WhichResult;
5817 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5818 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5821 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5822 .getValue(WhichResult);
5825 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5826 // shuffles that produce a result larger than their operands with:
5827 // shuffle(concat(v1, undef), concat(v2, undef))
5829 // shuffle(concat(v1, v2), undef)
5830 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5832 // This is useful in the general case, but there are special cases where
5833 // native shuffles produce larger results: the two-result ops.
5835 // Look through the concat when lowering them:
5836 // shuffle(concat(v1, v2), undef)
5838 // concat(VZIP(v1, v2):0, :1)
5840 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5841 V2->getOpcode() == ISD::UNDEF) {
5842 SDValue SubV1 = V1->getOperand(0);
5843 SDValue SubV2 = V1->getOperand(1);
5844 EVT SubVT = SubV1.getValueType();
5846 // We expect these to have been canonicalized to -1.
5847 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5848 return i < (int)VT.getVectorNumElements();
5849 }) && "Unexpected shuffle index into UNDEF operand!");
5851 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5852 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5855 assert((WhichResult == 0) &&
5856 "In-place shuffle of concat can only have one result!");
5857 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5859 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5865 // If the shuffle is not directly supported and it has 4 elements, use
5866 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5867 unsigned NumElts = VT.getVectorNumElements();
5869 unsigned PFIndexes[4];
5870 for (unsigned i = 0; i != 4; ++i) {
5871 if (ShuffleMask[i] < 0)
5874 PFIndexes[i] = ShuffleMask[i];
5877 // Compute the index in the perfect shuffle table.
5878 unsigned PFTableIndex =
5879 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5880 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5881 unsigned Cost = (PFEntry >> 30);
5884 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5887 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5888 if (EltSize >= 32) {
5889 // Do the expansion with floating-point types, since that is what the VFP
5890 // registers are defined to use, and since i64 is not legal.
5891 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5892 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5893 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5894 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5895 SmallVector<SDValue, 8> Ops;
5896 for (unsigned i = 0; i < NumElts; ++i) {
5897 if (ShuffleMask[i] < 0)
5898 Ops.push_back(DAG.getUNDEF(EltVT));
5900 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5901 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5902 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5905 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5906 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5909 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5910 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5912 if (VT == MVT::v8i8) {
5913 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5914 if (NewOp.getNode())
5921 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5922 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5923 SDValue Lane = Op.getOperand(2);
5924 if (!isa<ConstantSDNode>(Lane))
5930 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5931 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5932 SDValue Lane = Op.getOperand(1);
5933 if (!isa<ConstantSDNode>(Lane))
5936 SDValue Vec = Op.getOperand(0);
5937 if (Op.getValueType() == MVT::i32 &&
5938 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5940 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5946 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5947 // The only time a CONCAT_VECTORS operation can have legal types is when
5948 // two 64-bit vectors are concatenated to a 128-bit vector.
5949 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5950 "unexpected CONCAT_VECTORS");
5952 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5953 SDValue Op0 = Op.getOperand(0);
5954 SDValue Op1 = Op.getOperand(1);
5955 if (Op0.getOpcode() != ISD::UNDEF)
5956 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5957 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5958 DAG.getIntPtrConstant(0, dl));
5959 if (Op1.getOpcode() != ISD::UNDEF)
5960 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5961 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5962 DAG.getIntPtrConstant(1, dl));
5963 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5966 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5967 /// element has been zero/sign-extended, depending on the isSigned parameter,
5968 /// from an integer type half its size.
5969 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5971 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5972 EVT VT = N->getValueType(0);
5973 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5974 SDNode *BVN = N->getOperand(0).getNode();
5975 if (BVN->getValueType(0) != MVT::v4i32 ||
5976 BVN->getOpcode() != ISD::BUILD_VECTOR)
5978 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
5979 unsigned HiElt = 1 - LoElt;
5980 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5981 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5982 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5983 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5984 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5987 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5988 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5991 if (Hi0->isNullValue() && Hi1->isNullValue())
5997 if (N->getOpcode() != ISD::BUILD_VECTOR)
6000 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6001 SDNode *Elt = N->getOperand(i).getNode();
6002 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6003 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6004 unsigned HalfSize = EltSize / 2;
6006 if (!isIntN(HalfSize, C->getSExtValue()))
6009 if (!isUIntN(HalfSize, C->getZExtValue()))
6020 /// isSignExtended - Check if a node is a vector value that is sign-extended
6021 /// or a constant BUILD_VECTOR with sign-extended elements.
6022 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6023 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6025 if (isExtendedBUILD_VECTOR(N, DAG, true))
6030 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6031 /// or a constant BUILD_VECTOR with zero-extended elements.
6032 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6033 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6035 if (isExtendedBUILD_VECTOR(N, DAG, false))
6040 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6041 if (OrigVT.getSizeInBits() >= 64)
6044 assert(OrigVT.isSimple() && "Expecting a simple value type");
6046 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6047 switch (OrigSimpleTy) {
6048 default: llvm_unreachable("Unexpected Vector Type");
6057 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6058 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6059 /// We insert the required extension here to get the vector to fill a D register.
6060 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6063 unsigned ExtOpcode) {
6064 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6065 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6066 // 64-bits we need to insert a new extension so that it will be 64-bits.
6067 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6068 if (OrigTy.getSizeInBits() >= 64)
6071 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6072 EVT NewVT = getExtensionTo64Bits(OrigTy);
6074 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6077 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6078 /// does not do any sign/zero extension. If the original vector is less
6079 /// than 64 bits, an appropriate extension will be added after the load to
6080 /// reach a total size of 64 bits. We have to add the extension separately
6081 /// because ARM does not have a sign/zero extending load for vectors.
6082 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6083 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6085 // The load already has the right type.
6086 if (ExtendedTy == LD->getMemoryVT())
6087 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6088 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6089 LD->isNonTemporal(), LD->isInvariant(),
6090 LD->getAlignment());
6092 // We need to create a zextload/sextload. We cannot just create a load
6093 // followed by a zext/zext node because LowerMUL is also run during normal
6094 // operation legalization where we can't create illegal types.
6095 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6096 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6097 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6098 LD->isNonTemporal(), LD->getAlignment());
6101 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6102 /// extending load, or BUILD_VECTOR with extended elements, return the
6103 /// unextended value. The unextended vector should be 64 bits so that it can
6104 /// be used as an operand to a VMULL instruction. If the original vector size
6105 /// before extension is less than 64 bits we add a an extension to resize
6106 /// the vector to 64 bits.
6107 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6108 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6109 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6110 N->getOperand(0)->getValueType(0),
6114 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6115 return SkipLoadExtensionForVMULL(LD, DAG);
6117 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6118 // have been legalized as a BITCAST from v4i32.
6119 if (N->getOpcode() == ISD::BITCAST) {
6120 SDNode *BVN = N->getOperand(0).getNode();
6121 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6122 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6123 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6124 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6125 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6127 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6128 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6129 EVT VT = N->getValueType(0);
6130 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6131 unsigned NumElts = VT.getVectorNumElements();
6132 MVT TruncVT = MVT::getIntegerVT(EltSize);
6133 SmallVector<SDValue, 8> Ops;
6135 for (unsigned i = 0; i != NumElts; ++i) {
6136 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6137 const APInt &CInt = C->getAPIntValue();
6138 // Element types smaller than 32 bits are not legal, so use i32 elements.
6139 // The values are implicitly truncated so sext vs. zext doesn't matter.
6140 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6142 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6143 MVT::getVectorVT(TruncVT, NumElts), Ops);
6146 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6147 unsigned Opcode = N->getOpcode();
6148 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6149 SDNode *N0 = N->getOperand(0).getNode();
6150 SDNode *N1 = N->getOperand(1).getNode();
6151 return N0->hasOneUse() && N1->hasOneUse() &&
6152 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6157 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6158 unsigned Opcode = N->getOpcode();
6159 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6160 SDNode *N0 = N->getOperand(0).getNode();
6161 SDNode *N1 = N->getOperand(1).getNode();
6162 return N0->hasOneUse() && N1->hasOneUse() &&
6163 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6168 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6169 // Multiplications are only custom-lowered for 128-bit vectors so that
6170 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6171 EVT VT = Op.getValueType();
6172 assert(VT.is128BitVector() && VT.isInteger() &&
6173 "unexpected type for custom-lowering ISD::MUL");
6174 SDNode *N0 = Op.getOperand(0).getNode();
6175 SDNode *N1 = Op.getOperand(1).getNode();
6176 unsigned NewOpc = 0;
6178 bool isN0SExt = isSignExtended(N0, DAG);
6179 bool isN1SExt = isSignExtended(N1, DAG);
6180 if (isN0SExt && isN1SExt)
6181 NewOpc = ARMISD::VMULLs;
6183 bool isN0ZExt = isZeroExtended(N0, DAG);
6184 bool isN1ZExt = isZeroExtended(N1, DAG);
6185 if (isN0ZExt && isN1ZExt)
6186 NewOpc = ARMISD::VMULLu;
6187 else if (isN1SExt || isN1ZExt) {
6188 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6189 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6190 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6191 NewOpc = ARMISD::VMULLs;
6193 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6194 NewOpc = ARMISD::VMULLu;
6196 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6198 NewOpc = ARMISD::VMULLu;
6204 if (VT == MVT::v2i64)
6205 // Fall through to expand this. It is not legal.
6208 // Other vector multiplications are legal.
6213 // Legalize to a VMULL instruction.
6216 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6218 Op0 = SkipExtensionForVMULL(N0, DAG);
6219 assert(Op0.getValueType().is64BitVector() &&
6220 Op1.getValueType().is64BitVector() &&
6221 "unexpected types for extended operands to VMULL");
6222 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6225 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6226 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6233 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6234 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6235 EVT Op1VT = Op1.getValueType();
6236 return DAG.getNode(N0->getOpcode(), DL, VT,
6237 DAG.getNode(NewOpc, DL, VT,
6238 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6239 DAG.getNode(NewOpc, DL, VT,
6240 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6244 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6246 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6247 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6248 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6249 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6250 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6251 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6252 // Get reciprocal estimate.
6253 // float4 recip = vrecpeq_f32(yf);
6254 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6255 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6257 // Because char has a smaller range than uchar, we can actually get away
6258 // without any newton steps. This requires that we use a weird bias
6259 // of 0xb000, however (again, this has been exhaustively tested).
6260 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6261 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6262 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6263 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6264 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6265 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6266 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6267 // Convert back to short.
6268 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6269 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6274 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6276 // Convert to float.
6277 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6278 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6279 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6280 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6281 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6282 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6284 // Use reciprocal estimate and one refinement step.
6285 // float4 recip = vrecpeq_f32(yf);
6286 // recip *= vrecpsq_f32(yf, recip);
6287 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6288 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6290 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6291 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6293 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6294 // Because short has a smaller range than ushort, we can actually get away
6295 // with only a single newton step. This requires that we use a weird bias
6296 // of 89, however (again, this has been exhaustively tested).
6297 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6298 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6299 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6300 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6301 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6302 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6303 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6304 // Convert back to integer and return.
6305 // return vmovn_s32(vcvt_s32_f32(result));
6306 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6307 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6311 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6312 EVT VT = Op.getValueType();
6313 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6314 "unexpected type for custom-lowering ISD::SDIV");
6317 SDValue N0 = Op.getOperand(0);
6318 SDValue N1 = Op.getOperand(1);
6321 if (VT == MVT::v8i8) {
6322 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6323 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6325 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6326 DAG.getIntPtrConstant(4, dl));
6327 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6328 DAG.getIntPtrConstant(4, dl));
6329 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6330 DAG.getIntPtrConstant(0, dl));
6331 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6332 DAG.getIntPtrConstant(0, dl));
6334 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6335 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6337 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6338 N0 = LowerCONCAT_VECTORS(N0, DAG);
6340 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6343 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6346 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6347 EVT VT = Op.getValueType();
6348 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6349 "unexpected type for custom-lowering ISD::UDIV");
6352 SDValue N0 = Op.getOperand(0);
6353 SDValue N1 = Op.getOperand(1);
6356 if (VT == MVT::v8i8) {
6357 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6358 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6360 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6361 DAG.getIntPtrConstant(4, dl));
6362 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6363 DAG.getIntPtrConstant(4, dl));
6364 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6365 DAG.getIntPtrConstant(0, dl));
6366 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6367 DAG.getIntPtrConstant(0, dl));
6369 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6370 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6372 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6373 N0 = LowerCONCAT_VECTORS(N0, DAG);
6375 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6376 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6382 // v4i16 sdiv ... Convert to float.
6383 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6384 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6385 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6386 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6387 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6388 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6390 // Use reciprocal estimate and two refinement steps.
6391 // float4 recip = vrecpeq_f32(yf);
6392 // recip *= vrecpsq_f32(yf, recip);
6393 // recip *= vrecpsq_f32(yf, recip);
6394 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6395 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6397 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6398 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6400 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6401 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6402 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6404 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6405 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6406 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6407 // and that it will never cause us to return an answer too large).
6408 // float4 result = as_float4(as_int4(xf*recip) + 2);
6409 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6410 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6411 N1 = DAG.getConstant(2, dl, MVT::i32);
6412 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6413 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6414 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6415 // Convert back to integer and return.
6416 // return vmovn_u32(vcvt_s32_f32(result));
6417 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6418 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6422 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6423 EVT VT = Op.getNode()->getValueType(0);
6424 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6427 bool ExtraOp = false;
6428 switch (Op.getOpcode()) {
6429 default: llvm_unreachable("Invalid code");
6430 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6431 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6432 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6433 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6437 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6439 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6440 Op.getOperand(1), Op.getOperand(2));
6443 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6444 assert(Subtarget->isTargetDarwin());
6446 // For iOS, we want to call an alternative entry point: __sincos_stret,
6447 // return values are passed via sret.
6449 SDValue Arg = Op.getOperand(0);
6450 EVT ArgVT = Arg.getValueType();
6451 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6452 auto PtrVT = getPointerTy(DAG.getDataLayout());
6454 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6456 // Pair of floats / doubles used to pass the result.
6457 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6459 // Create stack object for sret.
6460 auto &DL = DAG.getDataLayout();
6461 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6462 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6463 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6464 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6470 Entry.Ty = RetTy->getPointerTo();
6471 Entry.isSExt = false;
6472 Entry.isZExt = false;
6473 Entry.isSRet = true;
6474 Args.push_back(Entry);
6478 Entry.isSExt = false;
6479 Entry.isZExt = false;
6480 Args.push_back(Entry);
6482 const char *LibcallName = (ArgVT == MVT::f64)
6483 ? "__sincos_stret" : "__sincosf_stret";
6484 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6486 TargetLowering::CallLoweringInfo CLI(DAG);
6487 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6488 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6490 .setDiscardResult();
6492 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6494 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6495 MachinePointerInfo(), false, false, false, 0);
6497 // Address of cos field.
6498 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6499 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6500 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6501 MachinePointerInfo(), false, false, false, 0);
6503 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6504 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6505 LoadSin.getValue(0), LoadCos.getValue(0));
6508 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6509 // Monotonic load/store is legal for all targets
6510 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6513 // Acquire/Release load/store is not legal for targets without a
6514 // dmb or equivalent available.
6518 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6519 SmallVectorImpl<SDValue> &Results,
6521 const ARMSubtarget *Subtarget) {
6523 SDValue Cycles32, OutChain;
6525 if (Subtarget->hasPerfMon()) {
6526 // Under Power Management extensions, the cycle-count is:
6527 // mrc p15, #0, <Rt>, c9, c13, #0
6528 SDValue Ops[] = { N->getOperand(0), // Chain
6529 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6530 DAG.getConstant(15, DL, MVT::i32),
6531 DAG.getConstant(0, DL, MVT::i32),
6532 DAG.getConstant(9, DL, MVT::i32),
6533 DAG.getConstant(13, DL, MVT::i32),
6534 DAG.getConstant(0, DL, MVT::i32)
6537 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6538 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6539 OutChain = Cycles32.getValue(1);
6541 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6542 // there are older ARM CPUs that have implementation-specific ways of
6543 // obtaining this information (FIXME!).
6544 Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6545 OutChain = DAG.getEntryNode();
6549 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6550 Cycles32, DAG.getConstant(0, DL, MVT::i32));
6551 Results.push_back(Cycles64);
6552 Results.push_back(OutChain);
6555 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6556 switch (Op.getOpcode()) {
6557 default: llvm_unreachable("Don't know how to custom lower this!");
6558 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6559 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6560 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6561 case ISD::GlobalAddress:
6562 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6563 default: llvm_unreachable("unknown object format");
6565 return LowerGlobalAddressWindows(Op, DAG);
6567 return LowerGlobalAddressELF(Op, DAG);
6569 return LowerGlobalAddressDarwin(Op, DAG);
6571 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6572 case ISD::SELECT: return LowerSELECT(Op, DAG);
6573 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6574 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6575 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6576 case ISD::VASTART: return LowerVASTART(Op, DAG);
6577 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6578 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6579 case ISD::SINT_TO_FP:
6580 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6581 case ISD::FP_TO_SINT:
6582 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6583 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6584 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6585 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6586 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6587 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6588 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6589 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6590 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6592 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6595 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6596 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6597 case ISD::SRL_PARTS:
6598 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6600 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6601 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6602 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6603 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6604 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6605 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6606 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6607 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6608 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6609 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6610 case ISD::MUL: return LowerMUL(Op, DAG);
6611 case ISD::SDIV: return LowerSDIV(Op, DAG);
6612 case ISD::UDIV: return LowerUDIV(Op, DAG);
6616 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6621 return LowerXALUO(Op, DAG);
6622 case ISD::ATOMIC_LOAD:
6623 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6624 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6626 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6627 case ISD::DYNAMIC_STACKALLOC:
6628 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6629 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6630 llvm_unreachable("Don't know how to custom lower this!");
6631 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6632 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6636 /// ReplaceNodeResults - Replace the results of node with an illegal result
6637 /// type with new values built out of custom code.
6638 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6639 SmallVectorImpl<SDValue>&Results,
6640 SelectionDAG &DAG) const {
6642 switch (N->getOpcode()) {
6644 llvm_unreachable("Don't know how to custom expand this!");
6645 case ISD::READ_REGISTER:
6646 ExpandREAD_REGISTER(N, Results, DAG);
6649 Res = ExpandBITCAST(N, DAG);
6653 Res = Expand64BitShift(N, DAG, Subtarget);
6655 case ISD::READCYCLECOUNTER:
6656 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6660 Results.push_back(Res);
6663 //===----------------------------------------------------------------------===//
6664 // ARM Scheduler Hooks
6665 //===----------------------------------------------------------------------===//
6667 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6668 /// registers the function context.
6669 void ARMTargetLowering::
6670 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6671 MachineBasicBlock *DispatchBB, int FI) const {
6672 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6673 DebugLoc dl = MI->getDebugLoc();
6674 MachineFunction *MF = MBB->getParent();
6675 MachineRegisterInfo *MRI = &MF->getRegInfo();
6676 MachineConstantPool *MCP = MF->getConstantPool();
6677 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6678 const Function *F = MF->getFunction();
6680 bool isThumb = Subtarget->isThumb();
6681 bool isThumb2 = Subtarget->isThumb2();
6683 unsigned PCLabelId = AFI->createPICLabelUId();
6684 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6685 ARMConstantPoolValue *CPV =
6686 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6687 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6689 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6690 : &ARM::GPRRegClass;
6692 // Grab constant pool and fixed stack memory operands.
6693 MachineMemOperand *CPMMO =
6694 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6695 MachineMemOperand::MOLoad, 4, 4);
6697 MachineMemOperand *FIMMOSt =
6698 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6699 MachineMemOperand::MOStore, 4, 4);
6701 // Load the address of the dispatch MBB into the jump buffer.
6703 // Incoming value: jbuf
6704 // ldr.n r5, LCPI1_1
6707 // str r5, [$jbuf, #+4] ; &jbuf[1]
6708 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6709 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6710 .addConstantPoolIndex(CPI)
6711 .addMemOperand(CPMMO));
6712 // Set the low bit because of thumb mode.
6713 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6715 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6716 .addReg(NewVReg1, RegState::Kill)
6718 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6719 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6720 .addReg(NewVReg2, RegState::Kill)
6722 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6723 .addReg(NewVReg3, RegState::Kill)
6725 .addImm(36) // &jbuf[1] :: pc
6726 .addMemOperand(FIMMOSt));
6727 } else if (isThumb) {
6728 // Incoming value: jbuf
6729 // ldr.n r1, LCPI1_4
6733 // add r2, $jbuf, #+4 ; &jbuf[1]
6735 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6736 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6737 .addConstantPoolIndex(CPI)
6738 .addMemOperand(CPMMO));
6739 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6740 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6741 .addReg(NewVReg1, RegState::Kill)
6743 // Set the low bit because of thumb mode.
6744 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6745 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6746 .addReg(ARM::CPSR, RegState::Define)
6748 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6749 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6750 .addReg(ARM::CPSR, RegState::Define)
6751 .addReg(NewVReg2, RegState::Kill)
6752 .addReg(NewVReg3, RegState::Kill));
6753 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6754 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6756 .addImm(36); // &jbuf[1] :: pc
6757 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6758 .addReg(NewVReg4, RegState::Kill)
6759 .addReg(NewVReg5, RegState::Kill)
6761 .addMemOperand(FIMMOSt));
6763 // Incoming value: jbuf
6766 // str r1, [$jbuf, #+4] ; &jbuf[1]
6767 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6768 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6769 .addConstantPoolIndex(CPI)
6771 .addMemOperand(CPMMO));
6772 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6773 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6774 .addReg(NewVReg1, RegState::Kill)
6775 .addImm(PCLabelId));
6776 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6777 .addReg(NewVReg2, RegState::Kill)
6779 .addImm(36) // &jbuf[1] :: pc
6780 .addMemOperand(FIMMOSt));
6784 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6785 MachineBasicBlock *MBB) const {
6786 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6787 DebugLoc dl = MI->getDebugLoc();
6788 MachineFunction *MF = MBB->getParent();
6789 MachineRegisterInfo *MRI = &MF->getRegInfo();
6790 MachineFrameInfo *MFI = MF->getFrameInfo();
6791 int FI = MFI->getFunctionContextIndex();
6793 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6794 : &ARM::GPRnopcRegClass;
6796 // Get a mapping of the call site numbers to all of the landing pads they're
6798 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6799 unsigned MaxCSNum = 0;
6800 MachineModuleInfo &MMI = MF->getMMI();
6801 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6803 if (!BB->isLandingPad()) continue;
6805 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6807 for (MachineBasicBlock::iterator
6808 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6809 if (!II->isEHLabel()) continue;
6811 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6812 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6814 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6815 for (SmallVectorImpl<unsigned>::iterator
6816 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6817 CSI != CSE; ++CSI) {
6818 CallSiteNumToLPad[*CSI].push_back(BB);
6819 MaxCSNum = std::max(MaxCSNum, *CSI);
6825 // Get an ordered list of the machine basic blocks for the jump table.
6826 std::vector<MachineBasicBlock*> LPadList;
6827 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6828 LPadList.reserve(CallSiteNumToLPad.size());
6829 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6830 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6831 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6832 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6833 LPadList.push_back(*II);
6834 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6838 assert(!LPadList.empty() &&
6839 "No landing pad destinations for the dispatch jump table!");
6841 // Create the jump table and associated information.
6842 MachineJumpTableInfo *JTI =
6843 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6844 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6845 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6847 // Create the MBBs for the dispatch code.
6849 // Shove the dispatch's address into the return slot in the function context.
6850 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6851 DispatchBB->setIsLandingPad();
6853 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6854 unsigned trap_opcode;
6855 if (Subtarget->isThumb())
6856 trap_opcode = ARM::tTRAP;
6858 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6860 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6861 DispatchBB->addSuccessor(TrapBB);
6863 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6864 DispatchBB->addSuccessor(DispContBB);
6867 MF->insert(MF->end(), DispatchBB);
6868 MF->insert(MF->end(), DispContBB);
6869 MF->insert(MF->end(), TrapBB);
6871 // Insert code into the entry block that creates and registers the function
6873 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6875 MachineMemOperand *FIMMOLd =
6876 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6877 MachineMemOperand::MOLoad |
6878 MachineMemOperand::MOVolatile, 4, 4);
6880 MachineInstrBuilder MIB;
6881 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6883 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6884 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6886 // Add a register mask with no preserved registers. This results in all
6887 // registers being marked as clobbered.
6888 MIB.addRegMask(RI.getNoPreservedMask());
6890 unsigned NumLPads = LPadList.size();
6891 if (Subtarget->isThumb2()) {
6892 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6893 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6896 .addMemOperand(FIMMOLd));
6898 if (NumLPads < 256) {
6899 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6901 .addImm(LPadList.size()));
6903 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6904 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6905 .addImm(NumLPads & 0xFFFF));
6907 unsigned VReg2 = VReg1;
6908 if ((NumLPads & 0xFFFF0000) != 0) {
6909 VReg2 = MRI->createVirtualRegister(TRC);
6910 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6912 .addImm(NumLPads >> 16));
6915 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6920 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6925 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6926 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6927 .addJumpTableIndex(MJTI));
6929 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6932 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6933 .addReg(NewVReg3, RegState::Kill)
6935 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6937 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6938 .addReg(NewVReg4, RegState::Kill)
6940 .addJumpTableIndex(MJTI);
6941 } else if (Subtarget->isThumb()) {
6942 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6943 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6946 .addMemOperand(FIMMOLd));
6948 if (NumLPads < 256) {
6949 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6953 MachineConstantPool *ConstantPool = MF->getConstantPool();
6954 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6955 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6957 // MachineConstantPool wants an explicit alignment.
6958 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
6960 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
6961 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6963 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6964 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6965 .addReg(VReg1, RegState::Define)
6966 .addConstantPoolIndex(Idx));
6967 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6972 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6977 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6978 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6979 .addReg(ARM::CPSR, RegState::Define)
6983 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6984 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6985 .addJumpTableIndex(MJTI));
6987 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6988 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6989 .addReg(ARM::CPSR, RegState::Define)
6990 .addReg(NewVReg2, RegState::Kill)
6993 MachineMemOperand *JTMMOLd =
6994 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6995 MachineMemOperand::MOLoad, 4, 4);
6997 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6998 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6999 .addReg(NewVReg4, RegState::Kill)
7001 .addMemOperand(JTMMOLd));
7003 unsigned NewVReg6 = NewVReg5;
7004 if (RelocM == Reloc::PIC_) {
7005 NewVReg6 = MRI->createVirtualRegister(TRC);
7006 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7007 .addReg(ARM::CPSR, RegState::Define)
7008 .addReg(NewVReg5, RegState::Kill)
7012 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7013 .addReg(NewVReg6, RegState::Kill)
7014 .addJumpTableIndex(MJTI);
7016 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7017 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7020 .addMemOperand(FIMMOLd));
7022 if (NumLPads < 256) {
7023 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7026 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7027 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7028 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7029 .addImm(NumLPads & 0xFFFF));
7031 unsigned VReg2 = VReg1;
7032 if ((NumLPads & 0xFFFF0000) != 0) {
7033 VReg2 = MRI->createVirtualRegister(TRC);
7034 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7036 .addImm(NumLPads >> 16));
7039 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7043 MachineConstantPool *ConstantPool = MF->getConstantPool();
7044 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7045 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7047 // MachineConstantPool wants an explicit alignment.
7048 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7050 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7051 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7053 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7054 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7055 .addReg(VReg1, RegState::Define)
7056 .addConstantPoolIndex(Idx)
7058 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7060 .addReg(VReg1, RegState::Kill));
7063 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7068 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7070 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7072 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7073 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7074 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7075 .addJumpTableIndex(MJTI));
7077 MachineMemOperand *JTMMOLd =
7078 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7079 MachineMemOperand::MOLoad, 4, 4);
7080 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7082 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7083 .addReg(NewVReg3, RegState::Kill)
7086 .addMemOperand(JTMMOLd));
7088 if (RelocM == Reloc::PIC_) {
7089 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7090 .addReg(NewVReg5, RegState::Kill)
7092 .addJumpTableIndex(MJTI);
7094 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7095 .addReg(NewVReg5, RegState::Kill)
7096 .addJumpTableIndex(MJTI);
7100 // Add the jump table entries as successors to the MBB.
7101 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7102 for (std::vector<MachineBasicBlock*>::iterator
7103 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7104 MachineBasicBlock *CurMBB = *I;
7105 if (SeenMBBs.insert(CurMBB).second)
7106 DispContBB->addSuccessor(CurMBB);
7109 // N.B. the order the invoke BBs are processed in doesn't matter here.
7110 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7111 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7112 for (MachineBasicBlock *BB : InvokeBBs) {
7114 // Remove the landing pad successor from the invoke block and replace it
7115 // with the new dispatch block.
7116 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7118 while (!Successors.empty()) {
7119 MachineBasicBlock *SMBB = Successors.pop_back_val();
7120 if (SMBB->isLandingPad()) {
7121 BB->removeSuccessor(SMBB);
7122 MBBLPads.push_back(SMBB);
7126 BB->addSuccessor(DispatchBB);
7128 // Find the invoke call and mark all of the callee-saved registers as
7129 // 'implicit defined' so that they're spilled. This prevents code from
7130 // moving instructions to before the EH block, where they will never be
7132 for (MachineBasicBlock::reverse_iterator
7133 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7134 if (!II->isCall()) continue;
7136 DenseMap<unsigned, bool> DefRegs;
7137 for (MachineInstr::mop_iterator
7138 OI = II->operands_begin(), OE = II->operands_end();
7140 if (!OI->isReg()) continue;
7141 DefRegs[OI->getReg()] = true;
7144 MachineInstrBuilder MIB(*MF, &*II);
7146 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7147 unsigned Reg = SavedRegs[i];
7148 if (Subtarget->isThumb2() &&
7149 !ARM::tGPRRegClass.contains(Reg) &&
7150 !ARM::hGPRRegClass.contains(Reg))
7152 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7154 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7157 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7164 // Mark all former landing pads as non-landing pads. The dispatch is the only
7166 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7167 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7168 (*I)->setIsLandingPad(false);
7170 // The instruction is gone now.
7171 MI->eraseFromParent();
7175 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7176 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7177 E = MBB->succ_end(); I != E; ++I)
7180 llvm_unreachable("Expecting a BB with two successors!");
7183 /// Return the load opcode for a given load size. If load size >= 8,
7184 /// neon opcode will be returned.
7185 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7187 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7188 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7190 return LdSize == 4 ? ARM::tLDRi
7191 : LdSize == 2 ? ARM::tLDRHi
7192 : LdSize == 1 ? ARM::tLDRBi : 0;
7194 return LdSize == 4 ? ARM::t2LDR_POST
7195 : LdSize == 2 ? ARM::t2LDRH_POST
7196 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7197 return LdSize == 4 ? ARM::LDR_POST_IMM
7198 : LdSize == 2 ? ARM::LDRH_POST
7199 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7202 /// Return the store opcode for a given store size. If store size >= 8,
7203 /// neon opcode will be returned.
7204 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7206 return StSize == 16 ? ARM::VST1q32wb_fixed
7207 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7209 return StSize == 4 ? ARM::tSTRi
7210 : StSize == 2 ? ARM::tSTRHi
7211 : StSize == 1 ? ARM::tSTRBi : 0;
7213 return StSize == 4 ? ARM::t2STR_POST
7214 : StSize == 2 ? ARM::t2STRH_POST
7215 : StSize == 1 ? ARM::t2STRB_POST : 0;
7216 return StSize == 4 ? ARM::STR_POST_IMM
7217 : StSize == 2 ? ARM::STRH_POST
7218 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7221 /// Emit a post-increment load operation with given size. The instructions
7222 /// will be added to BB at Pos.
7223 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7224 const TargetInstrInfo *TII, DebugLoc dl,
7225 unsigned LdSize, unsigned Data, unsigned AddrIn,
7226 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7227 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7228 assert(LdOpc != 0 && "Should have a load opcode");
7230 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7231 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7233 } else if (IsThumb1) {
7234 // load + update AddrIn
7235 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7236 .addReg(AddrIn).addImm(0));
7237 MachineInstrBuilder MIB =
7238 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7239 MIB = AddDefaultT1CC(MIB);
7240 MIB.addReg(AddrIn).addImm(LdSize);
7241 AddDefaultPred(MIB);
7242 } else if (IsThumb2) {
7243 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7244 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7247 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7248 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7249 .addReg(0).addImm(LdSize));
7253 /// Emit a post-increment store operation with given size. The instructions
7254 /// will be added to BB at Pos.
7255 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7256 const TargetInstrInfo *TII, DebugLoc dl,
7257 unsigned StSize, unsigned Data, unsigned AddrIn,
7258 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7259 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7260 assert(StOpc != 0 && "Should have a store opcode");
7262 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7263 .addReg(AddrIn).addImm(0).addReg(Data));
7264 } else if (IsThumb1) {
7265 // store + update AddrIn
7266 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7267 .addReg(AddrIn).addImm(0));
7268 MachineInstrBuilder MIB =
7269 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7270 MIB = AddDefaultT1CC(MIB);
7271 MIB.addReg(AddrIn).addImm(StSize);
7272 AddDefaultPred(MIB);
7273 } else if (IsThumb2) {
7274 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7275 .addReg(Data).addReg(AddrIn).addImm(StSize));
7277 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7278 .addReg(Data).addReg(AddrIn).addReg(0)
7284 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7285 MachineBasicBlock *BB) const {
7286 // This pseudo instruction has 3 operands: dst, src, size
7287 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7288 // Otherwise, we will generate unrolled scalar copies.
7289 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7290 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7291 MachineFunction::iterator It = BB;
7294 unsigned dest = MI->getOperand(0).getReg();
7295 unsigned src = MI->getOperand(1).getReg();
7296 unsigned SizeVal = MI->getOperand(2).getImm();
7297 unsigned Align = MI->getOperand(3).getImm();
7298 DebugLoc dl = MI->getDebugLoc();
7300 MachineFunction *MF = BB->getParent();
7301 MachineRegisterInfo &MRI = MF->getRegInfo();
7302 unsigned UnitSize = 0;
7303 const TargetRegisterClass *TRC = nullptr;
7304 const TargetRegisterClass *VecTRC = nullptr;
7306 bool IsThumb1 = Subtarget->isThumb1Only();
7307 bool IsThumb2 = Subtarget->isThumb2();
7311 } else if (Align & 2) {
7314 // Check whether we can use NEON instructions.
7315 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7316 Subtarget->hasNEON()) {
7317 if ((Align % 16 == 0) && SizeVal >= 16)
7319 else if ((Align % 8 == 0) && SizeVal >= 8)
7322 // Can't use NEON instructions.
7327 // Select the correct opcode and register class for unit size load/store
7328 bool IsNeon = UnitSize >= 8;
7329 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7331 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7332 : UnitSize == 8 ? &ARM::DPRRegClass
7335 unsigned BytesLeft = SizeVal % UnitSize;
7336 unsigned LoopSize = SizeVal - BytesLeft;
7338 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7339 // Use LDR and STR to copy.
7340 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7341 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7342 unsigned srcIn = src;
7343 unsigned destIn = dest;
7344 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7345 unsigned srcOut = MRI.createVirtualRegister(TRC);
7346 unsigned destOut = MRI.createVirtualRegister(TRC);
7347 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7348 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7349 IsThumb1, IsThumb2);
7350 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7351 IsThumb1, IsThumb2);
7356 // Handle the leftover bytes with LDRB and STRB.
7357 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7358 // [destOut] = STRB_POST(scratch, destIn, 1)
7359 for (unsigned i = 0; i < BytesLeft; i++) {
7360 unsigned srcOut = MRI.createVirtualRegister(TRC);
7361 unsigned destOut = MRI.createVirtualRegister(TRC);
7362 unsigned scratch = MRI.createVirtualRegister(TRC);
7363 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7364 IsThumb1, IsThumb2);
7365 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7366 IsThumb1, IsThumb2);
7370 MI->eraseFromParent(); // The instruction is gone now.
7374 // Expand the pseudo op to a loop.
7377 // movw varEnd, # --> with thumb2
7379 // ldrcp varEnd, idx --> without thumb2
7380 // fallthrough --> loopMBB
7382 // PHI varPhi, varEnd, varLoop
7383 // PHI srcPhi, src, srcLoop
7384 // PHI destPhi, dst, destLoop
7385 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7386 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7387 // subs varLoop, varPhi, #UnitSize
7389 // fallthrough --> exitMBB
7391 // epilogue to handle left-over bytes
7392 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7393 // [destOut] = STRB_POST(scratch, destLoop, 1)
7394 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7395 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7396 MF->insert(It, loopMBB);
7397 MF->insert(It, exitMBB);
7399 // Transfer the remainder of BB and its successor edges to exitMBB.
7400 exitMBB->splice(exitMBB->begin(), BB,
7401 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7402 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7404 // Load an immediate to varEnd.
7405 unsigned varEnd = MRI.createVirtualRegister(TRC);
7406 if (Subtarget->useMovt(*MF)) {
7407 unsigned Vtmp = varEnd;
7408 if ((LoopSize & 0xFFFF0000) != 0)
7409 Vtmp = MRI.createVirtualRegister(TRC);
7410 AddDefaultPred(BuildMI(BB, dl,
7411 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7412 Vtmp).addImm(LoopSize & 0xFFFF));
7414 if ((LoopSize & 0xFFFF0000) != 0)
7415 AddDefaultPred(BuildMI(BB, dl,
7416 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7419 .addImm(LoopSize >> 16));
7421 MachineConstantPool *ConstantPool = MF->getConstantPool();
7422 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7423 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7425 // MachineConstantPool wants an explicit alignment.
7426 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7428 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7429 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7432 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7433 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7435 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7436 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7438 BB->addSuccessor(loopMBB);
7440 // Generate the loop body:
7441 // varPhi = PHI(varLoop, varEnd)
7442 // srcPhi = PHI(srcLoop, src)
7443 // destPhi = PHI(destLoop, dst)
7444 MachineBasicBlock *entryBB = BB;
7446 unsigned varLoop = MRI.createVirtualRegister(TRC);
7447 unsigned varPhi = MRI.createVirtualRegister(TRC);
7448 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7449 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7450 unsigned destLoop = MRI.createVirtualRegister(TRC);
7451 unsigned destPhi = MRI.createVirtualRegister(TRC);
7453 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7454 .addReg(varLoop).addMBB(loopMBB)
7455 .addReg(varEnd).addMBB(entryBB);
7456 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7457 .addReg(srcLoop).addMBB(loopMBB)
7458 .addReg(src).addMBB(entryBB);
7459 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7460 .addReg(destLoop).addMBB(loopMBB)
7461 .addReg(dest).addMBB(entryBB);
7463 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7464 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7465 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7466 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7467 IsThumb1, IsThumb2);
7468 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7469 IsThumb1, IsThumb2);
7471 // Decrement loop variable by UnitSize.
7473 MachineInstrBuilder MIB =
7474 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7475 MIB = AddDefaultT1CC(MIB);
7476 MIB.addReg(varPhi).addImm(UnitSize);
7477 AddDefaultPred(MIB);
7479 MachineInstrBuilder MIB =
7480 BuildMI(*BB, BB->end(), dl,
7481 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7482 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7483 MIB->getOperand(5).setReg(ARM::CPSR);
7484 MIB->getOperand(5).setIsDef(true);
7486 BuildMI(*BB, BB->end(), dl,
7487 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7488 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7490 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7491 BB->addSuccessor(loopMBB);
7492 BB->addSuccessor(exitMBB);
7494 // Add epilogue to handle BytesLeft.
7496 MachineInstr *StartOfExit = exitMBB->begin();
7498 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7499 // [destOut] = STRB_POST(scratch, destLoop, 1)
7500 unsigned srcIn = srcLoop;
7501 unsigned destIn = destLoop;
7502 for (unsigned i = 0; i < BytesLeft; i++) {
7503 unsigned srcOut = MRI.createVirtualRegister(TRC);
7504 unsigned destOut = MRI.createVirtualRegister(TRC);
7505 unsigned scratch = MRI.createVirtualRegister(TRC);
7506 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7507 IsThumb1, IsThumb2);
7508 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7509 IsThumb1, IsThumb2);
7514 MI->eraseFromParent(); // The instruction is gone now.
7519 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7520 MachineBasicBlock *MBB) const {
7521 const TargetMachine &TM = getTargetMachine();
7522 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7523 DebugLoc DL = MI->getDebugLoc();
7525 assert(Subtarget->isTargetWindows() &&
7526 "__chkstk is only supported on Windows");
7527 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7529 // __chkstk takes the number of words to allocate on the stack in R4, and
7530 // returns the stack adjustment in number of bytes in R4. This will not
7531 // clober any other registers (other than the obvious lr).
7533 // Although, technically, IP should be considered a register which may be
7534 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7535 // thumb-2 environment, so there is no interworking required. As a result, we
7536 // do not expect a veneer to be emitted by the linker, clobbering IP.
7538 // Each module receives its own copy of __chkstk, so no import thunk is
7539 // required, again, ensuring that IP is not clobbered.
7541 // Finally, although some linkers may theoretically provide a trampoline for
7542 // out of range calls (which is quite common due to a 32M range limitation of
7543 // branches for Thumb), we can generate the long-call version via
7544 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7547 switch (TM.getCodeModel()) {
7548 case CodeModel::Small:
7549 case CodeModel::Medium:
7550 case CodeModel::Default:
7551 case CodeModel::Kernel:
7552 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7553 .addImm((unsigned)ARMCC::AL).addReg(0)
7554 .addExternalSymbol("__chkstk")
7555 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7556 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7557 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7559 case CodeModel::Large:
7560 case CodeModel::JITDefault: {
7561 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7562 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7564 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7565 .addExternalSymbol("__chkstk");
7566 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7567 .addImm((unsigned)ARMCC::AL).addReg(0)
7568 .addReg(Reg, RegState::Kill)
7569 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7570 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7571 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7576 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7578 .addReg(ARM::SP).addReg(ARM::R4)));
7580 MI->eraseFromParent();
7585 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7586 MachineBasicBlock *BB) const {
7587 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7588 DebugLoc dl = MI->getDebugLoc();
7589 bool isThumb2 = Subtarget->isThumb2();
7590 switch (MI->getOpcode()) {
7593 llvm_unreachable("Unexpected instr type to insert");
7595 // The Thumb2 pre-indexed stores have the same MI operands, they just
7596 // define them differently in the .td files from the isel patterns, so
7597 // they need pseudos.
7598 case ARM::t2STR_preidx:
7599 MI->setDesc(TII->get(ARM::t2STR_PRE));
7601 case ARM::t2STRB_preidx:
7602 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7604 case ARM::t2STRH_preidx:
7605 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7608 case ARM::STRi_preidx:
7609 case ARM::STRBi_preidx: {
7610 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7611 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7612 // Decode the offset.
7613 unsigned Offset = MI->getOperand(4).getImm();
7614 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7615 Offset = ARM_AM::getAM2Offset(Offset);
7619 MachineMemOperand *MMO = *MI->memoperands_begin();
7620 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7621 .addOperand(MI->getOperand(0)) // Rn_wb
7622 .addOperand(MI->getOperand(1)) // Rt
7623 .addOperand(MI->getOperand(2)) // Rn
7624 .addImm(Offset) // offset (skip GPR==zero_reg)
7625 .addOperand(MI->getOperand(5)) // pred
7626 .addOperand(MI->getOperand(6))
7627 .addMemOperand(MMO);
7628 MI->eraseFromParent();
7631 case ARM::STRr_preidx:
7632 case ARM::STRBr_preidx:
7633 case ARM::STRH_preidx: {
7635 switch (MI->getOpcode()) {
7636 default: llvm_unreachable("unexpected opcode!");
7637 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7638 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7639 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7641 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7642 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7643 MIB.addOperand(MI->getOperand(i));
7644 MI->eraseFromParent();
7648 case ARM::tMOVCCr_pseudo: {
7649 // To "insert" a SELECT_CC instruction, we actually have to insert the
7650 // diamond control-flow pattern. The incoming instruction knows the
7651 // destination vreg to set, the condition code register to branch on, the
7652 // true/false values to select between, and a branch opcode to use.
7653 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7654 MachineFunction::iterator It = BB;
7660 // cmpTY ccX, r1, r2
7662 // fallthrough --> copy0MBB
7663 MachineBasicBlock *thisMBB = BB;
7664 MachineFunction *F = BB->getParent();
7665 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7666 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7667 F->insert(It, copy0MBB);
7668 F->insert(It, sinkMBB);
7670 // Transfer the remainder of BB and its successor edges to sinkMBB.
7671 sinkMBB->splice(sinkMBB->begin(), BB,
7672 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7673 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7675 BB->addSuccessor(copy0MBB);
7676 BB->addSuccessor(sinkMBB);
7678 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7679 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7682 // %FalseValue = ...
7683 // # fallthrough to sinkMBB
7686 // Update machine-CFG edges
7687 BB->addSuccessor(sinkMBB);
7690 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7693 BuildMI(*BB, BB->begin(), dl,
7694 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7695 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7696 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7698 MI->eraseFromParent(); // The pseudo instruction is gone now.
7703 case ARM::BCCZi64: {
7704 // If there is an unconditional branch to the other successor, remove it.
7705 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7707 // Compare both parts that make up the double comparison separately for
7709 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7711 unsigned LHS1 = MI->getOperand(1).getReg();
7712 unsigned LHS2 = MI->getOperand(2).getReg();
7714 AddDefaultPred(BuildMI(BB, dl,
7715 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7716 .addReg(LHS1).addImm(0));
7717 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7718 .addReg(LHS2).addImm(0)
7719 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7721 unsigned RHS1 = MI->getOperand(3).getReg();
7722 unsigned RHS2 = MI->getOperand(4).getReg();
7723 AddDefaultPred(BuildMI(BB, dl,
7724 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7725 .addReg(LHS1).addReg(RHS1));
7726 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7727 .addReg(LHS2).addReg(RHS2)
7728 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7731 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7732 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7733 if (MI->getOperand(0).getImm() == ARMCC::NE)
7734 std::swap(destMBB, exitMBB);
7736 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7737 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7739 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7741 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7743 MI->eraseFromParent(); // The pseudo instruction is gone now.
7747 case ARM::Int_eh_sjlj_setjmp:
7748 case ARM::Int_eh_sjlj_setjmp_nofp:
7749 case ARM::tInt_eh_sjlj_setjmp:
7750 case ARM::t2Int_eh_sjlj_setjmp:
7751 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7754 case ARM::Int_eh_sjlj_setup_dispatch:
7755 EmitSjLjDispatchBlock(MI, BB);
7760 // To insert an ABS instruction, we have to insert the
7761 // diamond control-flow pattern. The incoming instruction knows the
7762 // source vreg to test against 0, the destination vreg to set,
7763 // the condition code register to branch on, the
7764 // true/false values to select between, and a branch opcode to use.
7769 // BCC (branch to SinkBB if V0 >= 0)
7770 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7771 // SinkBB: V1 = PHI(V2, V3)
7772 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7773 MachineFunction::iterator BBI = BB;
7775 MachineFunction *Fn = BB->getParent();
7776 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7777 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7778 Fn->insert(BBI, RSBBB);
7779 Fn->insert(BBI, SinkBB);
7781 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7782 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7783 bool ABSSrcKIll = MI->getOperand(1).isKill();
7784 bool isThumb2 = Subtarget->isThumb2();
7785 MachineRegisterInfo &MRI = Fn->getRegInfo();
7786 // In Thumb mode S must not be specified if source register is the SP or
7787 // PC and if destination register is the SP, so restrict register class
7788 unsigned NewRsbDstReg =
7789 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7791 // Transfer the remainder of BB and its successor edges to sinkMBB.
7792 SinkBB->splice(SinkBB->begin(), BB,
7793 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7794 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7796 BB->addSuccessor(RSBBB);
7797 BB->addSuccessor(SinkBB);
7799 // fall through to SinkMBB
7800 RSBBB->addSuccessor(SinkBB);
7802 // insert a cmp at the end of BB
7803 AddDefaultPred(BuildMI(BB, dl,
7804 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7805 .addReg(ABSSrcReg).addImm(0));
7807 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7809 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7810 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7812 // insert rsbri in RSBBB
7813 // Note: BCC and rsbri will be converted into predicated rsbmi
7814 // by if-conversion pass
7815 BuildMI(*RSBBB, RSBBB->begin(), dl,
7816 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7817 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7818 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7820 // insert PHI in SinkBB,
7821 // reuse ABSDstReg to not change uses of ABS instruction
7822 BuildMI(*SinkBB, SinkBB->begin(), dl,
7823 TII->get(ARM::PHI), ABSDstReg)
7824 .addReg(NewRsbDstReg).addMBB(RSBBB)
7825 .addReg(ABSSrcReg).addMBB(BB);
7827 // remove ABS instruction
7828 MI->eraseFromParent();
7830 // return last added BB
7833 case ARM::COPY_STRUCT_BYVAL_I32:
7835 return EmitStructByval(MI, BB);
7836 case ARM::WIN__CHKSTK:
7837 return EmitLowered__chkstk(MI, BB);
7841 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7842 SDNode *Node) const {
7843 const MCInstrDesc *MCID = &MI->getDesc();
7844 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7845 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7846 // operand is still set to noreg. If needed, set the optional operand's
7847 // register to CPSR, and remove the redundant implicit def.
7849 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7851 // Rename pseudo opcodes.
7852 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7854 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7855 MCID = &TII->get(NewOpc);
7857 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7858 "converted opcode should be the same except for cc_out");
7862 // Add the optional cc_out operand
7863 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7865 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7867 // Any ARM instruction that sets the 's' bit should specify an optional
7868 // "cc_out" operand in the last operand position.
7869 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7870 assert(!NewOpc && "Optional cc_out operand required");
7873 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7874 // since we already have an optional CPSR def.
7875 bool definesCPSR = false;
7876 bool deadCPSR = false;
7877 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7879 const MachineOperand &MO = MI->getOperand(i);
7880 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7884 MI->RemoveOperand(i);
7889 assert(!NewOpc && "Optional cc_out operand required");
7892 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7894 assert(!MI->getOperand(ccOutIdx).getReg() &&
7895 "expect uninitialized optional cc_out operand");
7899 // If this instruction was defined with an optional CPSR def and its dag node
7900 // had a live implicit CPSR def, then activate the optional CPSR def.
7901 MachineOperand &MO = MI->getOperand(ccOutIdx);
7902 MO.setReg(ARM::CPSR);
7906 //===----------------------------------------------------------------------===//
7907 // ARM Optimization Hooks
7908 //===----------------------------------------------------------------------===//
7910 // Helper function that checks if N is a null or all ones constant.
7911 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7912 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7915 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7918 // Return true if N is conditionally 0 or all ones.
7919 // Detects these expressions where cc is an i1 value:
7921 // (select cc 0, y) [AllOnes=0]
7922 // (select cc y, 0) [AllOnes=0]
7923 // (zext cc) [AllOnes=0]
7924 // (sext cc) [AllOnes=0/1]
7925 // (select cc -1, y) [AllOnes=1]
7926 // (select cc y, -1) [AllOnes=1]
7928 // Invert is set when N is the null/all ones constant when CC is false.
7929 // OtherOp is set to the alternative value of N.
7930 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7931 SDValue &CC, bool &Invert,
7933 SelectionDAG &DAG) {
7934 switch (N->getOpcode()) {
7935 default: return false;
7937 CC = N->getOperand(0);
7938 SDValue N1 = N->getOperand(1);
7939 SDValue N2 = N->getOperand(2);
7940 if (isZeroOrAllOnes(N1, AllOnes)) {
7945 if (isZeroOrAllOnes(N2, AllOnes)) {
7952 case ISD::ZERO_EXTEND:
7953 // (zext cc) can never be the all ones value.
7957 case ISD::SIGN_EXTEND: {
7959 EVT VT = N->getValueType(0);
7960 CC = N->getOperand(0);
7961 if (CC.getValueType() != MVT::i1)
7965 // When looking for an AllOnes constant, N is an sext, and the 'other'
7967 OtherOp = DAG.getConstant(0, dl, VT);
7968 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7969 // When looking for a 0 constant, N can be zext or sext.
7970 OtherOp = DAG.getConstant(1, dl, VT);
7972 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7979 // Combine a constant select operand into its use:
7981 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7982 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7983 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7984 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7985 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7987 // The transform is rejected if the select doesn't have a constant operand that
7988 // is null, or all ones when AllOnes is set.
7990 // Also recognize sext/zext from i1:
7992 // (add (zext cc), x) -> (select cc (add x, 1), x)
7993 // (add (sext cc), x) -> (select cc (add x, -1), x)
7995 // These transformations eventually create predicated instructions.
7997 // @param N The node to transform.
7998 // @param Slct The N operand that is a select.
7999 // @param OtherOp The other N operand (x above).
8000 // @param DCI Context.
8001 // @param AllOnes Require the select constant to be all ones instead of null.
8002 // @returns The new node, or SDValue() on failure.
8004 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8005 TargetLowering::DAGCombinerInfo &DCI,
8006 bool AllOnes = false) {
8007 SelectionDAG &DAG = DCI.DAG;
8008 EVT VT = N->getValueType(0);
8009 SDValue NonConstantVal;
8012 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8013 NonConstantVal, DAG))
8016 // Slct is now know to be the desired identity constant when CC is true.
8017 SDValue TrueVal = OtherOp;
8018 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8019 OtherOp, NonConstantVal);
8020 // Unless SwapSelectOps says CC should be false.
8022 std::swap(TrueVal, FalseVal);
8024 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8025 CCOp, TrueVal, FalseVal);
8028 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8030 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8031 TargetLowering::DAGCombinerInfo &DCI) {
8032 SDValue N0 = N->getOperand(0);
8033 SDValue N1 = N->getOperand(1);
8034 if (N0.getNode()->hasOneUse()) {
8035 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8036 if (Result.getNode())
8039 if (N1.getNode()->hasOneUse()) {
8040 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8041 if (Result.getNode())
8047 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8048 // (only after legalization).
8049 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8050 TargetLowering::DAGCombinerInfo &DCI,
8051 const ARMSubtarget *Subtarget) {
8053 // Only perform optimization if after legalize, and if NEON is available. We
8054 // also expected both operands to be BUILD_VECTORs.
8055 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8056 || N0.getOpcode() != ISD::BUILD_VECTOR
8057 || N1.getOpcode() != ISD::BUILD_VECTOR)
8060 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8061 EVT VT = N->getValueType(0);
8062 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8065 // Check that the vector operands are of the right form.
8066 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8067 // operands, where N is the size of the formed vector.
8068 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8069 // index such that we have a pair wise add pattern.
8071 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8072 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8074 SDValue Vec = N0->getOperand(0)->getOperand(0);
8075 SDNode *V = Vec.getNode();
8076 unsigned nextIndex = 0;
8078 // For each operands to the ADD which are BUILD_VECTORs,
8079 // check to see if each of their operands are an EXTRACT_VECTOR with
8080 // the same vector and appropriate index.
8081 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8082 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8083 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8085 SDValue ExtVec0 = N0->getOperand(i);
8086 SDValue ExtVec1 = N1->getOperand(i);
8088 // First operand is the vector, verify its the same.
8089 if (V != ExtVec0->getOperand(0).getNode() ||
8090 V != ExtVec1->getOperand(0).getNode())
8093 // Second is the constant, verify its correct.
8094 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8095 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8097 // For the constant, we want to see all the even or all the odd.
8098 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8099 || C1->getZExtValue() != nextIndex+1)
8108 // Create VPADDL node.
8109 SelectionDAG &DAG = DCI.DAG;
8110 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8114 // Build operand list.
8115 SmallVector<SDValue, 8> Ops;
8116 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8117 TLI.getPointerTy(DAG.getDataLayout())));
8119 // Input is the vector.
8122 // Get widened type and narrowed type.
8124 unsigned numElem = VT.getVectorNumElements();
8126 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8127 switch (inputLaneType.getSimpleVT().SimpleTy) {
8128 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8129 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8130 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8132 llvm_unreachable("Invalid vector element type for padd optimization.");
8135 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8136 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8137 return DAG.getNode(ExtOp, dl, VT, tmp);
8140 static SDValue findMUL_LOHI(SDValue V) {
8141 if (V->getOpcode() == ISD::UMUL_LOHI ||
8142 V->getOpcode() == ISD::SMUL_LOHI)
8147 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8148 TargetLowering::DAGCombinerInfo &DCI,
8149 const ARMSubtarget *Subtarget) {
8151 if (Subtarget->isThumb1Only()) return SDValue();
8153 // Only perform the checks after legalize when the pattern is available.
8154 if (DCI.isBeforeLegalize()) return SDValue();
8156 // Look for multiply add opportunities.
8157 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8158 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8159 // a glue link from the first add to the second add.
8160 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8161 // a S/UMLAL instruction.
8164 // / \ [no multiline comment]
8170 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8171 SDValue AddcOp0 = AddcNode->getOperand(0);
8172 SDValue AddcOp1 = AddcNode->getOperand(1);
8174 // Check if the two operands are from the same mul_lohi node.
8175 if (AddcOp0.getNode() == AddcOp1.getNode())
8178 assert(AddcNode->getNumValues() == 2 &&
8179 AddcNode->getValueType(0) == MVT::i32 &&
8180 "Expect ADDC with two result values. First: i32");
8182 // Check that we have a glued ADDC node.
8183 if (AddcNode->getValueType(1) != MVT::Glue)
8186 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8187 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8188 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8189 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8190 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8193 // Look for the glued ADDE.
8194 SDNode* AddeNode = AddcNode->getGluedUser();
8198 // Make sure it is really an ADDE.
8199 if (AddeNode->getOpcode() != ISD::ADDE)
8202 assert(AddeNode->getNumOperands() == 3 &&
8203 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8204 "ADDE node has the wrong inputs");
8206 // Check for the triangle shape.
8207 SDValue AddeOp0 = AddeNode->getOperand(0);
8208 SDValue AddeOp1 = AddeNode->getOperand(1);
8210 // Make sure that the ADDE operands are not coming from the same node.
8211 if (AddeOp0.getNode() == AddeOp1.getNode())
8214 // Find the MUL_LOHI node walking up ADDE's operands.
8215 bool IsLeftOperandMUL = false;
8216 SDValue MULOp = findMUL_LOHI(AddeOp0);
8217 if (MULOp == SDValue())
8218 MULOp = findMUL_LOHI(AddeOp1);
8220 IsLeftOperandMUL = true;
8221 if (MULOp == SDValue())
8224 // Figure out the right opcode.
8225 unsigned Opc = MULOp->getOpcode();
8226 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8228 // Figure out the high and low input values to the MLAL node.
8229 SDValue* HiAdd = nullptr;
8230 SDValue* LoMul = nullptr;
8231 SDValue* LowAdd = nullptr;
8233 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8234 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8237 if (IsLeftOperandMUL)
8243 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8244 // whose low result is fed to the ADDC we are checking.
8246 if (AddcOp0 == MULOp.getValue(0)) {
8250 if (AddcOp1 == MULOp.getValue(0)) {
8258 // Create the merged node.
8259 SelectionDAG &DAG = DCI.DAG;
8261 // Build operand list.
8262 SmallVector<SDValue, 8> Ops;
8263 Ops.push_back(LoMul->getOperand(0));
8264 Ops.push_back(LoMul->getOperand(1));
8265 Ops.push_back(*LowAdd);
8266 Ops.push_back(*HiAdd);
8268 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8269 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8271 // Replace the ADDs' nodes uses by the MLA node's values.
8272 SDValue HiMLALResult(MLALNode.getNode(), 1);
8273 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8275 SDValue LoMLALResult(MLALNode.getNode(), 0);
8276 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8278 // Return original node to notify the driver to stop replacing.
8279 SDValue resNode(AddcNode, 0);
8283 /// PerformADDCCombine - Target-specific dag combine transform from
8284 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8285 static SDValue PerformADDCCombine(SDNode *N,
8286 TargetLowering::DAGCombinerInfo &DCI,
8287 const ARMSubtarget *Subtarget) {
8289 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8293 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8294 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8295 /// called with the default operands, and if that fails, with commuted
8297 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8298 TargetLowering::DAGCombinerInfo &DCI,
8299 const ARMSubtarget *Subtarget){
8301 // Attempt to create vpaddl for this add.
8302 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8303 if (Result.getNode())
8306 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8307 if (N0.getNode()->hasOneUse()) {
8308 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8309 if (Result.getNode()) return Result;
8314 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8316 static SDValue PerformADDCombine(SDNode *N,
8317 TargetLowering::DAGCombinerInfo &DCI,
8318 const ARMSubtarget *Subtarget) {
8319 SDValue N0 = N->getOperand(0);
8320 SDValue N1 = N->getOperand(1);
8322 // First try with the default operand order.
8323 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8324 if (Result.getNode())
8327 // If that didn't work, try again with the operands commuted.
8328 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8331 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8333 static SDValue PerformSUBCombine(SDNode *N,
8334 TargetLowering::DAGCombinerInfo &DCI) {
8335 SDValue N0 = N->getOperand(0);
8336 SDValue N1 = N->getOperand(1);
8338 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8339 if (N1.getNode()->hasOneUse()) {
8340 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8341 if (Result.getNode()) return Result;
8347 /// PerformVMULCombine
8348 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8349 /// special multiplier accumulator forwarding.
8355 // However, for (A + B) * (A + B),
8362 static SDValue PerformVMULCombine(SDNode *N,
8363 TargetLowering::DAGCombinerInfo &DCI,
8364 const ARMSubtarget *Subtarget) {
8365 if (!Subtarget->hasVMLxForwarding())
8368 SelectionDAG &DAG = DCI.DAG;
8369 SDValue N0 = N->getOperand(0);
8370 SDValue N1 = N->getOperand(1);
8371 unsigned Opcode = N0.getOpcode();
8372 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8373 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8374 Opcode = N1.getOpcode();
8375 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8376 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8384 EVT VT = N->getValueType(0);
8386 SDValue N00 = N0->getOperand(0);
8387 SDValue N01 = N0->getOperand(1);
8388 return DAG.getNode(Opcode, DL, VT,
8389 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8390 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8393 static SDValue PerformMULCombine(SDNode *N,
8394 TargetLowering::DAGCombinerInfo &DCI,
8395 const ARMSubtarget *Subtarget) {
8396 SelectionDAG &DAG = DCI.DAG;
8398 if (Subtarget->isThumb1Only())
8401 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8404 EVT VT = N->getValueType(0);
8405 if (VT.is64BitVector() || VT.is128BitVector())
8406 return PerformVMULCombine(N, DCI, Subtarget);
8410 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8414 int64_t MulAmt = C->getSExtValue();
8415 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8417 ShiftAmt = ShiftAmt & (32 - 1);
8418 SDValue V = N->getOperand(0);
8422 MulAmt >>= ShiftAmt;
8425 if (isPowerOf2_32(MulAmt - 1)) {
8426 // (mul x, 2^N + 1) => (add (shl x, N), x)
8427 Res = DAG.getNode(ISD::ADD, DL, VT,
8429 DAG.getNode(ISD::SHL, DL, VT,
8431 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8433 } else if (isPowerOf2_32(MulAmt + 1)) {
8434 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8435 Res = DAG.getNode(ISD::SUB, DL, VT,
8436 DAG.getNode(ISD::SHL, DL, VT,
8438 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8444 uint64_t MulAmtAbs = -MulAmt;
8445 if (isPowerOf2_32(MulAmtAbs + 1)) {
8446 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8447 Res = DAG.getNode(ISD::SUB, DL, VT,
8449 DAG.getNode(ISD::SHL, DL, VT,
8451 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8453 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8454 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8455 Res = DAG.getNode(ISD::ADD, DL, VT,
8457 DAG.getNode(ISD::SHL, DL, VT,
8459 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8461 Res = DAG.getNode(ISD::SUB, DL, VT,
8462 DAG.getConstant(0, DL, MVT::i32), Res);
8469 Res = DAG.getNode(ISD::SHL, DL, VT,
8470 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8472 // Do not add new nodes to DAG combiner worklist.
8473 DCI.CombineTo(N, Res, false);
8477 static SDValue PerformANDCombine(SDNode *N,
8478 TargetLowering::DAGCombinerInfo &DCI,
8479 const ARMSubtarget *Subtarget) {
8481 // Attempt to use immediate-form VBIC
8482 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8484 EVT VT = N->getValueType(0);
8485 SelectionDAG &DAG = DCI.DAG;
8487 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8490 APInt SplatBits, SplatUndef;
8491 unsigned SplatBitSize;
8494 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8495 if (SplatBitSize <= 64) {
8497 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8498 SplatUndef.getZExtValue(), SplatBitSize,
8499 DAG, dl, VbicVT, VT.is128BitVector(),
8501 if (Val.getNode()) {
8503 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8504 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8505 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8510 if (!Subtarget->isThumb1Only()) {
8511 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8512 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8513 if (Result.getNode())
8520 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8521 static SDValue PerformORCombine(SDNode *N,
8522 TargetLowering::DAGCombinerInfo &DCI,
8523 const ARMSubtarget *Subtarget) {
8524 // Attempt to use immediate-form VORR
8525 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8527 EVT VT = N->getValueType(0);
8528 SelectionDAG &DAG = DCI.DAG;
8530 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8533 APInt SplatBits, SplatUndef;
8534 unsigned SplatBitSize;
8536 if (BVN && Subtarget->hasNEON() &&
8537 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8538 if (SplatBitSize <= 64) {
8540 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8541 SplatUndef.getZExtValue(), SplatBitSize,
8542 DAG, dl, VorrVT, VT.is128BitVector(),
8544 if (Val.getNode()) {
8546 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8547 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8548 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8553 if (!Subtarget->isThumb1Only()) {
8554 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8555 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8556 if (Result.getNode())
8560 // The code below optimizes (or (and X, Y), Z).
8561 // The AND operand needs to have a single user to make these optimizations
8563 SDValue N0 = N->getOperand(0);
8564 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8566 SDValue N1 = N->getOperand(1);
8568 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8569 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8570 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8572 unsigned SplatBitSize;
8575 APInt SplatBits0, SplatBits1;
8576 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8577 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8578 // Ensure that the second operand of both ands are constants
8579 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8580 HasAnyUndefs) && !HasAnyUndefs) {
8581 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8582 HasAnyUndefs) && !HasAnyUndefs) {
8583 // Ensure that the bit width of the constants are the same and that
8584 // the splat arguments are logical inverses as per the pattern we
8585 // are trying to simplify.
8586 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8587 SplatBits0 == ~SplatBits1) {
8588 // Canonicalize the vector type to make instruction selection
8590 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8591 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8595 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8601 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8604 // BFI is only available on V6T2+
8605 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8609 // 1) or (and A, mask), val => ARMbfi A, val, mask
8610 // iff (val & mask) == val
8612 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8613 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8614 // && mask == ~mask2
8615 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8616 // && ~mask == mask2
8617 // (i.e., copy a bitfield value into another bitfield of the same width)
8622 SDValue N00 = N0.getOperand(0);
8624 // The value and the mask need to be constants so we can verify this is
8625 // actually a bitfield set. If the mask is 0xffff, we can do better
8626 // via a movt instruction, so don't use BFI in that case.
8627 SDValue MaskOp = N0.getOperand(1);
8628 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8631 unsigned Mask = MaskC->getZExtValue();
8635 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8636 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8638 unsigned Val = N1C->getZExtValue();
8639 if ((Val & ~Mask) != Val)
8642 if (ARM::isBitFieldInvertedMask(Mask)) {
8643 Val >>= countTrailingZeros(~Mask);
8645 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8646 DAG.getConstant(Val, DL, MVT::i32),
8647 DAG.getConstant(Mask, DL, MVT::i32));
8649 // Do not add new nodes to DAG combiner worklist.
8650 DCI.CombineTo(N, Res, false);
8653 } else if (N1.getOpcode() == ISD::AND) {
8654 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8655 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8658 unsigned Mask2 = N11C->getZExtValue();
8660 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8662 if (ARM::isBitFieldInvertedMask(Mask) &&
8664 // The pack halfword instruction works better for masks that fit it,
8665 // so use that when it's available.
8666 if (Subtarget->hasT2ExtractPack() &&
8667 (Mask == 0xffff || Mask == 0xffff0000))
8670 unsigned amt = countTrailingZeros(Mask2);
8671 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8672 DAG.getConstant(amt, DL, MVT::i32));
8673 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8674 DAG.getConstant(Mask, DL, MVT::i32));
8675 // Do not add new nodes to DAG combiner worklist.
8676 DCI.CombineTo(N, Res, false);
8678 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8680 // The pack halfword instruction works better for masks that fit it,
8681 // so use that when it's available.
8682 if (Subtarget->hasT2ExtractPack() &&
8683 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8686 unsigned lsb = countTrailingZeros(Mask);
8687 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8688 DAG.getConstant(lsb, DL, MVT::i32));
8689 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8690 DAG.getConstant(Mask2, DL, MVT::i32));
8691 // Do not add new nodes to DAG combiner worklist.
8692 DCI.CombineTo(N, Res, false);
8697 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8698 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8699 ARM::isBitFieldInvertedMask(~Mask)) {
8700 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8701 // where lsb(mask) == #shamt and masked bits of B are known zero.
8702 SDValue ShAmt = N00.getOperand(1);
8703 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8704 unsigned LSB = countTrailingZeros(Mask);
8708 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8709 DAG.getConstant(~Mask, DL, MVT::i32));
8711 // Do not add new nodes to DAG combiner worklist.
8712 DCI.CombineTo(N, Res, false);
8718 static SDValue PerformXORCombine(SDNode *N,
8719 TargetLowering::DAGCombinerInfo &DCI,
8720 const ARMSubtarget *Subtarget) {
8721 EVT VT = N->getValueType(0);
8722 SelectionDAG &DAG = DCI.DAG;
8724 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8727 if (!Subtarget->isThumb1Only()) {
8728 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8729 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8730 if (Result.getNode())
8737 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8738 /// the bits being cleared by the AND are not demanded by the BFI.
8739 static SDValue PerformBFICombine(SDNode *N,
8740 TargetLowering::DAGCombinerInfo &DCI) {
8741 SDValue N1 = N->getOperand(1);
8742 if (N1.getOpcode() == ISD::AND) {
8743 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8746 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8747 unsigned LSB = countTrailingZeros(~InvMask);
8748 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8750 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8751 "undefined behavior");
8752 unsigned Mask = (1u << Width) - 1;
8753 unsigned Mask2 = N11C->getZExtValue();
8754 if ((Mask & (~Mask2)) == 0)
8755 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8756 N->getOperand(0), N1.getOperand(0),
8762 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8763 /// ARMISD::VMOVRRD.
8764 static SDValue PerformVMOVRRDCombine(SDNode *N,
8765 TargetLowering::DAGCombinerInfo &DCI,
8766 const ARMSubtarget *Subtarget) {
8767 // vmovrrd(vmovdrr x, y) -> x,y
8768 SDValue InDouble = N->getOperand(0);
8769 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8770 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8772 // vmovrrd(load f64) -> (load i32), (load i32)
8773 SDNode *InNode = InDouble.getNode();
8774 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8775 InNode->getValueType(0) == MVT::f64 &&
8776 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8777 !cast<LoadSDNode>(InNode)->isVolatile()) {
8778 // TODO: Should this be done for non-FrameIndex operands?
8779 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8781 SelectionDAG &DAG = DCI.DAG;
8783 SDValue BasePtr = LD->getBasePtr();
8784 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8785 LD->getPointerInfo(), LD->isVolatile(),
8786 LD->isNonTemporal(), LD->isInvariant(),
8787 LD->getAlignment());
8789 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8790 DAG.getConstant(4, DL, MVT::i32));
8791 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8792 LD->getPointerInfo(), LD->isVolatile(),
8793 LD->isNonTemporal(), LD->isInvariant(),
8794 std::min(4U, LD->getAlignment() / 2));
8796 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8797 if (DCI.DAG.getDataLayout().isBigEndian())
8798 std::swap (NewLD1, NewLD2);
8799 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8806 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8807 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8808 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8809 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8810 SDValue Op0 = N->getOperand(0);
8811 SDValue Op1 = N->getOperand(1);
8812 if (Op0.getOpcode() == ISD::BITCAST)
8813 Op0 = Op0.getOperand(0);
8814 if (Op1.getOpcode() == ISD::BITCAST)
8815 Op1 = Op1.getOperand(0);
8816 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8817 Op0.getNode() == Op1.getNode() &&
8818 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8819 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8820 N->getValueType(0), Op0.getOperand(0));
8824 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8825 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8826 /// i64 vector to have f64 elements, since the value can then be loaded
8827 /// directly into a VFP register.
8828 static bool hasNormalLoadOperand(SDNode *N) {
8829 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8830 for (unsigned i = 0; i < NumElts; ++i) {
8831 SDNode *Elt = N->getOperand(i).getNode();
8832 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8838 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8839 /// ISD::BUILD_VECTOR.
8840 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8841 TargetLowering::DAGCombinerInfo &DCI,
8842 const ARMSubtarget *Subtarget) {
8843 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8844 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8845 // into a pair of GPRs, which is fine when the value is used as a scalar,
8846 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8847 SelectionDAG &DAG = DCI.DAG;
8848 if (N->getNumOperands() == 2) {
8849 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8854 // Load i64 elements as f64 values so that type legalization does not split
8855 // them up into i32 values.
8856 EVT VT = N->getValueType(0);
8857 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8860 SmallVector<SDValue, 8> Ops;
8861 unsigned NumElts = VT.getVectorNumElements();
8862 for (unsigned i = 0; i < NumElts; ++i) {
8863 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8865 // Make the DAGCombiner fold the bitcast.
8866 DCI.AddToWorklist(V.getNode());
8868 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8869 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8870 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8873 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8875 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8876 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8877 // At that time, we may have inserted bitcasts from integer to float.
8878 // If these bitcasts have survived DAGCombine, change the lowering of this
8879 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8880 // force to use floating point types.
8882 // Make sure we can change the type of the vector.
8883 // This is possible iff:
8884 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8885 // 1.1. Vector is used only once.
8886 // 1.2. Use is a bit convert to an integer type.
8887 // 2. The size of its operands are 32-bits (64-bits are not legal).
8888 EVT VT = N->getValueType(0);
8889 EVT EltVT = VT.getVectorElementType();
8891 // Check 1.1. and 2.
8892 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8895 // By construction, the input type must be float.
8896 assert(EltVT == MVT::f32 && "Unexpected type!");
8899 SDNode *Use = *N->use_begin();
8900 if (Use->getOpcode() != ISD::BITCAST ||
8901 Use->getValueType(0).isFloatingPoint())
8904 // Check profitability.
8905 // Model is, if more than half of the relevant operands are bitcast from
8906 // i32, turn the build_vector into a sequence of insert_vector_elt.
8907 // Relevant operands are everything that is not statically
8908 // (i.e., at compile time) bitcasted.
8909 unsigned NumOfBitCastedElts = 0;
8910 unsigned NumElts = VT.getVectorNumElements();
8911 unsigned NumOfRelevantElts = NumElts;
8912 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8913 SDValue Elt = N->getOperand(Idx);
8914 if (Elt->getOpcode() == ISD::BITCAST) {
8915 // Assume only bit cast to i32 will go away.
8916 if (Elt->getOperand(0).getValueType() == MVT::i32)
8917 ++NumOfBitCastedElts;
8918 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8919 // Constants are statically casted, thus do not count them as
8920 // relevant operands.
8921 --NumOfRelevantElts;
8924 // Check if more than half of the elements require a non-free bitcast.
8925 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8928 SelectionDAG &DAG = DCI.DAG;
8929 // Create the new vector type.
8930 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8931 // Check if the type is legal.
8932 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8933 if (!TLI.isTypeLegal(VecVT))
8937 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8938 // => BITCAST INSERT_VECTOR_ELT
8939 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8941 SDValue Vec = DAG.getUNDEF(VecVT);
8943 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8944 SDValue V = N->getOperand(Idx);
8945 if (V.getOpcode() == ISD::UNDEF)
8947 if (V.getOpcode() == ISD::BITCAST &&
8948 V->getOperand(0).getValueType() == MVT::i32)
8949 // Fold obvious case.
8950 V = V.getOperand(0);
8952 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8953 // Make the DAGCombiner fold the bitcasts.
8954 DCI.AddToWorklist(V.getNode());
8956 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8957 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8959 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8960 // Make the DAGCombiner fold the bitcasts.
8961 DCI.AddToWorklist(Vec.getNode());
8965 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8966 /// ISD::INSERT_VECTOR_ELT.
8967 static SDValue PerformInsertEltCombine(SDNode *N,
8968 TargetLowering::DAGCombinerInfo &DCI) {
8969 // Bitcast an i64 load inserted into a vector to f64.
8970 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8971 EVT VT = N->getValueType(0);
8972 SDNode *Elt = N->getOperand(1).getNode();
8973 if (VT.getVectorElementType() != MVT::i64 ||
8974 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8977 SelectionDAG &DAG = DCI.DAG;
8979 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8980 VT.getVectorNumElements());
8981 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8982 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8983 // Make the DAGCombiner fold the bitcasts.
8984 DCI.AddToWorklist(Vec.getNode());
8985 DCI.AddToWorklist(V.getNode());
8986 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8987 Vec, V, N->getOperand(2));
8988 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8991 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8992 /// ISD::VECTOR_SHUFFLE.
8993 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8994 // The LLVM shufflevector instruction does not require the shuffle mask
8995 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8996 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8997 // operands do not match the mask length, they are extended by concatenating
8998 // them with undef vectors. That is probably the right thing for other
8999 // targets, but for NEON it is better to concatenate two double-register
9000 // size vector operands into a single quad-register size vector. Do that
9001 // transformation here:
9002 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9003 // shuffle(concat(v1, v2), undef)
9004 SDValue Op0 = N->getOperand(0);
9005 SDValue Op1 = N->getOperand(1);
9006 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9007 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9008 Op0.getNumOperands() != 2 ||
9009 Op1.getNumOperands() != 2)
9011 SDValue Concat0Op1 = Op0.getOperand(1);
9012 SDValue Concat1Op1 = Op1.getOperand(1);
9013 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9014 Concat1Op1.getOpcode() != ISD::UNDEF)
9016 // Skip the transformation if any of the types are illegal.
9017 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9018 EVT VT = N->getValueType(0);
9019 if (!TLI.isTypeLegal(VT) ||
9020 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9021 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9024 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9025 Op0.getOperand(0), Op1.getOperand(0));
9026 // Translate the shuffle mask.
9027 SmallVector<int, 16> NewMask;
9028 unsigned NumElts = VT.getVectorNumElements();
9029 unsigned HalfElts = NumElts/2;
9030 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9031 for (unsigned n = 0; n < NumElts; ++n) {
9032 int MaskElt = SVN->getMaskElt(n);
9034 if (MaskElt < (int)HalfElts)
9036 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9037 NewElt = HalfElts + MaskElt - NumElts;
9038 NewMask.push_back(NewElt);
9040 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9041 DAG.getUNDEF(VT), NewMask.data());
9044 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9045 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9046 /// base address updates.
9047 /// For generic load/stores, the memory type is assumed to be a vector.
9048 /// The caller is assumed to have checked legality.
9049 static SDValue CombineBaseUpdate(SDNode *N,
9050 TargetLowering::DAGCombinerInfo &DCI) {
9051 SelectionDAG &DAG = DCI.DAG;
9052 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9053 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9054 const bool isStore = N->getOpcode() == ISD::STORE;
9055 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9056 SDValue Addr = N->getOperand(AddrOpIdx);
9057 MemSDNode *MemN = cast<MemSDNode>(N);
9060 // Search for a use of the address operand that is an increment.
9061 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9062 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9064 if (User->getOpcode() != ISD::ADD ||
9065 UI.getUse().getResNo() != Addr.getResNo())
9068 // Check that the add is independent of the load/store. Otherwise, folding
9069 // it would create a cycle.
9070 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9073 // Find the new opcode for the updating load/store.
9074 bool isLoadOp = true;
9075 bool isLaneOp = false;
9076 unsigned NewOpc = 0;
9077 unsigned NumVecs = 0;
9079 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9081 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9082 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9084 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9086 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9088 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9090 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9091 NumVecs = 2; isLaneOp = true; break;
9092 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9093 NumVecs = 3; isLaneOp = true; break;
9094 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9095 NumVecs = 4; isLaneOp = true; break;
9096 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9097 NumVecs = 1; isLoadOp = false; break;
9098 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9099 NumVecs = 2; isLoadOp = false; break;
9100 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9101 NumVecs = 3; isLoadOp = false; break;
9102 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9103 NumVecs = 4; isLoadOp = false; break;
9104 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9105 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9106 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9107 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9108 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9109 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9113 switch (N->getOpcode()) {
9114 default: llvm_unreachable("unexpected opcode for Neon base update");
9115 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9116 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9117 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9118 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9119 NumVecs = 1; isLaneOp = false; break;
9120 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9121 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9125 // Find the size of memory referenced by the load/store.
9128 VecTy = N->getValueType(0);
9129 } else if (isIntrinsic) {
9130 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9132 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9133 VecTy = N->getOperand(1).getValueType();
9136 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9138 NumBytes /= VecTy.getVectorNumElements();
9140 // If the increment is a constant, it must match the memory ref size.
9141 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9142 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9143 uint64_t IncVal = CInc->getZExtValue();
9144 if (IncVal != NumBytes)
9146 } else if (NumBytes >= 3 * 16) {
9147 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9148 // separate instructions that make it harder to use a non-constant update.
9152 // OK, we found an ADD we can fold into the base update.
9153 // Now, create a _UPD node, taking care of not breaking alignment.
9155 EVT AlignedVecTy = VecTy;
9156 unsigned Alignment = MemN->getAlignment();
9158 // If this is a less-than-standard-aligned load/store, change the type to
9159 // match the standard alignment.
9160 // The alignment is overlooked when selecting _UPD variants; and it's
9161 // easier to introduce bitcasts here than fix that.
9162 // There are 3 ways to get to this base-update combine:
9163 // - intrinsics: they are assumed to be properly aligned (to the standard
9164 // alignment of the memory type), so we don't need to do anything.
9165 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9166 // intrinsics, so, likewise, there's nothing to do.
9167 // - generic load/store instructions: the alignment is specified as an
9168 // explicit operand, rather than implicitly as the standard alignment
9169 // of the memory type (like the intrisics). We need to change the
9170 // memory type to match the explicit alignment. That way, we don't
9171 // generate non-standard-aligned ARMISD::VLDx nodes.
9172 if (isa<LSBaseSDNode>(N)) {
9175 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9176 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9177 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9178 assert(!isLaneOp && "Unexpected generic load/store lane.");
9179 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9180 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9182 // Don't set an explicit alignment on regular load/stores that we want
9183 // to transform to VLD/VST 1_UPD nodes.
9184 // This matches the behavior of regular load/stores, which only get an
9185 // explicit alignment if the MMO alignment is larger than the standard
9186 // alignment of the memory type.
9187 // Intrinsics, however, always get an explicit alignment, set to the
9188 // alignment of the MMO.
9192 // Create the new updating load/store node.
9193 // First, create an SDVTList for the new updating node's results.
9195 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9197 for (n = 0; n < NumResultVecs; ++n)
9198 Tys[n] = AlignedVecTy;
9199 Tys[n++] = MVT::i32;
9200 Tys[n] = MVT::Other;
9201 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9203 // Then, gather the new node's operands.
9204 SmallVector<SDValue, 8> Ops;
9205 Ops.push_back(N->getOperand(0)); // incoming chain
9206 Ops.push_back(N->getOperand(AddrOpIdx));
9209 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9210 // Try to match the intrinsic's signature
9211 Ops.push_back(StN->getValue());
9213 // Loads (and of course intrinsics) match the intrinsics' signature,
9214 // so just add all but the alignment operand.
9215 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9216 Ops.push_back(N->getOperand(i));
9219 // For all node types, the alignment operand is always the last one.
9220 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9222 // If this is a non-standard-aligned STORE, the penultimate operand is the
9223 // stored value. Bitcast it to the aligned type.
9224 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9225 SDValue &StVal = Ops[Ops.size()-2];
9226 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9229 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9231 MemN->getMemOperand());
9234 SmallVector<SDValue, 5> NewResults;
9235 for (unsigned i = 0; i < NumResultVecs; ++i)
9236 NewResults.push_back(SDValue(UpdN.getNode(), i));
9238 // If this is an non-standard-aligned LOAD, the first result is the loaded
9239 // value. Bitcast it to the expected result type.
9240 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9241 SDValue &LdVal = NewResults[0];
9242 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9245 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9246 DCI.CombineTo(N, NewResults);
9247 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9254 static SDValue PerformVLDCombine(SDNode *N,
9255 TargetLowering::DAGCombinerInfo &DCI) {
9256 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9259 return CombineBaseUpdate(N, DCI);
9262 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9263 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9264 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9266 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9267 SelectionDAG &DAG = DCI.DAG;
9268 EVT VT = N->getValueType(0);
9269 // vldN-dup instructions only support 64-bit vectors for N > 1.
9270 if (!VT.is64BitVector())
9273 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9274 SDNode *VLD = N->getOperand(0).getNode();
9275 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9277 unsigned NumVecs = 0;
9278 unsigned NewOpc = 0;
9279 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9280 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9282 NewOpc = ARMISD::VLD2DUP;
9283 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9285 NewOpc = ARMISD::VLD3DUP;
9286 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9288 NewOpc = ARMISD::VLD4DUP;
9293 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9294 // numbers match the load.
9295 unsigned VLDLaneNo =
9296 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9297 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9299 // Ignore uses of the chain result.
9300 if (UI.getUse().getResNo() == NumVecs)
9303 if (User->getOpcode() != ARMISD::VDUPLANE ||
9304 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9308 // Create the vldN-dup node.
9311 for (n = 0; n < NumVecs; ++n)
9313 Tys[n] = MVT::Other;
9314 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9315 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9316 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9317 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9318 Ops, VLDMemInt->getMemoryVT(),
9319 VLDMemInt->getMemOperand());
9322 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9324 unsigned ResNo = UI.getUse().getResNo();
9325 // Ignore uses of the chain result.
9326 if (ResNo == NumVecs)
9329 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9332 // Now the vldN-lane intrinsic is dead except for its chain result.
9333 // Update uses of the chain.
9334 std::vector<SDValue> VLDDupResults;
9335 for (unsigned n = 0; n < NumVecs; ++n)
9336 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9337 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9338 DCI.CombineTo(VLD, VLDDupResults);
9343 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9344 /// ARMISD::VDUPLANE.
9345 static SDValue PerformVDUPLANECombine(SDNode *N,
9346 TargetLowering::DAGCombinerInfo &DCI) {
9347 SDValue Op = N->getOperand(0);
9349 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9350 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9351 if (CombineVLDDUP(N, DCI))
9352 return SDValue(N, 0);
9354 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9355 // redundant. Ignore bit_converts for now; element sizes are checked below.
9356 while (Op.getOpcode() == ISD::BITCAST)
9357 Op = Op.getOperand(0);
9358 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9361 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9362 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9363 // The canonical VMOV for a zero vector uses a 32-bit element size.
9364 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9366 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9368 EVT VT = N->getValueType(0);
9369 if (EltSize > VT.getVectorElementType().getSizeInBits())
9372 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9375 static SDValue PerformLOADCombine(SDNode *N,
9376 TargetLowering::DAGCombinerInfo &DCI) {
9377 EVT VT = N->getValueType(0);
9379 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9380 if (ISD::isNormalLoad(N) && VT.isVector() &&
9381 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9382 return CombineBaseUpdate(N, DCI);
9387 /// PerformSTORECombine - Target-specific dag combine xforms for
9389 static SDValue PerformSTORECombine(SDNode *N,
9390 TargetLowering::DAGCombinerInfo &DCI) {
9391 StoreSDNode *St = cast<StoreSDNode>(N);
9392 if (St->isVolatile())
9395 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9396 // pack all of the elements in one place. Next, store to memory in fewer
9398 SDValue StVal = St->getValue();
9399 EVT VT = StVal.getValueType();
9400 if (St->isTruncatingStore() && VT.isVector()) {
9401 SelectionDAG &DAG = DCI.DAG;
9402 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9403 EVT StVT = St->getMemoryVT();
9404 unsigned NumElems = VT.getVectorNumElements();
9405 assert(StVT != VT && "Cannot truncate to the same type");
9406 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9407 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9409 // From, To sizes and ElemCount must be pow of two
9410 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9412 // We are going to use the original vector elt for storing.
9413 // Accumulated smaller vector elements must be a multiple of the store size.
9414 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9416 unsigned SizeRatio = FromEltSz / ToEltSz;
9417 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9419 // Create a type on which we perform the shuffle.
9420 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9421 NumElems*SizeRatio);
9422 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9425 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9426 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9427 for (unsigned i = 0; i < NumElems; ++i)
9428 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9429 ? (i + 1) * SizeRatio - 1
9432 // Can't shuffle using an illegal type.
9433 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9435 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9436 DAG.getUNDEF(WideVec.getValueType()),
9438 // At this point all of the data is stored at the bottom of the
9439 // register. We now need to save it to mem.
9441 // Find the largest store unit
9442 MVT StoreType = MVT::i8;
9443 for (MVT Tp : MVT::integer_valuetypes()) {
9444 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9447 // Didn't find a legal store type.
9448 if (!TLI.isTypeLegal(StoreType))
9451 // Bitcast the original vector into a vector of store-size units
9452 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9453 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9454 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9455 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9456 SmallVector<SDValue, 8> Chains;
9457 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9458 TLI.getPointerTy(DAG.getDataLayout()));
9459 SDValue BasePtr = St->getBasePtr();
9461 // Perform one or more big stores into memory.
9462 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9463 for (unsigned I = 0; I < E; I++) {
9464 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9465 StoreType, ShuffWide,
9466 DAG.getIntPtrConstant(I, DL));
9467 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9468 St->getPointerInfo(), St->isVolatile(),
9469 St->isNonTemporal(), St->getAlignment());
9470 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9472 Chains.push_back(Ch);
9474 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9477 if (!ISD::isNormalStore(St))
9480 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9481 // ARM stores of arguments in the same cache line.
9482 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9483 StVal.getNode()->hasOneUse()) {
9484 SelectionDAG &DAG = DCI.DAG;
9485 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9487 SDValue BasePtr = St->getBasePtr();
9488 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9489 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9490 BasePtr, St->getPointerInfo(), St->isVolatile(),
9491 St->isNonTemporal(), St->getAlignment());
9493 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9494 DAG.getConstant(4, DL, MVT::i32));
9495 return DAG.getStore(NewST1.getValue(0), DL,
9496 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9497 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9498 St->isNonTemporal(),
9499 std::min(4U, St->getAlignment() / 2));
9502 if (StVal.getValueType() == MVT::i64 &&
9503 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9505 // Bitcast an i64 store extracted from a vector to f64.
9506 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9507 SelectionDAG &DAG = DCI.DAG;
9509 SDValue IntVec = StVal.getOperand(0);
9510 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9511 IntVec.getValueType().getVectorNumElements());
9512 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9513 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9514 Vec, StVal.getOperand(1));
9516 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9517 // Make the DAGCombiner fold the bitcasts.
9518 DCI.AddToWorklist(Vec.getNode());
9519 DCI.AddToWorklist(ExtElt.getNode());
9520 DCI.AddToWorklist(V.getNode());
9521 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9522 St->getPointerInfo(), St->isVolatile(),
9523 St->isNonTemporal(), St->getAlignment(),
9527 // If this is a legal vector store, try to combine it into a VST1_UPD.
9528 if (ISD::isNormalStore(N) && VT.isVector() &&
9529 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9530 return CombineBaseUpdate(N, DCI);
9535 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9536 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9537 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9541 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9543 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9548 APFloat APF = C->getValueAPF();
9549 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9550 != APFloat::opOK || !isExact)
9553 c0 = (I == 0) ? cN : c0;
9554 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9561 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9562 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9563 /// when the VMUL has a constant operand that is a power of 2.
9565 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9566 /// vmul.f32 d16, d17, d16
9567 /// vcvt.s32.f32 d16, d16
9569 /// vcvt.s32.f32 d16, d16, #3
9570 static SDValue PerformVCVTCombine(SDNode *N,
9571 TargetLowering::DAGCombinerInfo &DCI,
9572 const ARMSubtarget *Subtarget) {
9573 SelectionDAG &DAG = DCI.DAG;
9574 SDValue Op = N->getOperand(0);
9576 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9577 Op.getOpcode() != ISD::FMUL)
9581 SDValue N0 = Op->getOperand(0);
9582 SDValue ConstVec = Op->getOperand(1);
9583 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9585 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9586 !isConstVecPow2(ConstVec, isSigned, C))
9589 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9590 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9591 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9592 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9594 // These instructions only exist converting from f32 to i32. We can handle
9595 // smaller integers by generating an extra truncate, but larger ones would
9596 // be lossy. We also can't handle more then 4 lanes, since these intructions
9597 // only support v2i32/v4i32 types.
9602 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9603 Intrinsic::arm_neon_vcvtfp2fxu;
9604 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9605 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9606 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9608 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9610 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9611 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9616 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9617 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9618 /// when the VDIV has a constant operand that is a power of 2.
9620 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9621 /// vcvt.f32.s32 d16, d16
9622 /// vdiv.f32 d16, d17, d16
9624 /// vcvt.f32.s32 d16, d16, #3
9625 static SDValue PerformVDIVCombine(SDNode *N,
9626 TargetLowering::DAGCombinerInfo &DCI,
9627 const ARMSubtarget *Subtarget) {
9628 SelectionDAG &DAG = DCI.DAG;
9629 SDValue Op = N->getOperand(0);
9630 unsigned OpOpcode = Op.getNode()->getOpcode();
9632 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9633 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9637 SDValue ConstVec = N->getOperand(1);
9638 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9640 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9641 !isConstVecPow2(ConstVec, isSigned, C))
9644 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9645 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9646 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9647 // These instructions only exist converting from i32 to f32. We can handle
9648 // smaller integers by generating an extra extend, but larger ones would
9654 SDValue ConvInput = Op.getOperand(0);
9655 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9656 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9657 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9658 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9661 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9662 Intrinsic::arm_neon_vcvtfxu2fp;
9663 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9665 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9666 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9669 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9670 /// operand of a vector shift operation, where all the elements of the
9671 /// build_vector must have the same constant integer value.
9672 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9673 // Ignore bit_converts.
9674 while (Op.getOpcode() == ISD::BITCAST)
9675 Op = Op.getOperand(0);
9676 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9677 APInt SplatBits, SplatUndef;
9678 unsigned SplatBitSize;
9680 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9681 HasAnyUndefs, ElementBits) ||
9682 SplatBitSize > ElementBits)
9684 Cnt = SplatBits.getSExtValue();
9688 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9689 /// operand of a vector shift left operation. That value must be in the range:
9690 /// 0 <= Value < ElementBits for a left shift; or
9691 /// 0 <= Value <= ElementBits for a long left shift.
9692 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9693 assert(VT.isVector() && "vector shift count is not a vector type");
9694 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9695 if (! getVShiftImm(Op, ElementBits, Cnt))
9697 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9700 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9701 /// operand of a vector shift right operation. For a shift opcode, the value
9702 /// is positive, but for an intrinsic the value count must be negative. The
9703 /// absolute value must be in the range:
9704 /// 1 <= |Value| <= ElementBits for a right shift; or
9705 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9706 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9708 assert(VT.isVector() && "vector shift count is not a vector type");
9709 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9710 if (! getVShiftImm(Op, ElementBits, Cnt))
9714 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9717 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9718 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9719 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9722 // Don't do anything for most intrinsics.
9725 case Intrinsic::arm_neon_vabds:
9726 if (!N->getValueType(0).isInteger())
9728 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9729 N->getOperand(1), N->getOperand(2));
9730 case Intrinsic::arm_neon_vabdu:
9731 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9732 N->getOperand(1), N->getOperand(2));
9734 // Vector shifts: check for immediate versions and lower them.
9735 // Note: This is done during DAG combining instead of DAG legalizing because
9736 // the build_vectors for 64-bit vector element shift counts are generally
9737 // not legal, and it is hard to see their values after they get legalized to
9738 // loads from a constant pool.
9739 case Intrinsic::arm_neon_vshifts:
9740 case Intrinsic::arm_neon_vshiftu:
9741 case Intrinsic::arm_neon_vrshifts:
9742 case Intrinsic::arm_neon_vrshiftu:
9743 case Intrinsic::arm_neon_vrshiftn:
9744 case Intrinsic::arm_neon_vqshifts:
9745 case Intrinsic::arm_neon_vqshiftu:
9746 case Intrinsic::arm_neon_vqshiftsu:
9747 case Intrinsic::arm_neon_vqshiftns:
9748 case Intrinsic::arm_neon_vqshiftnu:
9749 case Intrinsic::arm_neon_vqshiftnsu:
9750 case Intrinsic::arm_neon_vqrshiftns:
9751 case Intrinsic::arm_neon_vqrshiftnu:
9752 case Intrinsic::arm_neon_vqrshiftnsu: {
9753 EVT VT = N->getOperand(1).getValueType();
9755 unsigned VShiftOpc = 0;
9758 case Intrinsic::arm_neon_vshifts:
9759 case Intrinsic::arm_neon_vshiftu:
9760 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9761 VShiftOpc = ARMISD::VSHL;
9764 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9765 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9766 ARMISD::VSHRs : ARMISD::VSHRu);
9771 case Intrinsic::arm_neon_vrshifts:
9772 case Intrinsic::arm_neon_vrshiftu:
9773 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9777 case Intrinsic::arm_neon_vqshifts:
9778 case Intrinsic::arm_neon_vqshiftu:
9779 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9783 case Intrinsic::arm_neon_vqshiftsu:
9784 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9786 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9788 case Intrinsic::arm_neon_vrshiftn:
9789 case Intrinsic::arm_neon_vqshiftns:
9790 case Intrinsic::arm_neon_vqshiftnu:
9791 case Intrinsic::arm_neon_vqshiftnsu:
9792 case Intrinsic::arm_neon_vqrshiftns:
9793 case Intrinsic::arm_neon_vqrshiftnu:
9794 case Intrinsic::arm_neon_vqrshiftnsu:
9795 // Narrowing shifts require an immediate right shift.
9796 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9798 llvm_unreachable("invalid shift count for narrowing vector shift "
9802 llvm_unreachable("unhandled vector shift");
9806 case Intrinsic::arm_neon_vshifts:
9807 case Intrinsic::arm_neon_vshiftu:
9808 // Opcode already set above.
9810 case Intrinsic::arm_neon_vrshifts:
9811 VShiftOpc = ARMISD::VRSHRs; break;
9812 case Intrinsic::arm_neon_vrshiftu:
9813 VShiftOpc = ARMISD::VRSHRu; break;
9814 case Intrinsic::arm_neon_vrshiftn:
9815 VShiftOpc = ARMISD::VRSHRN; break;
9816 case Intrinsic::arm_neon_vqshifts:
9817 VShiftOpc = ARMISD::VQSHLs; break;
9818 case Intrinsic::arm_neon_vqshiftu:
9819 VShiftOpc = ARMISD::VQSHLu; break;
9820 case Intrinsic::arm_neon_vqshiftsu:
9821 VShiftOpc = ARMISD::VQSHLsu; break;
9822 case Intrinsic::arm_neon_vqshiftns:
9823 VShiftOpc = ARMISD::VQSHRNs; break;
9824 case Intrinsic::arm_neon_vqshiftnu:
9825 VShiftOpc = ARMISD::VQSHRNu; break;
9826 case Intrinsic::arm_neon_vqshiftnsu:
9827 VShiftOpc = ARMISD::VQSHRNsu; break;
9828 case Intrinsic::arm_neon_vqrshiftns:
9829 VShiftOpc = ARMISD::VQRSHRNs; break;
9830 case Intrinsic::arm_neon_vqrshiftnu:
9831 VShiftOpc = ARMISD::VQRSHRNu; break;
9832 case Intrinsic::arm_neon_vqrshiftnsu:
9833 VShiftOpc = ARMISD::VQRSHRNsu; break;
9837 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9838 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9841 case Intrinsic::arm_neon_vshiftins: {
9842 EVT VT = N->getOperand(1).getValueType();
9844 unsigned VShiftOpc = 0;
9846 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9847 VShiftOpc = ARMISD::VSLI;
9848 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9849 VShiftOpc = ARMISD::VSRI;
9851 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9855 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9856 N->getOperand(1), N->getOperand(2),
9857 DAG.getConstant(Cnt, dl, MVT::i32));
9860 case Intrinsic::arm_neon_vqrshifts:
9861 case Intrinsic::arm_neon_vqrshiftu:
9862 // No immediate versions of these to check for.
9869 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9870 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9871 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9872 /// vector element shift counts are generally not legal, and it is hard to see
9873 /// their values after they get legalized to loads from a constant pool.
9874 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9875 const ARMSubtarget *ST) {
9876 EVT VT = N->getValueType(0);
9877 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9878 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9879 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9880 SDValue N1 = N->getOperand(1);
9881 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9882 SDValue N0 = N->getOperand(0);
9883 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9884 DAG.MaskedValueIsZero(N0.getOperand(0),
9885 APInt::getHighBitsSet(32, 16)))
9886 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9890 // Nothing to be done for scalar shifts.
9891 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9892 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9895 assert(ST->hasNEON() && "unexpected vector shift");
9898 switch (N->getOpcode()) {
9899 default: llvm_unreachable("unexpected shift opcode");
9902 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9904 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9905 DAG.getConstant(Cnt, dl, MVT::i32));
9911 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9912 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9913 ARMISD::VSHRs : ARMISD::VSHRu);
9915 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9916 DAG.getConstant(Cnt, dl, MVT::i32));
9922 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9923 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9924 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9925 const ARMSubtarget *ST) {
9926 SDValue N0 = N->getOperand(0);
9928 // Check for sign- and zero-extensions of vector extract operations of 8-
9929 // and 16-bit vector elements. NEON supports these directly. They are
9930 // handled during DAG combining because type legalization will promote them
9931 // to 32-bit types and it is messy to recognize the operations after that.
9932 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9933 SDValue Vec = N0.getOperand(0);
9934 SDValue Lane = N0.getOperand(1);
9935 EVT VT = N->getValueType(0);
9936 EVT EltVT = N0.getValueType();
9937 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9939 if (VT == MVT::i32 &&
9940 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9941 TLI.isTypeLegal(Vec.getValueType()) &&
9942 isa<ConstantSDNode>(Lane)) {
9945 switch (N->getOpcode()) {
9946 default: llvm_unreachable("unexpected opcode");
9947 case ISD::SIGN_EXTEND:
9948 Opc = ARMISD::VGETLANEs;
9950 case ISD::ZERO_EXTEND:
9951 case ISD::ANY_EXTEND:
9952 Opc = ARMISD::VGETLANEu;
9955 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9962 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9963 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9964 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9965 const ARMSubtarget *ST) {
9966 // If the target supports NEON, try to use vmax/vmin instructions for f32
9967 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9968 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9969 // a NaN; only do the transformation when it matches that behavior.
9971 // For now only do this when using NEON for FP operations; if using VFP, it
9972 // is not obvious that the benefit outweighs the cost of switching to the
9974 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9975 N->getValueType(0) != MVT::f32)
9978 SDValue CondLHS = N->getOperand(0);
9979 SDValue CondRHS = N->getOperand(1);
9980 SDValue LHS = N->getOperand(2);
9981 SDValue RHS = N->getOperand(3);
9982 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9984 unsigned Opcode = 0;
9986 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9987 IsReversed = false; // x CC y ? x : y
9988 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9989 IsReversed = true ; // x CC y ? y : x
10003 // If LHS is NaN, an ordered comparison will be false and the result will
10004 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
10005 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10006 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10007 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10009 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10010 // will return -0, so vmin can only be used for unsafe math or if one of
10011 // the operands is known to be nonzero.
10012 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10013 !DAG.getTarget().Options.UnsafeFPMath &&
10014 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10016 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10025 // If LHS is NaN, an ordered comparison will be false and the result will
10026 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
10027 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10028 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10029 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10031 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10032 // will return +0, so vmax can only be used for unsafe math or if one of
10033 // the operands is known to be nonzero.
10034 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10035 !DAG.getTarget().Options.UnsafeFPMath &&
10036 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10038 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10044 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10047 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10049 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10050 SDValue Cmp = N->getOperand(4);
10051 if (Cmp.getOpcode() != ARMISD::CMPZ)
10052 // Only looking at EQ and NE cases.
10055 EVT VT = N->getValueType(0);
10057 SDValue LHS = Cmp.getOperand(0);
10058 SDValue RHS = Cmp.getOperand(1);
10059 SDValue FalseVal = N->getOperand(0);
10060 SDValue TrueVal = N->getOperand(1);
10061 SDValue ARMcc = N->getOperand(2);
10062 ARMCC::CondCodes CC =
10063 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10081 /// FIXME: Turn this into a target neutral optimization?
10083 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10084 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10085 N->getOperand(3), Cmp);
10086 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10088 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10089 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10090 N->getOperand(3), NewCmp);
10093 if (Res.getNode()) {
10094 APInt KnownZero, KnownOne;
10095 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10096 // Capture demanded bits information that would be otherwise lost.
10097 if (KnownZero == 0xfffffffe)
10098 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10099 DAG.getValueType(MVT::i1));
10100 else if (KnownZero == 0xffffff00)
10101 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10102 DAG.getValueType(MVT::i8));
10103 else if (KnownZero == 0xffff0000)
10104 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10105 DAG.getValueType(MVT::i16));
10111 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10112 DAGCombinerInfo &DCI) const {
10113 switch (N->getOpcode()) {
10115 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10116 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10117 case ISD::SUB: return PerformSUBCombine(N, DCI);
10118 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10119 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10120 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10121 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10122 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10123 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10124 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10125 case ISD::STORE: return PerformSTORECombine(N, DCI);
10126 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10127 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10128 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10129 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10130 case ISD::FP_TO_SINT:
10131 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10132 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10133 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10136 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10137 case ISD::SIGN_EXTEND:
10138 case ISD::ZERO_EXTEND:
10139 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10140 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10141 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10142 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10143 case ARMISD::VLD2DUP:
10144 case ARMISD::VLD3DUP:
10145 case ARMISD::VLD4DUP:
10146 return PerformVLDCombine(N, DCI);
10147 case ARMISD::BUILD_VECTOR:
10148 return PerformARMBUILD_VECTORCombine(N, DCI);
10149 case ISD::INTRINSIC_VOID:
10150 case ISD::INTRINSIC_W_CHAIN:
10151 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10152 case Intrinsic::arm_neon_vld1:
10153 case Intrinsic::arm_neon_vld2:
10154 case Intrinsic::arm_neon_vld3:
10155 case Intrinsic::arm_neon_vld4:
10156 case Intrinsic::arm_neon_vld2lane:
10157 case Intrinsic::arm_neon_vld3lane:
10158 case Intrinsic::arm_neon_vld4lane:
10159 case Intrinsic::arm_neon_vst1:
10160 case Intrinsic::arm_neon_vst2:
10161 case Intrinsic::arm_neon_vst3:
10162 case Intrinsic::arm_neon_vst4:
10163 case Intrinsic::arm_neon_vst2lane:
10164 case Intrinsic::arm_neon_vst3lane:
10165 case Intrinsic::arm_neon_vst4lane:
10166 return PerformVLDCombine(N, DCI);
10174 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10176 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10179 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10182 bool *Fast) const {
10183 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10184 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10186 switch (VT.getSimpleVT().SimpleTy) {
10192 // Unaligned access can use (for example) LRDB, LRDH, LDR
10193 if (AllowsUnaligned) {
10195 *Fast = Subtarget->hasV7Ops();
10202 // For any little-endian targets with neon, we can support unaligned ld/st
10203 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10204 // A big-endian target may also explicitly support unaligned accesses
10205 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10215 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10216 unsigned AlignCheck) {
10217 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10218 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10221 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10222 unsigned DstAlign, unsigned SrcAlign,
10223 bool IsMemset, bool ZeroMemset,
10225 MachineFunction &MF) const {
10226 const Function *F = MF.getFunction();
10228 // See if we can use NEON instructions for this...
10229 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10230 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10233 (memOpAlign(SrcAlign, DstAlign, 16) ||
10234 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10236 } else if (Size >= 8 &&
10237 (memOpAlign(SrcAlign, DstAlign, 8) ||
10238 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10244 // Lowering to i32/i16 if the size permits.
10247 else if (Size >= 2)
10250 // Let the target-independent logic figure it out.
10254 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10255 if (Val.getOpcode() != ISD::LOAD)
10258 EVT VT1 = Val.getValueType();
10259 if (!VT1.isSimple() || !VT1.isInteger() ||
10260 !VT2.isSimple() || !VT2.isInteger())
10263 switch (VT1.getSimpleVT().SimpleTy) {
10268 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10275 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10276 EVT VT = ExtVal.getValueType();
10278 if (!isTypeLegal(VT))
10281 // Don't create a loadext if we can fold the extension into a wide/long
10283 // If there's more than one user instruction, the loadext is desirable no
10284 // matter what. There can be two uses by the same instruction.
10285 if (ExtVal->use_empty() ||
10286 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10289 SDNode *U = *ExtVal->use_begin();
10290 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10291 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10297 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10298 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10301 if (!isTypeLegal(EVT::getEVT(Ty1)))
10304 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10306 // Assuming the caller doesn't have a zeroext or signext return parameter,
10307 // truncation all the way down to i1 is valid.
10312 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10316 unsigned Scale = 1;
10317 switch (VT.getSimpleVT().SimpleTy) {
10318 default: return false;
10333 if ((V & (Scale - 1)) != 0)
10336 return V == (V & ((1LL << 5) - 1));
10339 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10340 const ARMSubtarget *Subtarget) {
10341 bool isNeg = false;
10347 switch (VT.getSimpleVT().SimpleTy) {
10348 default: return false;
10353 // + imm12 or - imm8
10355 return V == (V & ((1LL << 8) - 1));
10356 return V == (V & ((1LL << 12) - 1));
10359 // Same as ARM mode. FIXME: NEON?
10360 if (!Subtarget->hasVFP2())
10365 return V == (V & ((1LL << 8) - 1));
10369 /// isLegalAddressImmediate - Return true if the integer value can be used
10370 /// as the offset of the target addressing mode for load / store of the
10372 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10373 const ARMSubtarget *Subtarget) {
10377 if (!VT.isSimple())
10380 if (Subtarget->isThumb1Only())
10381 return isLegalT1AddressImmediate(V, VT);
10382 else if (Subtarget->isThumb2())
10383 return isLegalT2AddressImmediate(V, VT, Subtarget);
10388 switch (VT.getSimpleVT().SimpleTy) {
10389 default: return false;
10394 return V == (V & ((1LL << 12) - 1));
10397 return V == (V & ((1LL << 8) - 1));
10400 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10405 return V == (V & ((1LL << 8) - 1));
10409 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10411 int Scale = AM.Scale;
10415 switch (VT.getSimpleVT().SimpleTy) {
10416 default: return false;
10424 Scale = Scale & ~1;
10425 return Scale == 2 || Scale == 4 || Scale == 8;
10428 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10432 // Note, we allow "void" uses (basically, uses that aren't loads or
10433 // stores), because arm allows folding a scale into many arithmetic
10434 // operations. This should be made more precise and revisited later.
10436 // Allow r << imm, but the imm has to be a multiple of two.
10437 if (Scale & 1) return false;
10438 return isPowerOf2_32(Scale);
10442 /// isLegalAddressingMode - Return true if the addressing mode represented
10443 /// by AM is legal for this target, for a load/store of the specified type.
10444 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10445 const AddrMode &AM, Type *Ty,
10446 unsigned AS) const {
10447 EVT VT = getValueType(DL, Ty, true);
10448 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10451 // Can never fold addr of global into load/store.
10455 switch (AM.Scale) {
10456 case 0: // no scale reg, must be "r+i" or "r", or "i".
10459 if (Subtarget->isThumb1Only())
10463 // ARM doesn't support any R+R*scale+imm addr modes.
10467 if (!VT.isSimple())
10470 if (Subtarget->isThumb2())
10471 return isLegalT2ScaledAddressingMode(AM, VT);
10473 int Scale = AM.Scale;
10474 switch (VT.getSimpleVT().SimpleTy) {
10475 default: return false;
10479 if (Scale < 0) Scale = -Scale;
10483 return isPowerOf2_32(Scale & ~1);
10487 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10492 // Note, we allow "void" uses (basically, uses that aren't loads or
10493 // stores), because arm allows folding a scale into many arithmetic
10494 // operations. This should be made more precise and revisited later.
10496 // Allow r << imm, but the imm has to be a multiple of two.
10497 if (Scale & 1) return false;
10498 return isPowerOf2_32(Scale);
10504 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10505 /// icmp immediate, that is the target has icmp instructions which can compare
10506 /// a register against the immediate without having to materialize the
10507 /// immediate into a register.
10508 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10509 // Thumb2 and ARM modes can use cmn for negative immediates.
10510 if (!Subtarget->isThumb())
10511 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10512 if (Subtarget->isThumb2())
10513 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10514 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10515 return Imm >= 0 && Imm <= 255;
10518 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10519 /// *or sub* immediate, that is the target has add or sub instructions which can
10520 /// add a register with the immediate without having to materialize the
10521 /// immediate into a register.
10522 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10523 // Same encoding for add/sub, just flip the sign.
10524 int64_t AbsImm = std::abs(Imm);
10525 if (!Subtarget->isThumb())
10526 return ARM_AM::getSOImmVal(AbsImm) != -1;
10527 if (Subtarget->isThumb2())
10528 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10529 // Thumb1 only has 8-bit unsigned immediate.
10530 return AbsImm >= 0 && AbsImm <= 255;
10533 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10534 bool isSEXTLoad, SDValue &Base,
10535 SDValue &Offset, bool &isInc,
10536 SelectionDAG &DAG) {
10537 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10540 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10541 // AddressingMode 3
10542 Base = Ptr->getOperand(0);
10543 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10544 int RHSC = (int)RHS->getZExtValue();
10545 if (RHSC < 0 && RHSC > -256) {
10546 assert(Ptr->getOpcode() == ISD::ADD);
10548 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10552 isInc = (Ptr->getOpcode() == ISD::ADD);
10553 Offset = Ptr->getOperand(1);
10555 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10556 // AddressingMode 2
10557 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10558 int RHSC = (int)RHS->getZExtValue();
10559 if (RHSC < 0 && RHSC > -0x1000) {
10560 assert(Ptr->getOpcode() == ISD::ADD);
10562 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10563 Base = Ptr->getOperand(0);
10568 if (Ptr->getOpcode() == ISD::ADD) {
10570 ARM_AM::ShiftOpc ShOpcVal=
10571 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10572 if (ShOpcVal != ARM_AM::no_shift) {
10573 Base = Ptr->getOperand(1);
10574 Offset = Ptr->getOperand(0);
10576 Base = Ptr->getOperand(0);
10577 Offset = Ptr->getOperand(1);
10582 isInc = (Ptr->getOpcode() == ISD::ADD);
10583 Base = Ptr->getOperand(0);
10584 Offset = Ptr->getOperand(1);
10588 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10592 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10593 bool isSEXTLoad, SDValue &Base,
10594 SDValue &Offset, bool &isInc,
10595 SelectionDAG &DAG) {
10596 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10599 Base = Ptr->getOperand(0);
10600 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10601 int RHSC = (int)RHS->getZExtValue();
10602 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10603 assert(Ptr->getOpcode() == ISD::ADD);
10605 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10607 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10608 isInc = Ptr->getOpcode() == ISD::ADD;
10609 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10617 /// getPreIndexedAddressParts - returns true by value, base pointer and
10618 /// offset pointer and addressing mode by reference if the node's address
10619 /// can be legally represented as pre-indexed load / store address.
10621 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10623 ISD::MemIndexedMode &AM,
10624 SelectionDAG &DAG) const {
10625 if (Subtarget->isThumb1Only())
10630 bool isSEXTLoad = false;
10631 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10632 Ptr = LD->getBasePtr();
10633 VT = LD->getMemoryVT();
10634 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10635 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10636 Ptr = ST->getBasePtr();
10637 VT = ST->getMemoryVT();
10642 bool isLegal = false;
10643 if (Subtarget->isThumb2())
10644 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10645 Offset, isInc, DAG);
10647 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10648 Offset, isInc, DAG);
10652 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10656 /// getPostIndexedAddressParts - returns true by value, base pointer and
10657 /// offset pointer and addressing mode by reference if this node can be
10658 /// combined with a load / store to form a post-indexed load / store.
10659 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10662 ISD::MemIndexedMode &AM,
10663 SelectionDAG &DAG) const {
10664 if (Subtarget->isThumb1Only())
10669 bool isSEXTLoad = false;
10670 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10671 VT = LD->getMemoryVT();
10672 Ptr = LD->getBasePtr();
10673 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10674 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10675 VT = ST->getMemoryVT();
10676 Ptr = ST->getBasePtr();
10681 bool isLegal = false;
10682 if (Subtarget->isThumb2())
10683 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10686 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10692 // Swap base ptr and offset to catch more post-index load / store when
10693 // it's legal. In Thumb2 mode, offset must be an immediate.
10694 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10695 !Subtarget->isThumb2())
10696 std::swap(Base, Offset);
10698 // Post-indexed load / store update the base pointer.
10703 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10707 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10710 const SelectionDAG &DAG,
10711 unsigned Depth) const {
10712 unsigned BitWidth = KnownOne.getBitWidth();
10713 KnownZero = KnownOne = APInt(BitWidth, 0);
10714 switch (Op.getOpcode()) {
10720 // These nodes' second result is a boolean
10721 if (Op.getResNo() == 0)
10723 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10725 case ARMISD::CMOV: {
10726 // Bits are known zero/one if known on the LHS and RHS.
10727 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10728 if (KnownZero == 0 && KnownOne == 0) return;
10730 APInt KnownZeroRHS, KnownOneRHS;
10731 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10732 KnownZero &= KnownZeroRHS;
10733 KnownOne &= KnownOneRHS;
10736 case ISD::INTRINSIC_W_CHAIN: {
10737 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10738 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10741 case Intrinsic::arm_ldaex:
10742 case Intrinsic::arm_ldrex: {
10743 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10744 unsigned MemBits = VT.getScalarType().getSizeInBits();
10745 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10753 //===----------------------------------------------------------------------===//
10754 // ARM Inline Assembly Support
10755 //===----------------------------------------------------------------------===//
10757 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10758 // Looking for "rev" which is V6+.
10759 if (!Subtarget->hasV6Ops())
10762 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10763 std::string AsmStr = IA->getAsmString();
10764 SmallVector<StringRef, 4> AsmPieces;
10765 SplitString(AsmStr, AsmPieces, ";\n");
10767 switch (AsmPieces.size()) {
10768 default: return false;
10770 AsmStr = AsmPieces[0];
10772 SplitString(AsmStr, AsmPieces, " \t,");
10775 if (AsmPieces.size() == 3 &&
10776 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10777 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10778 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10779 if (Ty && Ty->getBitWidth() == 32)
10780 return IntrinsicLowering::LowerToByteSwap(CI);
10788 /// getConstraintType - Given a constraint letter, return the type of
10789 /// constraint it is for this target.
10790 ARMTargetLowering::ConstraintType
10791 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10792 if (Constraint.size() == 1) {
10793 switch (Constraint[0]) {
10795 case 'l': return C_RegisterClass;
10796 case 'w': return C_RegisterClass;
10797 case 'h': return C_RegisterClass;
10798 case 'x': return C_RegisterClass;
10799 case 't': return C_RegisterClass;
10800 case 'j': return C_Other; // Constant for movw.
10801 // An address with a single base register. Due to the way we
10802 // currently handle addresses it is the same as an 'r' memory constraint.
10803 case 'Q': return C_Memory;
10805 } else if (Constraint.size() == 2) {
10806 switch (Constraint[0]) {
10808 // All 'U+' constraints are addresses.
10809 case 'U': return C_Memory;
10812 return TargetLowering::getConstraintType(Constraint);
10815 /// Examine constraint type and operand type and determine a weight value.
10816 /// This object must already have been set up with the operand type
10817 /// and the current alternative constraint selected.
10818 TargetLowering::ConstraintWeight
10819 ARMTargetLowering::getSingleConstraintMatchWeight(
10820 AsmOperandInfo &info, const char *constraint) const {
10821 ConstraintWeight weight = CW_Invalid;
10822 Value *CallOperandVal = info.CallOperandVal;
10823 // If we don't have a value, we can't do a match,
10824 // but allow it at the lowest weight.
10825 if (!CallOperandVal)
10827 Type *type = CallOperandVal->getType();
10828 // Look at the constraint type.
10829 switch (*constraint) {
10831 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10834 if (type->isIntegerTy()) {
10835 if (Subtarget->isThumb())
10836 weight = CW_SpecificReg;
10838 weight = CW_Register;
10842 if (type->isFloatingPointTy())
10843 weight = CW_Register;
10849 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10850 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10851 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10852 if (Constraint.size() == 1) {
10853 // GCC ARM Constraint Letters
10854 switch (Constraint[0]) {
10855 case 'l': // Low regs or general regs.
10856 if (Subtarget->isThumb())
10857 return RCPair(0U, &ARM::tGPRRegClass);
10858 return RCPair(0U, &ARM::GPRRegClass);
10859 case 'h': // High regs or no regs.
10860 if (Subtarget->isThumb())
10861 return RCPair(0U, &ARM::hGPRRegClass);
10864 if (Subtarget->isThumb1Only())
10865 return RCPair(0U, &ARM::tGPRRegClass);
10866 return RCPair(0U, &ARM::GPRRegClass);
10868 if (VT == MVT::Other)
10870 if (VT == MVT::f32)
10871 return RCPair(0U, &ARM::SPRRegClass);
10872 if (VT.getSizeInBits() == 64)
10873 return RCPair(0U, &ARM::DPRRegClass);
10874 if (VT.getSizeInBits() == 128)
10875 return RCPair(0U, &ARM::QPRRegClass);
10878 if (VT == MVT::Other)
10880 if (VT == MVT::f32)
10881 return RCPair(0U, &ARM::SPR_8RegClass);
10882 if (VT.getSizeInBits() == 64)
10883 return RCPair(0U, &ARM::DPR_8RegClass);
10884 if (VT.getSizeInBits() == 128)
10885 return RCPair(0U, &ARM::QPR_8RegClass);
10888 if (VT == MVT::f32)
10889 return RCPair(0U, &ARM::SPRRegClass);
10893 if (StringRef("{cc}").equals_lower(Constraint))
10894 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10896 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10899 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10900 /// vector. If it is invalid, don't add anything to Ops.
10901 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10902 std::string &Constraint,
10903 std::vector<SDValue>&Ops,
10904 SelectionDAG &DAG) const {
10907 // Currently only support length 1 constraints.
10908 if (Constraint.length() != 1) return;
10910 char ConstraintLetter = Constraint[0];
10911 switch (ConstraintLetter) {
10914 case 'I': case 'J': case 'K': case 'L':
10915 case 'M': case 'N': case 'O':
10916 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10920 int64_t CVal64 = C->getSExtValue();
10921 int CVal = (int) CVal64;
10922 // None of these constraints allow values larger than 32 bits. Check
10923 // that the value fits in an int.
10924 if (CVal != CVal64)
10927 switch (ConstraintLetter) {
10929 // Constant suitable for movw, must be between 0 and
10931 if (Subtarget->hasV6T2Ops())
10932 if (CVal >= 0 && CVal <= 65535)
10936 if (Subtarget->isThumb1Only()) {
10937 // This must be a constant between 0 and 255, for ADD
10939 if (CVal >= 0 && CVal <= 255)
10941 } else if (Subtarget->isThumb2()) {
10942 // A constant that can be used as an immediate value in a
10943 // data-processing instruction.
10944 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10947 // A constant that can be used as an immediate value in a
10948 // data-processing instruction.
10949 if (ARM_AM::getSOImmVal(CVal) != -1)
10955 if (Subtarget->isThumb()) { // FIXME thumb2
10956 // This must be a constant between -255 and -1, for negated ADD
10957 // immediates. This can be used in GCC with an "n" modifier that
10958 // prints the negated value, for use with SUB instructions. It is
10959 // not useful otherwise but is implemented for compatibility.
10960 if (CVal >= -255 && CVal <= -1)
10963 // This must be a constant between -4095 and 4095. It is not clear
10964 // what this constraint is intended for. Implemented for
10965 // compatibility with GCC.
10966 if (CVal >= -4095 && CVal <= 4095)
10972 if (Subtarget->isThumb1Only()) {
10973 // A 32-bit value where only one byte has a nonzero value. Exclude
10974 // zero to match GCC. This constraint is used by GCC internally for
10975 // constants that can be loaded with a move/shift combination.
10976 // It is not useful otherwise but is implemented for compatibility.
10977 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10979 } else if (Subtarget->isThumb2()) {
10980 // A constant whose bitwise inverse can be used as an immediate
10981 // value in a data-processing instruction. This can be used in GCC
10982 // with a "B" modifier that prints the inverted value, for use with
10983 // BIC and MVN instructions. It is not useful otherwise but is
10984 // implemented for compatibility.
10985 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10988 // A constant whose bitwise inverse can be used as an immediate
10989 // value in a data-processing instruction. This can be used in GCC
10990 // with a "B" modifier that prints the inverted value, for use with
10991 // BIC and MVN instructions. It is not useful otherwise but is
10992 // implemented for compatibility.
10993 if (ARM_AM::getSOImmVal(~CVal) != -1)
10999 if (Subtarget->isThumb1Only()) {
11000 // This must be a constant between -7 and 7,
11001 // for 3-operand ADD/SUB immediate instructions.
11002 if (CVal >= -7 && CVal < 7)
11004 } else if (Subtarget->isThumb2()) {
11005 // A constant whose negation can be used as an immediate value in a
11006 // data-processing instruction. This can be used in GCC with an "n"
11007 // modifier that prints the negated value, for use with SUB
11008 // instructions. It is not useful otherwise but is implemented for
11010 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11013 // A constant whose negation can be used as an immediate value in a
11014 // data-processing instruction. This can be used in GCC with an "n"
11015 // modifier that prints the negated value, for use with SUB
11016 // instructions. It is not useful otherwise but is implemented for
11018 if (ARM_AM::getSOImmVal(-CVal) != -1)
11024 if (Subtarget->isThumb()) { // FIXME thumb2
11025 // This must be a multiple of 4 between 0 and 1020, for
11026 // ADD sp + immediate.
11027 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11030 // A power of two or a constant between 0 and 32. This is used in
11031 // GCC for the shift amount on shifted register operands, but it is
11032 // useful in general for any shift amounts.
11033 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11039 if (Subtarget->isThumb()) { // FIXME thumb2
11040 // This must be a constant between 0 and 31, for shift amounts.
11041 if (CVal >= 0 && CVal <= 31)
11047 if (Subtarget->isThumb()) { // FIXME thumb2
11048 // This must be a multiple of 4 between -508 and 508, for
11049 // ADD/SUB sp = sp + immediate.
11050 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11055 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11059 if (Result.getNode()) {
11060 Ops.push_back(Result);
11063 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11066 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11067 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11068 unsigned Opcode = Op->getOpcode();
11069 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11070 "Invalid opcode for Div/Rem lowering");
11071 bool isSigned = (Opcode == ISD::SDIVREM);
11072 EVT VT = Op->getValueType(0);
11073 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11076 switch (VT.getSimpleVT().SimpleTy) {
11077 default: llvm_unreachable("Unexpected request for libcall!");
11078 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11079 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11080 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11081 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11084 SDValue InChain = DAG.getEntryNode();
11086 TargetLowering::ArgListTy Args;
11087 TargetLowering::ArgListEntry Entry;
11088 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11089 EVT ArgVT = Op->getOperand(i).getValueType();
11090 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11091 Entry.Node = Op->getOperand(i);
11093 Entry.isSExt = isSigned;
11094 Entry.isZExt = !isSigned;
11095 Args.push_back(Entry);
11098 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11099 getPointerTy(DAG.getDataLayout()));
11101 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11104 TargetLowering::CallLoweringInfo CLI(DAG);
11105 CLI.setDebugLoc(dl).setChain(InChain)
11106 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11107 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11109 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11110 return CallInfo.first;
11114 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11115 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11119 SDValue Chain = Op.getOperand(0);
11120 SDValue Size = Op.getOperand(1);
11122 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11123 DAG.getConstant(2, DL, MVT::i32));
11126 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11127 Flag = Chain.getValue(1);
11129 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11130 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11132 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11133 Chain = NewSP.getValue(1);
11135 SDValue Ops[2] = { NewSP, Chain };
11136 return DAG.getMergeValues(Ops, DL);
11139 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11140 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11141 "Unexpected type for custom-lowering FP_EXTEND");
11144 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11146 SDValue SrcVal = Op.getOperand(0);
11147 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11148 /*isSigned*/ false, SDLoc(Op)).first;
11151 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11152 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11153 Subtarget->isFPOnlySP() &&
11154 "Unexpected type for custom-lowering FP_ROUND");
11157 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11159 SDValue SrcVal = Op.getOperand(0);
11160 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11161 /*isSigned*/ false, SDLoc(Op)).first;
11165 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11166 // The ARM target isn't yet aware of offsets.
11170 bool ARM::isBitFieldInvertedMask(unsigned v) {
11171 if (v == 0xffffffff)
11174 // there can be 1's on either or both "outsides", all the "inside"
11175 // bits must be 0's
11176 return isShiftedMask_32(~v);
11179 /// isFPImmLegal - Returns true if the target can instruction select the
11180 /// specified FP immediate natively. If false, the legalizer will
11181 /// materialize the FP immediate as a load from a constant pool.
11182 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11183 if (!Subtarget->hasVFP3())
11185 if (VT == MVT::f32)
11186 return ARM_AM::getFP32Imm(Imm) != -1;
11187 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11188 return ARM_AM::getFP64Imm(Imm) != -1;
11192 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11193 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11194 /// specified in the intrinsic calls.
11195 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11197 unsigned Intrinsic) const {
11198 switch (Intrinsic) {
11199 case Intrinsic::arm_neon_vld1:
11200 case Intrinsic::arm_neon_vld2:
11201 case Intrinsic::arm_neon_vld3:
11202 case Intrinsic::arm_neon_vld4:
11203 case Intrinsic::arm_neon_vld2lane:
11204 case Intrinsic::arm_neon_vld3lane:
11205 case Intrinsic::arm_neon_vld4lane: {
11206 Info.opc = ISD::INTRINSIC_W_CHAIN;
11207 // Conservatively set memVT to the entire set of vectors loaded.
11208 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11209 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11210 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11211 Info.ptrVal = I.getArgOperand(0);
11213 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11214 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11215 Info.vol = false; // volatile loads with NEON intrinsics not supported
11216 Info.readMem = true;
11217 Info.writeMem = false;
11220 case Intrinsic::arm_neon_vst1:
11221 case Intrinsic::arm_neon_vst2:
11222 case Intrinsic::arm_neon_vst3:
11223 case Intrinsic::arm_neon_vst4:
11224 case Intrinsic::arm_neon_vst2lane:
11225 case Intrinsic::arm_neon_vst3lane:
11226 case Intrinsic::arm_neon_vst4lane: {
11227 Info.opc = ISD::INTRINSIC_VOID;
11228 // Conservatively set memVT to the entire set of vectors stored.
11229 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11230 unsigned NumElts = 0;
11231 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11232 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11233 if (!ArgTy->isVectorTy())
11235 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11237 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11238 Info.ptrVal = I.getArgOperand(0);
11240 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11241 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11242 Info.vol = false; // volatile stores with NEON intrinsics not supported
11243 Info.readMem = false;
11244 Info.writeMem = true;
11247 case Intrinsic::arm_ldaex:
11248 case Intrinsic::arm_ldrex: {
11249 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11250 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11251 Info.opc = ISD::INTRINSIC_W_CHAIN;
11252 Info.memVT = MVT::getVT(PtrTy->getElementType());
11253 Info.ptrVal = I.getArgOperand(0);
11255 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11257 Info.readMem = true;
11258 Info.writeMem = false;
11261 case Intrinsic::arm_stlex:
11262 case Intrinsic::arm_strex: {
11263 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11264 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11265 Info.opc = ISD::INTRINSIC_W_CHAIN;
11266 Info.memVT = MVT::getVT(PtrTy->getElementType());
11267 Info.ptrVal = I.getArgOperand(1);
11269 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11271 Info.readMem = false;
11272 Info.writeMem = true;
11275 case Intrinsic::arm_stlexd:
11276 case Intrinsic::arm_strexd: {
11277 Info.opc = ISD::INTRINSIC_W_CHAIN;
11278 Info.memVT = MVT::i64;
11279 Info.ptrVal = I.getArgOperand(2);
11283 Info.readMem = false;
11284 Info.writeMem = true;
11287 case Intrinsic::arm_ldaexd:
11288 case Intrinsic::arm_ldrexd: {
11289 Info.opc = ISD::INTRINSIC_W_CHAIN;
11290 Info.memVT = MVT::i64;
11291 Info.ptrVal = I.getArgOperand(0);
11295 Info.readMem = true;
11296 Info.writeMem = false;
11306 /// \brief Returns true if it is beneficial to convert a load of a constant
11307 /// to just the constant itself.
11308 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11310 assert(Ty->isIntegerTy());
11312 unsigned Bits = Ty->getPrimitiveSizeInBits();
11313 if (Bits == 0 || Bits > 32)
11318 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11320 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11321 ARM_MB::MemBOpt Domain) const {
11322 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11324 // First, if the target has no DMB, see what fallback we can use.
11325 if (!Subtarget->hasDataBarrier()) {
11326 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11327 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11329 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11330 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11331 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11332 Builder.getInt32(0), Builder.getInt32(7),
11333 Builder.getInt32(10), Builder.getInt32(5)};
11334 return Builder.CreateCall(MCR, args);
11336 // Instead of using barriers, atomic accesses on these subtargets use
11338 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11341 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11342 // Only a full system barrier exists in the M-class architectures.
11343 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11344 Constant *CDomain = Builder.getInt32(Domain);
11345 return Builder.CreateCall(DMB, CDomain);
11349 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11350 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11351 AtomicOrdering Ord, bool IsStore,
11352 bool IsLoad) const {
11353 if (!getInsertFencesForAtomic())
11359 llvm_unreachable("Invalid fence: unordered/non-atomic");
11362 return nullptr; // Nothing to do
11363 case SequentiallyConsistent:
11365 return nullptr; // Nothing to do
11368 case AcquireRelease:
11369 if (Subtarget->isSwift())
11370 return makeDMB(Builder, ARM_MB::ISHST);
11371 // FIXME: add a comment with a link to documentation justifying this.
11373 return makeDMB(Builder, ARM_MB::ISH);
11375 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11378 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11379 AtomicOrdering Ord, bool IsStore,
11380 bool IsLoad) const {
11381 if (!getInsertFencesForAtomic())
11387 llvm_unreachable("Invalid fence: unordered/not-atomic");
11390 return nullptr; // Nothing to do
11392 case AcquireRelease:
11393 case SequentiallyConsistent:
11394 return makeDMB(Builder, ARM_MB::ISH);
11396 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11399 // Loads and stores less than 64-bits are already atomic; ones above that
11400 // are doomed anyway, so defer to the default libcall and blame the OS when
11401 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11402 // anything for those.
11403 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11404 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11405 return (Size == 64) && !Subtarget->isMClass();
11408 // Loads and stores less than 64-bits are already atomic; ones above that
11409 // are doomed anyway, so defer to the default libcall and blame the OS when
11410 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11411 // anything for those.
11412 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11413 // guarantee, see DDI0406C ARM architecture reference manual,
11414 // sections A8.8.72-74 LDRD)
11415 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11416 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11417 return (Size == 64) && !Subtarget->isMClass();
11420 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11421 // and up to 64 bits on the non-M profiles
11422 TargetLoweringBase::AtomicRMWExpansionKind
11423 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11424 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11425 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11426 ? AtomicRMWExpansionKind::LLSC
11427 : AtomicRMWExpansionKind::None;
11430 // This has so far only been implemented for MachO.
11431 bool ARMTargetLowering::useLoadStackGuardNode() const {
11432 return Subtarget->isTargetMachO();
11435 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11436 unsigned &Cost) const {
11437 // If we do not have NEON, vector types are not natively supported.
11438 if (!Subtarget->hasNEON())
11441 // Floating point values and vector values map to the same register file.
11442 // Therefore, althought we could do a store extract of a vector type, this is
11443 // better to leave at float as we have more freedom in the addressing mode for
11445 if (VectorTy->isFPOrFPVectorTy())
11448 // If the index is unknown at compile time, this is very expensive to lower
11449 // and it is not possible to combine the store with the extract.
11450 if (!isa<ConstantInt>(Idx))
11453 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11454 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11455 // We can do a store + vector extract on any vector that fits perfectly in a D
11457 if (BitWidth == 64 || BitWidth == 128) {
11464 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11465 AtomicOrdering Ord) const {
11466 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11467 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11468 bool IsAcquire = isAtLeastAcquire(Ord);
11470 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11471 // intrinsic must return {i32, i32} and we have to recombine them into a
11472 // single i64 here.
11473 if (ValTy->getPrimitiveSizeInBits() == 64) {
11474 Intrinsic::ID Int =
11475 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11476 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11478 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11479 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11481 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11482 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11483 if (!Subtarget->isLittle())
11484 std::swap (Lo, Hi);
11485 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11486 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11487 return Builder.CreateOr(
11488 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11491 Type *Tys[] = { Addr->getType() };
11492 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11493 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11495 return Builder.CreateTruncOrBitCast(
11496 Builder.CreateCall(Ldrex, Addr),
11497 cast<PointerType>(Addr->getType())->getElementType());
11500 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11502 AtomicOrdering Ord) const {
11503 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11504 bool IsRelease = isAtLeastRelease(Ord);
11506 // Since the intrinsics must have legal type, the i64 intrinsics take two
11507 // parameters: "i32, i32". We must marshal Val into the appropriate form
11508 // before the call.
11509 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11510 Intrinsic::ID Int =
11511 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11512 Function *Strex = Intrinsic::getDeclaration(M, Int);
11513 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11515 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11516 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11517 if (!Subtarget->isLittle())
11518 std::swap (Lo, Hi);
11519 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11520 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11523 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11524 Type *Tys[] = { Addr->getType() };
11525 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11527 return Builder.CreateCall(
11528 Strex, {Builder.CreateZExtOrBitCast(
11529 Val, Strex->getFunctionType()->getParamType(0)),
11533 /// \brief Lower an interleaved load into a vldN intrinsic.
11535 /// E.g. Lower an interleaved load (Factor = 2):
11536 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11537 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
11538 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
11541 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11542 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11543 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11544 bool ARMTargetLowering::lowerInterleavedLoad(
11545 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11546 ArrayRef<unsigned> Indices, unsigned Factor) const {
11547 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11548 "Invalid interleave factor");
11549 assert(!Shuffles.empty() && "Empty shufflevector input");
11550 assert(Shuffles.size() == Indices.size() &&
11551 "Unmatched number of shufflevectors and indices");
11553 VectorType *VecTy = Shuffles[0]->getType();
11554 Type *EltTy = VecTy->getVectorElementType();
11556 const DataLayout &DL = LI->getModule()->getDataLayout();
11557 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11558 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11560 // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11561 // support i64/f64 element).
11562 if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11565 // A pointer vector can not be the return type of the ldN intrinsics. Need to
11566 // load integer vectors first and then convert to pointer vectors.
11567 if (EltTy->isPointerTy())
11569 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11571 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11572 Intrinsic::arm_neon_vld3,
11573 Intrinsic::arm_neon_vld4};
11575 Function *VldnFunc =
11576 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11578 IRBuilder<> Builder(LI);
11579 SmallVector<Value *, 2> Ops;
11581 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11582 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11583 Ops.push_back(Builder.getInt32(LI->getAlignment()));
11585 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11587 // Replace uses of each shufflevector with the corresponding vector loaded
11589 for (unsigned i = 0; i < Shuffles.size(); i++) {
11590 ShuffleVectorInst *SV = Shuffles[i];
11591 unsigned Index = Indices[i];
11593 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11595 // Convert the integer vector to pointer vector if the element is pointer.
11596 if (EltTy->isPointerTy())
11597 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11599 SV->replaceAllUsesWith(SubVec);
11605 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11607 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11608 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11609 unsigned NumElts) {
11610 SmallVector<Constant *, 16> Mask;
11611 for (unsigned i = 0; i < NumElts; i++)
11612 Mask.push_back(Builder.getInt32(Start + i));
11614 return ConstantVector::get(Mask);
11617 /// \brief Lower an interleaved store into a vstN intrinsic.
11619 /// E.g. Lower an interleaved store (Factor = 3):
11620 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11621 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11622 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11625 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11626 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11627 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11628 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11630 /// Note that the new shufflevectors will be removed and we'll only generate one
11631 /// vst3 instruction in CodeGen.
11632 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11633 ShuffleVectorInst *SVI,
11634 unsigned Factor) const {
11635 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11636 "Invalid interleave factor");
11638 VectorType *VecTy = SVI->getType();
11639 assert(VecTy->getVectorNumElements() % Factor == 0 &&
11640 "Invalid interleaved store");
11642 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11643 Type *EltTy = VecTy->getVectorElementType();
11644 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11646 const DataLayout &DL = SI->getModule()->getDataLayout();
11647 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11648 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11650 // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11651 // doesn't support i64/f64 element).
11652 if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11655 Value *Op0 = SVI->getOperand(0);
11656 Value *Op1 = SVI->getOperand(1);
11657 IRBuilder<> Builder(SI);
11659 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11660 // vectors to integer vectors.
11661 if (EltTy->isPointerTy()) {
11662 Type *IntTy = DL.getIntPtrType(EltTy);
11664 // Convert to the corresponding integer vector.
11666 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11667 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11668 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11670 SubVecTy = VectorType::get(IntTy, NumSubElts);
11673 static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11674 Intrinsic::arm_neon_vst3,
11675 Intrinsic::arm_neon_vst4};
11676 Function *VstNFunc = Intrinsic::getDeclaration(
11677 SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11679 SmallVector<Value *, 6> Ops;
11681 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11682 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11684 // Split the shufflevector operands into sub vectors for the new vstN call.
11685 for (unsigned i = 0; i < Factor; i++)
11686 Ops.push_back(Builder.CreateShuffleVector(
11687 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11689 Ops.push_back(Builder.getInt32(SI->getAlignment()));
11690 Builder.CreateCall(VstNFunc, Ops);
11702 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11703 uint64_t &Members) {
11704 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11705 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11706 uint64_t SubMembers = 0;
11707 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11709 Members += SubMembers;
11711 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11712 uint64_t SubMembers = 0;
11713 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11715 Members += SubMembers * AT->getNumElements();
11716 } else if (Ty->isFloatTy()) {
11717 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11721 } else if (Ty->isDoubleTy()) {
11722 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11726 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11733 return VT->getBitWidth() == 64;
11735 return VT->getBitWidth() == 128;
11737 switch (VT->getBitWidth()) {
11750 return (Members > 0 && Members <= 4);
11753 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11754 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11755 /// passing according to AAPCS rules.
11756 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11757 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11758 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11759 CallingConv::ARM_AAPCS_VFP)
11762 HABaseType Base = HA_UNKNOWN;
11763 uint64_t Members = 0;
11764 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11765 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11767 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11768 return IsHA || IsIntArray;