1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "arm-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
64 ARMInterworking("arm-interworking", cl::Hidden,
65 cl::desc("Enable / disable ARM interworking (for debugging only)"),
69 class ARMCCState : public CCState {
71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
74 : CCState(CC, isVarArg, MF, locs, C) {
75 assert(((PC == Call) || (PC == Prologue)) &&
76 "ARMCCState users must specify whether their context is call"
77 "or prologue generation.");
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85 ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89 MVT PromotedBitwiseVT) {
90 if (VT != PromotedLdStVT) {
91 setOperationAction(ISD::LOAD, VT, Promote);
92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94 setOperationAction(ISD::STORE, VT, Promote);
95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98 MVT ElemTy = VT.getVectorElementType();
99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100 setOperationAction(ISD::SETCC, VT, Custom);
101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103 if (ElemTy == MVT::i32) {
104 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118 setOperationAction(ISD::SELECT, VT, Expand);
119 setOperationAction(ISD::SELECT_CC, VT, Expand);
120 setOperationAction(ISD::VSELECT, VT, Expand);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122 if (VT.isInteger()) {
123 setOperationAction(ISD::SHL, VT, Custom);
124 setOperationAction(ISD::SRA, VT, Custom);
125 setOperationAction(ISD::SRL, VT, Custom);
128 // Promote all bit-wise operations.
129 if (VT.isInteger() && VT != PromotedBitwiseVT) {
130 setOperationAction(ISD::AND, VT, Promote);
131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132 setOperationAction(ISD::OR, VT, Promote);
133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::XOR, VT, Promote);
135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138 // Neon does not support vector divide/remainder operations.
139 setOperationAction(ISD::SDIV, VT, Expand);
140 setOperationAction(ISD::UDIV, VT, Expand);
141 setOperationAction(ISD::FDIV, VT, Expand);
142 setOperationAction(ISD::SREM, VT, Expand);
143 setOperationAction(ISD::UREM, VT, Expand);
144 setOperationAction(ISD::FREM, VT, Expand);
146 if (VT.isInteger()) {
147 setOperationAction(ISD::SABSDIFF, VT, Legal);
148 setOperationAction(ISD::UABSDIFF, VT, Legal);
150 if (!VT.isFloatingPoint() &&
151 VT != MVT::v2i64 && VT != MVT::v1i64)
152 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
153 setOperationAction(Opcode, VT, Legal);
157 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::DPRRegClass);
159 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
162 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
163 addRegisterClass(VT, &ARM::DPairRegClass);
164 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
168 const ARMSubtarget &STI)
169 : TargetLowering(TM), Subtarget(&STI) {
170 RegInfo = Subtarget->getRegisterInfo();
171 Itins = Subtarget->getInstrItineraryData();
173 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
175 if (Subtarget->isTargetMachO()) {
176 // Uses VFP for Thumb libfuncs if available.
177 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
179 static const struct {
180 const RTLIB::Libcall Op;
181 const char * const Name;
182 const ISD::CondCode Cond;
184 // Single-precision floating-point arithmetic.
185 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
186 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
187 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
188 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
190 // Double-precision floating-point arithmetic.
191 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
192 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
193 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
194 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
196 // Single-precision comparisons.
197 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
198 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
199 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
200 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
201 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
202 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
203 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
204 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
206 // Double-precision comparisons.
207 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
208 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
209 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
210 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
211 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
212 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
213 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
214 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
216 // Floating-point to integer conversions.
217 // i64 conversions are done via library routines even when generating VFP
218 // instructions, so use the same ones.
219 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
220 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
221 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
222 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
224 // Conversions between floating types.
225 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
226 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
228 // Integer to floating-point conversions.
229 // i64 conversions are done via library routines even when generating VFP
230 // instructions, so use the same ones.
231 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
232 // e.g., __floatunsidf vs. __floatunssidfvfp.
233 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
234 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
235 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
236 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
239 for (const auto &LC : LibraryCalls) {
240 setLibcallName(LC.Op, LC.Name);
241 if (LC.Cond != ISD::SETCC_INVALID)
242 setCmpLibcallCC(LC.Op, LC.Cond);
246 // Set the correct calling convention for ARMv7k WatchOS. It's just
247 // AAPCS_VFP for functions as simple as libcalls.
248 if (Subtarget->isTargetWatchOS()) {
249 for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
250 setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
254 // These libcalls are not available in 32-bit.
255 setLibcallName(RTLIB::SHL_I128, nullptr);
256 setLibcallName(RTLIB::SRL_I128, nullptr);
257 setLibcallName(RTLIB::SRA_I128, nullptr);
260 if (Subtarget->isAAPCS_ABI() &&
261 (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
262 Subtarget->isTargetAndroid())) {
263 static const struct {
264 const RTLIB::Libcall Op;
265 const char * const Name;
266 const CallingConv::ID CC;
267 const ISD::CondCode Cond;
269 // Double-precision floating-point arithmetic helper functions
270 // RTABI chapter 4.1.2, Table 2
271 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
273 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
274 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
276 // Double-precision floating-point comparison helper functions
277 // RTABI chapter 4.1.2, Table 3
278 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
279 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
280 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
281 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
282 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
283 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
284 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
285 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
287 // Single-precision floating-point arithmetic helper functions
288 // RTABI chapter 4.1.2, Table 4
289 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
291 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
292 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294 // Single-precision floating-point comparison helper functions
295 // RTABI chapter 4.1.2, Table 5
296 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
297 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
298 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
299 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
300 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
301 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
302 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
303 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
305 // Floating-point to integer conversions.
306 // RTABI chapter 4.1.2, Table 6
307 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 // Conversions between floating types.
317 // RTABI chapter 4.1.2, Table 7
318 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 // Integer to floating-point conversions.
323 // RTABI chapter 4.1.2, Table 8
324 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 // Long long helper functions
334 // RTABI chapter 4.2, Table 9
335 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 // Integer division functions
341 // RTABI chapter 4.3.1
342 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352 for (const auto &LC : LibraryCalls) {
353 setLibcallName(LC.Op, LC.Name);
354 setLibcallCallingConv(LC.Op, LC.CC);
355 if (LC.Cond != ISD::SETCC_INVALID)
356 setCmpLibcallCC(LC.Op, LC.Cond);
359 // EABI dependent RTLIB
360 if (TM.Options.EABIVersion == EABI::EABI4 ||
361 TM.Options.EABIVersion == EABI::EABI5) {
362 static const struct {
363 const RTLIB::Libcall Op;
364 const char *const Name;
365 const CallingConv::ID CC;
366 const ISD::CondCode Cond;
367 } MemOpsLibraryCalls[] = {
369 // RTABI chapter 4.3.4
370 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
371 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
372 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
375 for (const auto &LC : MemOpsLibraryCalls) {
376 setLibcallName(LC.Op, LC.Name);
377 setLibcallCallingConv(LC.Op, LC.CC);
378 if (LC.Cond != ISD::SETCC_INVALID)
379 setCmpLibcallCC(LC.Op, LC.Cond);
384 if (Subtarget->isTargetWindows()) {
385 static const struct {
386 const RTLIB::Libcall Op;
387 const char * const Name;
388 const CallingConv::ID CC;
390 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
391 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
392 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
393 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
394 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
395 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
396 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
397 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
398 { RTLIB::SDIV_I32, "__rt_sdiv", CallingConv::ARM_AAPCS_VFP },
399 { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
402 for (const auto &LC : LibraryCalls) {
403 setLibcallName(LC.Op, LC.Name);
404 setLibcallCallingConv(LC.Op, LC.CC);
408 // Use divmod compiler-rt calls for iOS 5.0 and later.
409 if (Subtarget->isTargetWatchOS() ||
410 (Subtarget->isTargetIOS() &&
411 !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
412 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
413 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
416 // The half <-> float conversion functions are always soft-float, but are
417 // needed for some targets which use a hard-float calling convention by
419 if (Subtarget->isAAPCS_ABI()) {
420 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
421 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
422 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
424 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
425 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
426 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
429 // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
430 // a __gnu_ prefix (which is the default).
431 if (Subtarget->isTargetAEABI()) {
432 setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
433 setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
434 setLibcallName(RTLIB::FPEXT_F16_F32, "__aeabi_h2f");
437 if (Subtarget->isThumb1Only())
438 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
440 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
441 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
442 !Subtarget->isThumb1Only()) {
443 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
444 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
447 for (MVT VT : MVT::vector_valuetypes()) {
448 for (MVT InnerVT : MVT::vector_valuetypes()) {
449 setTruncStoreAction(VT, InnerVT, Expand);
450 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
451 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
452 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
455 setOperationAction(ISD::MULHS, VT, Expand);
456 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
457 setOperationAction(ISD::MULHU, VT, Expand);
458 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
460 setOperationAction(ISD::BSWAP, VT, Expand);
463 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
464 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
466 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
467 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
469 if (Subtarget->hasNEON()) {
470 addDRTypeForNEON(MVT::v2f32);
471 addDRTypeForNEON(MVT::v8i8);
472 addDRTypeForNEON(MVT::v4i16);
473 addDRTypeForNEON(MVT::v2i32);
474 addDRTypeForNEON(MVT::v1i64);
476 addQRTypeForNEON(MVT::v4f32);
477 addQRTypeForNEON(MVT::v2f64);
478 addQRTypeForNEON(MVT::v16i8);
479 addQRTypeForNEON(MVT::v8i16);
480 addQRTypeForNEON(MVT::v4i32);
481 addQRTypeForNEON(MVT::v2i64);
483 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
484 // neither Neon nor VFP support any arithmetic operations on it.
485 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
486 // supported for v4f32.
487 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
488 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
489 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
490 // FIXME: Code duplication: FDIV and FREM are expanded always, see
491 // ARMTargetLowering::addTypeForNEON method for details.
492 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
493 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
494 // FIXME: Create unittest.
495 // In another words, find a way when "copysign" appears in DAG with vector
497 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
498 // FIXME: Code duplication: SETCC has custom operation action, see
499 // ARMTargetLowering::addTypeForNEON method for details.
500 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
501 // FIXME: Create unittest for FNEG and for FABS.
502 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
503 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
504 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
505 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
506 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
507 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
508 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
509 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
510 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
511 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
512 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
513 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
514 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
515 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
516 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
517 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
518 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
519 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
520 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
522 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
523 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
524 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
525 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
526 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
527 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
528 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
529 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
530 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
531 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
532 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
533 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
534 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
535 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
536 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
538 // Mark v2f32 intrinsics.
539 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
540 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
541 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
542 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
543 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
544 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
545 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
546 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
547 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
548 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
549 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
550 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
551 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
552 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
553 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
555 // Neon does not support some operations on v1i64 and v2i64 types.
556 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
557 // Custom handling for some quad-vector types to detect VMULL.
558 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
559 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
560 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
561 // Custom handling for some vector types to avoid expensive expansions
562 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
563 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
564 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
565 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
566 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
567 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
568 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
569 // a destination type that is wider than the source, and nor does
570 // it have a FP_TO_[SU]INT instruction with a narrower destination than
572 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
573 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
574 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
575 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
577 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
578 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
580 // NEON does not have single instruction CTPOP for vectors with element
581 // types wider than 8-bits. However, custom lowering can leverage the
582 // v8i8/v16i8 vcnt instruction.
583 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
584 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
585 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
586 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
588 // NEON does not have single instruction CTTZ for vectors.
589 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
590 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
591 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
592 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
594 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
595 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
596 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
597 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
599 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
600 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
601 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
602 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
604 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
605 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
606 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
607 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
609 // NEON only has FMA instructions as of VFP4.
610 if (!Subtarget->hasVFP4()) {
611 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
612 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
615 setTargetDAGCombine(ISD::INTRINSIC_VOID);
616 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
617 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
618 setTargetDAGCombine(ISD::SHL);
619 setTargetDAGCombine(ISD::SRL);
620 setTargetDAGCombine(ISD::SRA);
621 setTargetDAGCombine(ISD::SIGN_EXTEND);
622 setTargetDAGCombine(ISD::ZERO_EXTEND);
623 setTargetDAGCombine(ISD::ANY_EXTEND);
624 setTargetDAGCombine(ISD::BUILD_VECTOR);
625 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
626 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
627 setTargetDAGCombine(ISD::STORE);
628 setTargetDAGCombine(ISD::FP_TO_SINT);
629 setTargetDAGCombine(ISD::FP_TO_UINT);
630 setTargetDAGCombine(ISD::FDIV);
631 setTargetDAGCombine(ISD::LOAD);
633 // It is legal to extload from v4i8 to v4i16 or v4i32.
634 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
636 for (MVT VT : MVT::integer_vector_valuetypes()) {
637 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
638 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
639 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
644 // ARM and Thumb2 support UMLAL/SMLAL.
645 if (!Subtarget->isThumb1Only())
646 setTargetDAGCombine(ISD::ADDC);
648 if (Subtarget->isFPOnlySP()) {
649 // When targeting a floating-point unit with only single-precision
650 // operations, f64 is legal for the few double-precision instructions which
651 // are present However, no double-precision operations other than moves,
652 // loads and stores are provided by the hardware.
653 setOperationAction(ISD::FADD, MVT::f64, Expand);
654 setOperationAction(ISD::FSUB, MVT::f64, Expand);
655 setOperationAction(ISD::FMUL, MVT::f64, Expand);
656 setOperationAction(ISD::FMA, MVT::f64, Expand);
657 setOperationAction(ISD::FDIV, MVT::f64, Expand);
658 setOperationAction(ISD::FREM, MVT::f64, Expand);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
660 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
661 setOperationAction(ISD::FNEG, MVT::f64, Expand);
662 setOperationAction(ISD::FABS, MVT::f64, Expand);
663 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
664 setOperationAction(ISD::FSIN, MVT::f64, Expand);
665 setOperationAction(ISD::FCOS, MVT::f64, Expand);
666 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
667 setOperationAction(ISD::FPOW, MVT::f64, Expand);
668 setOperationAction(ISD::FLOG, MVT::f64, Expand);
669 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
670 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
671 setOperationAction(ISD::FEXP, MVT::f64, Expand);
672 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
673 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
674 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
675 setOperationAction(ISD::FRINT, MVT::f64, Expand);
676 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
677 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
678 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
679 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
680 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
681 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
682 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
683 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
684 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
685 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
688 computeRegisterProperties(Subtarget->getRegisterInfo());
690 // ARM does not have floating-point extending loads.
691 for (MVT VT : MVT::fp_valuetypes()) {
692 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
693 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
696 // ... or truncating stores
697 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
698 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
699 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
701 // ARM does not have i1 sign extending load.
702 for (MVT VT : MVT::integer_valuetypes())
703 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
705 // ARM supports all 4 flavors of integer indexed load / store.
706 if (!Subtarget->isThumb1Only()) {
707 for (unsigned im = (unsigned)ISD::PRE_INC;
708 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
709 setIndexedLoadAction(im, MVT::i1, Legal);
710 setIndexedLoadAction(im, MVT::i8, Legal);
711 setIndexedLoadAction(im, MVT::i16, Legal);
712 setIndexedLoadAction(im, MVT::i32, Legal);
713 setIndexedStoreAction(im, MVT::i1, Legal);
714 setIndexedStoreAction(im, MVT::i8, Legal);
715 setIndexedStoreAction(im, MVT::i16, Legal);
716 setIndexedStoreAction(im, MVT::i32, Legal);
720 setOperationAction(ISD::SADDO, MVT::i32, Custom);
721 setOperationAction(ISD::UADDO, MVT::i32, Custom);
722 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
723 setOperationAction(ISD::USUBO, MVT::i32, Custom);
725 // i64 operation support.
726 setOperationAction(ISD::MUL, MVT::i64, Expand);
727 setOperationAction(ISD::MULHU, MVT::i32, Expand);
728 if (Subtarget->isThumb1Only()) {
729 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
730 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
732 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
733 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
734 setOperationAction(ISD::MULHS, MVT::i32, Expand);
736 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
737 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
738 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
739 setOperationAction(ISD::SRL, MVT::i64, Custom);
740 setOperationAction(ISD::SRA, MVT::i64, Custom);
742 if (!Subtarget->isThumb1Only()) {
743 // FIXME: We should do this for Thumb1 as well.
744 setOperationAction(ISD::ADDC, MVT::i32, Custom);
745 setOperationAction(ISD::ADDE, MVT::i32, Custom);
746 setOperationAction(ISD::SUBC, MVT::i32, Custom);
747 setOperationAction(ISD::SUBE, MVT::i32, Custom);
750 if (!Subtarget->isThumb1Only())
751 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
753 // ARM does not have ROTL.
754 setOperationAction(ISD::ROTL, MVT::i32, Expand);
755 for (MVT VT : MVT::vector_valuetypes()) {
756 setOperationAction(ISD::ROTL, VT, Expand);
757 setOperationAction(ISD::ROTR, VT, Expand);
759 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
760 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
761 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
762 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
764 // These just redirect to CTTZ and CTLZ on ARM.
765 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
766 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
768 // @llvm.readcyclecounter requires the Performance Monitors extension.
769 // Default to the 0 expansion on unsupported platforms.
770 // FIXME: Technically there are older ARM CPUs that have
771 // implementation-specific ways of obtaining this information.
772 if (Subtarget->hasPerfMon())
773 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
775 // Only ARMv6 has BSWAP.
776 if (!Subtarget->hasV6Ops())
777 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
779 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
780 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
781 // These are expanded into libcalls if the cpu doesn't have HW divider.
782 setOperationAction(ISD::SDIV, MVT::i32, LibCall);
783 setOperationAction(ISD::UDIV, MVT::i32, LibCall);
786 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
787 setOperationAction(ISD::UDIV, MVT::i32, Custom);
789 setOperationAction(ISD::UDIV, MVT::i64, Custom);
792 setOperationAction(ISD::SREM, MVT::i32, Expand);
793 setOperationAction(ISD::UREM, MVT::i32, Expand);
794 // Register based DivRem for AEABI (RTABI 4.2)
795 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
796 setOperationAction(ISD::SREM, MVT::i64, Custom);
797 setOperationAction(ISD::UREM, MVT::i64, Custom);
799 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
800 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
801 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
802 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
803 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
804 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
805 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
806 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
808 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
809 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
810 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
811 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
812 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
813 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
814 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
815 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
817 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
818 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
820 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
821 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
824 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
825 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
826 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
827 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
829 setOperationAction(ISD::TRAP, MVT::Other, Legal);
831 // Use the default implementation.
832 setOperationAction(ISD::VASTART, MVT::Other, Custom);
833 setOperationAction(ISD::VAARG, MVT::Other, Expand);
834 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
835 setOperationAction(ISD::VAEND, MVT::Other, Expand);
836 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
837 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
839 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
840 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
842 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
844 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
845 // the default expansion. If we are targeting a single threaded system,
846 // then set them all for expand so we can lower them later into their
848 if (TM.Options.ThreadModel == ThreadModel::Single)
849 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
850 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
851 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
852 // to ldrex/strex loops already.
853 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
855 // On v8, we have particularly efficient implementations of atomic fences
856 // if they can be combined with nearby atomic loads and stores.
857 if (!Subtarget->hasV8Ops()) {
858 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
859 setInsertFencesForAtomic(true);
862 // If there's anything we can use as a barrier, go through custom lowering
864 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
865 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
867 // Set them all for expansion, which will force libcalls.
868 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
869 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
870 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
871 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
872 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
873 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
874 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
875 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
876 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
877 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
878 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
879 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
880 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
881 // Unordered/Monotonic case.
882 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
883 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
886 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
888 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
889 if (!Subtarget->hasV6Ops()) {
890 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
891 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
893 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
895 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
896 !Subtarget->isThumb1Only()) {
897 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
898 // iff target supports vfp2.
899 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
900 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
903 // We want to custom lower some of our intrinsics.
904 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
905 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
906 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
907 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
908 if (Subtarget->useSjLjEH())
909 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
911 setOperationAction(ISD::SETCC, MVT::i32, Expand);
912 setOperationAction(ISD::SETCC, MVT::f32, Expand);
913 setOperationAction(ISD::SETCC, MVT::f64, Expand);
914 setOperationAction(ISD::SELECT, MVT::i32, Custom);
915 setOperationAction(ISD::SELECT, MVT::f32, Custom);
916 setOperationAction(ISD::SELECT, MVT::f64, Custom);
917 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
918 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
919 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
921 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
922 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
923 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
924 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
925 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
927 // We don't support sin/cos/fmod/copysign/pow
928 setOperationAction(ISD::FSIN, MVT::f64, Expand);
929 setOperationAction(ISD::FSIN, MVT::f32, Expand);
930 setOperationAction(ISD::FCOS, MVT::f32, Expand);
931 setOperationAction(ISD::FCOS, MVT::f64, Expand);
932 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
933 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
934 setOperationAction(ISD::FREM, MVT::f64, Expand);
935 setOperationAction(ISD::FREM, MVT::f32, Expand);
936 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
937 !Subtarget->isThumb1Only()) {
938 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
939 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
941 setOperationAction(ISD::FPOW, MVT::f64, Expand);
942 setOperationAction(ISD::FPOW, MVT::f32, Expand);
944 if (!Subtarget->hasVFP4()) {
945 setOperationAction(ISD::FMA, MVT::f64, Expand);
946 setOperationAction(ISD::FMA, MVT::f32, Expand);
949 // Various VFP goodness
950 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
951 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
952 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
953 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
954 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
957 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
958 if (!Subtarget->hasFP16()) {
959 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
960 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
964 // Combine sin / cos into one node or libcall if possible.
965 if (Subtarget->hasSinCos()) {
966 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
967 setLibcallName(RTLIB::SINCOS_F64, "sincos");
968 if (Subtarget->isTargetWatchOS()) {
969 setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
970 setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
972 if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
973 // For iOS, we don't want to the normal expansion of a libcall to
974 // sincos. We want to issue a libcall to __sincos_stret.
975 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
976 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
980 // FP-ARMv8 implements a lot of rounding-like FP operations.
981 if (Subtarget->hasFPARMv8()) {
982 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
983 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
984 setOperationAction(ISD::FROUND, MVT::f32, Legal);
985 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
986 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
987 setOperationAction(ISD::FRINT, MVT::f32, Legal);
988 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
989 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
990 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
991 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
992 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
993 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
995 if (!Subtarget->isFPOnlySP()) {
996 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
997 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
998 setOperationAction(ISD::FROUND, MVT::f64, Legal);
999 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1000 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1001 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1002 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1003 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1007 if (Subtarget->hasNEON()) {
1008 // vmin and vmax aren't available in a scalar form, so we use
1009 // a NEON instruction with an undef lane instead.
1010 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1011 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1012 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1013 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1014 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1015 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1018 // We have target-specific dag combine patterns for the following nodes:
1019 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1020 setTargetDAGCombine(ISD::ADD);
1021 setTargetDAGCombine(ISD::SUB);
1022 setTargetDAGCombine(ISD::MUL);
1023 setTargetDAGCombine(ISD::AND);
1024 setTargetDAGCombine(ISD::OR);
1025 setTargetDAGCombine(ISD::XOR);
1027 if (Subtarget->hasV6Ops())
1028 setTargetDAGCombine(ISD::SRL);
1030 setStackPointerRegisterToSaveRestore(ARM::SP);
1032 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1033 !Subtarget->hasVFP2())
1034 setSchedulingPreference(Sched::RegPressure);
1036 setSchedulingPreference(Sched::Hybrid);
1038 //// temporary - rewrite interface to use type
1039 MaxStoresPerMemset = 8;
1040 MaxStoresPerMemsetOptSize = 4;
1041 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1042 MaxStoresPerMemcpyOptSize = 2;
1043 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1044 MaxStoresPerMemmoveOptSize = 2;
1046 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1047 // are at least 4 bytes aligned.
1048 setMinStackArgumentAlignment(4);
1050 // Prefer likely predicted branches to selects on out-of-order cores.
1051 PredictableSelectIsExpensive = Subtarget->isLikeA9();
1053 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1056 bool ARMTargetLowering::useSoftFloat() const {
1057 return Subtarget->useSoftFloat();
1060 // FIXME: It might make sense to define the representative register class as the
1061 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1062 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1063 // SPR's representative would be DPR_VFP2. This should work well if register
1064 // pressure tracking were modified such that a register use would increment the
1065 // pressure of the register class's representative and all of it's super
1066 // classes' representatives transitively. We have not implemented this because
1067 // of the difficulty prior to coalescing of modeling operand register classes
1068 // due to the common occurrence of cross class copies and subregister insertions
1070 std::pair<const TargetRegisterClass *, uint8_t>
1071 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1073 const TargetRegisterClass *RRC = nullptr;
1075 switch (VT.SimpleTy) {
1077 return TargetLowering::findRepresentativeClass(TRI, VT);
1078 // Use DPR as representative register class for all floating point
1079 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1080 // the cost is 1 for both f32 and f64.
1081 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1082 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1083 RRC = &ARM::DPRRegClass;
1084 // When NEON is used for SP, only half of the register file is available
1085 // because operations that define both SP and DP results will be constrained
1086 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1087 // coalescing by double-counting the SP regs. See the FIXME above.
1088 if (Subtarget->useNEONForSinglePrecisionFP())
1091 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1092 case MVT::v4f32: case MVT::v2f64:
1093 RRC = &ARM::DPRRegClass;
1097 RRC = &ARM::DPRRegClass;
1101 RRC = &ARM::DPRRegClass;
1105 return std::make_pair(RRC, Cost);
1108 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1109 switch ((ARMISD::NodeType)Opcode) {
1110 case ARMISD::FIRST_NUMBER: break;
1111 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1112 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1113 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1114 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1115 case ARMISD::CALL: return "ARMISD::CALL";
1116 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1117 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1118 case ARMISD::tCALL: return "ARMISD::tCALL";
1119 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1120 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1121 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1122 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1123 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1124 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1125 case ARMISD::CMP: return "ARMISD::CMP";
1126 case ARMISD::CMN: return "ARMISD::CMN";
1127 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1128 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1129 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1130 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1131 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1133 case ARMISD::CMOV: return "ARMISD::CMOV";
1135 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1136 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1137 case ARMISD::RRX: return "ARMISD::RRX";
1139 case ARMISD::ADDC: return "ARMISD::ADDC";
1140 case ARMISD::ADDE: return "ARMISD::ADDE";
1141 case ARMISD::SUBC: return "ARMISD::SUBC";
1142 case ARMISD::SUBE: return "ARMISD::SUBE";
1144 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1145 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1147 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1148 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1149 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1151 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1153 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1155 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1157 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1159 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1161 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1162 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1164 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1165 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1166 case ARMISD::VCGE: return "ARMISD::VCGE";
1167 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1168 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1169 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1170 case ARMISD::VCGT: return "ARMISD::VCGT";
1171 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1172 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1173 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1174 case ARMISD::VTST: return "ARMISD::VTST";
1176 case ARMISD::VSHL: return "ARMISD::VSHL";
1177 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1178 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1179 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1180 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1181 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1182 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1183 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1184 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1185 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1186 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1187 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1188 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1189 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1190 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1191 case ARMISD::VSLI: return "ARMISD::VSLI";
1192 case ARMISD::VSRI: return "ARMISD::VSRI";
1193 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1194 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1195 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1196 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1197 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1198 case ARMISD::VDUP: return "ARMISD::VDUP";
1199 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1200 case ARMISD::VEXT: return "ARMISD::VEXT";
1201 case ARMISD::VREV64: return "ARMISD::VREV64";
1202 case ARMISD::VREV32: return "ARMISD::VREV32";
1203 case ARMISD::VREV16: return "ARMISD::VREV16";
1204 case ARMISD::VZIP: return "ARMISD::VZIP";
1205 case ARMISD::VUZP: return "ARMISD::VUZP";
1206 case ARMISD::VTRN: return "ARMISD::VTRN";
1207 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1208 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1209 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1210 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1211 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1212 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1213 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1214 case ARMISD::BFI: return "ARMISD::BFI";
1215 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1216 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1217 case ARMISD::VBSL: return "ARMISD::VBSL";
1218 case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1219 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1220 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1221 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1222 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1223 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1224 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1225 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1226 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1227 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1228 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1229 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1230 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1231 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1232 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1233 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1234 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1235 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1236 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1237 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1238 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1243 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1246 return getPointerTy(DL);
1247 return VT.changeVectorElementTypeToInteger();
1250 /// getRegClassFor - Return the register class that should be used for the
1251 /// specified value type.
1252 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1253 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1254 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1255 // load / store 4 to 8 consecutive D registers.
1256 if (Subtarget->hasNEON()) {
1257 if (VT == MVT::v4i64)
1258 return &ARM::QQPRRegClass;
1259 if (VT == MVT::v8i64)
1260 return &ARM::QQQQPRRegClass;
1262 return TargetLowering::getRegClassFor(VT);
1265 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1266 // source/dest is aligned and the copy size is large enough. We therefore want
1267 // to align such objects passed to memory intrinsics.
1268 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1269 unsigned &PrefAlign) const {
1270 if (!isa<MemIntrinsic>(CI))
1273 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1274 // cycle faster than 4-byte aligned LDM.
1275 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1279 // Create a fast isel object.
1281 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1282 const TargetLibraryInfo *libInfo) const {
1283 return ARM::createFastISel(funcInfo, libInfo);
1286 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1287 unsigned NumVals = N->getNumValues();
1289 return Sched::RegPressure;
1291 for (unsigned i = 0; i != NumVals; ++i) {
1292 EVT VT = N->getValueType(i);
1293 if (VT == MVT::Glue || VT == MVT::Other)
1295 if (VT.isFloatingPoint() || VT.isVector())
1299 if (!N->isMachineOpcode())
1300 return Sched::RegPressure;
1302 // Load are scheduled for latency even if there instruction itinerary
1303 // is not available.
1304 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1305 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1307 if (MCID.getNumDefs() == 0)
1308 return Sched::RegPressure;
1309 if (!Itins->isEmpty() &&
1310 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1313 return Sched::RegPressure;
1316 //===----------------------------------------------------------------------===//
1318 //===----------------------------------------------------------------------===//
1320 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1321 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1323 default: llvm_unreachable("Unknown condition code!");
1324 case ISD::SETNE: return ARMCC::NE;
1325 case ISD::SETEQ: return ARMCC::EQ;
1326 case ISD::SETGT: return ARMCC::GT;
1327 case ISD::SETGE: return ARMCC::GE;
1328 case ISD::SETLT: return ARMCC::LT;
1329 case ISD::SETLE: return ARMCC::LE;
1330 case ISD::SETUGT: return ARMCC::HI;
1331 case ISD::SETUGE: return ARMCC::HS;
1332 case ISD::SETULT: return ARMCC::LO;
1333 case ISD::SETULE: return ARMCC::LS;
1337 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1338 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1339 ARMCC::CondCodes &CondCode2) {
1340 CondCode2 = ARMCC::AL;
1342 default: llvm_unreachable("Unknown FP condition!");
1344 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1346 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1348 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1349 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1350 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1351 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1352 case ISD::SETO: CondCode = ARMCC::VC; break;
1353 case ISD::SETUO: CondCode = ARMCC::VS; break;
1354 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1355 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1356 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1358 case ISD::SETULT: CondCode = ARMCC::LT; break;
1360 case ISD::SETULE: CondCode = ARMCC::LE; break;
1362 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1366 //===----------------------------------------------------------------------===//
1367 // Calling Convention Implementation
1368 //===----------------------------------------------------------------------===//
1370 #include "ARMGenCallingConv.inc"
1372 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1373 /// account presence of floating point hardware and calling convention
1374 /// limitations, such as support for variadic functions.
1376 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1377 bool isVarArg) const {
1380 llvm_unreachable("Unsupported calling convention");
1381 case CallingConv::ARM_AAPCS:
1382 case CallingConv::ARM_APCS:
1383 case CallingConv::GHC:
1385 case CallingConv::ARM_AAPCS_VFP:
1386 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1387 case CallingConv::C:
1388 if (!Subtarget->isAAPCS_ABI())
1389 return CallingConv::ARM_APCS;
1390 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1391 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1393 return CallingConv::ARM_AAPCS_VFP;
1395 return CallingConv::ARM_AAPCS;
1396 case CallingConv::Fast:
1397 if (!Subtarget->isAAPCS_ABI()) {
1398 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1399 return CallingConv::Fast;
1400 return CallingConv::ARM_APCS;
1401 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1402 return CallingConv::ARM_AAPCS_VFP;
1404 return CallingConv::ARM_AAPCS;
1408 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1409 /// CallingConvention.
1410 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1412 bool isVarArg) const {
1413 switch (getEffectiveCallingConv(CC, isVarArg)) {
1415 llvm_unreachable("Unsupported calling convention");
1416 case CallingConv::ARM_APCS:
1417 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1418 case CallingConv::ARM_AAPCS:
1419 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1420 case CallingConv::ARM_AAPCS_VFP:
1421 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1422 case CallingConv::Fast:
1423 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1424 case CallingConv::GHC:
1425 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1429 /// LowerCallResult - Lower the result values of a call into the
1430 /// appropriate copies out of appropriate physical registers.
1432 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1433 CallingConv::ID CallConv, bool isVarArg,
1434 const SmallVectorImpl<ISD::InputArg> &Ins,
1435 SDLoc dl, SelectionDAG &DAG,
1436 SmallVectorImpl<SDValue> &InVals,
1437 bool isThisReturn, SDValue ThisVal) const {
1439 // Assign locations to each value returned by this call.
1440 SmallVector<CCValAssign, 16> RVLocs;
1441 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1442 *DAG.getContext(), Call);
1443 CCInfo.AnalyzeCallResult(Ins,
1444 CCAssignFnForNode(CallConv, /* Return*/ true,
1447 // Copy all of the result registers out of their specified physreg.
1448 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1449 CCValAssign VA = RVLocs[i];
1451 // Pass 'this' value directly from the argument to return value, to avoid
1452 // reg unit interference
1453 if (i == 0 && isThisReturn) {
1454 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1455 "unexpected return calling convention register assignment");
1456 InVals.push_back(ThisVal);
1461 if (VA.needsCustom()) {
1462 // Handle f64 or half of a v2f64.
1463 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1465 Chain = Lo.getValue(1);
1466 InFlag = Lo.getValue(2);
1467 VA = RVLocs[++i]; // skip ahead to next loc
1468 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1470 Chain = Hi.getValue(1);
1471 InFlag = Hi.getValue(2);
1472 if (!Subtarget->isLittle())
1474 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1476 if (VA.getLocVT() == MVT::v2f64) {
1477 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1478 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1479 DAG.getConstant(0, dl, MVT::i32));
1481 VA = RVLocs[++i]; // skip ahead to next loc
1482 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1483 Chain = Lo.getValue(1);
1484 InFlag = Lo.getValue(2);
1485 VA = RVLocs[++i]; // skip ahead to next loc
1486 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1487 Chain = Hi.getValue(1);
1488 InFlag = Hi.getValue(2);
1489 if (!Subtarget->isLittle())
1491 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1492 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1493 DAG.getConstant(1, dl, MVT::i32));
1496 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1498 Chain = Val.getValue(1);
1499 InFlag = Val.getValue(2);
1502 switch (VA.getLocInfo()) {
1503 default: llvm_unreachable("Unknown loc info!");
1504 case CCValAssign::Full: break;
1505 case CCValAssign::BCvt:
1506 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1510 InVals.push_back(Val);
1516 /// LowerMemOpCallTo - Store the argument to the stack.
1518 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1519 SDValue StackPtr, SDValue Arg,
1520 SDLoc dl, SelectionDAG &DAG,
1521 const CCValAssign &VA,
1522 ISD::ArgFlagsTy Flags) const {
1523 unsigned LocMemOffset = VA.getLocMemOffset();
1524 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1525 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1527 return DAG.getStore(
1528 Chain, dl, Arg, PtrOff,
1529 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1533 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1534 SDValue Chain, SDValue &Arg,
1535 RegsToPassVector &RegsToPass,
1536 CCValAssign &VA, CCValAssign &NextVA,
1538 SmallVectorImpl<SDValue> &MemOpChains,
1539 ISD::ArgFlagsTy Flags) const {
1541 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1542 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1543 unsigned id = Subtarget->isLittle() ? 0 : 1;
1544 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1546 if (NextVA.isRegLoc())
1547 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1549 assert(NextVA.isMemLoc());
1550 if (!StackPtr.getNode())
1551 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1552 getPointerTy(DAG.getDataLayout()));
1554 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1560 /// LowerCall - Lowering a call into a callseq_start <-
1561 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1564 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1565 SmallVectorImpl<SDValue> &InVals) const {
1566 SelectionDAG &DAG = CLI.DAG;
1568 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1569 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1570 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1571 SDValue Chain = CLI.Chain;
1572 SDValue Callee = CLI.Callee;
1573 bool &isTailCall = CLI.IsTailCall;
1574 CallingConv::ID CallConv = CLI.CallConv;
1575 bool doesNotRet = CLI.DoesNotReturn;
1576 bool isVarArg = CLI.IsVarArg;
1578 MachineFunction &MF = DAG.getMachineFunction();
1579 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1580 bool isThisReturn = false;
1581 bool isSibCall = false;
1582 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1584 // Disable tail calls if they're not supported.
1585 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1589 // Check if it's really possible to do a tail call.
1590 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1591 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1592 Outs, OutVals, Ins, DAG);
1593 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1594 report_fatal_error("failed to perform tail call elimination on a call "
1595 "site marked musttail");
1596 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1597 // detected sibcalls.
1604 // Analyze operands of the call, assigning locations to each operand.
1605 SmallVector<CCValAssign, 16> ArgLocs;
1606 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1607 *DAG.getContext(), Call);
1608 CCInfo.AnalyzeCallOperands(Outs,
1609 CCAssignFnForNode(CallConv, /* Return*/ false,
1612 // Get a count of how many bytes are to be pushed on the stack.
1613 unsigned NumBytes = CCInfo.getNextStackOffset();
1615 // For tail calls, memory operands are available in our caller's stack.
1619 // Adjust the stack pointer for the new arguments...
1620 // These operations are automatically eliminated by the prolog/epilog pass
1622 Chain = DAG.getCALLSEQ_START(Chain,
1623 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1626 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1628 RegsToPassVector RegsToPass;
1629 SmallVector<SDValue, 8> MemOpChains;
1631 // Walk the register/memloc assignments, inserting copies/loads. In the case
1632 // of tail call optimization, arguments are handled later.
1633 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1635 ++i, ++realArgIdx) {
1636 CCValAssign &VA = ArgLocs[i];
1637 SDValue Arg = OutVals[realArgIdx];
1638 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1639 bool isByVal = Flags.isByVal();
1641 // Promote the value if needed.
1642 switch (VA.getLocInfo()) {
1643 default: llvm_unreachable("Unknown loc info!");
1644 case CCValAssign::Full: break;
1645 case CCValAssign::SExt:
1646 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1648 case CCValAssign::ZExt:
1649 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1651 case CCValAssign::AExt:
1652 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1654 case CCValAssign::BCvt:
1655 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1659 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1660 if (VA.needsCustom()) {
1661 if (VA.getLocVT() == MVT::v2f64) {
1662 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1663 DAG.getConstant(0, dl, MVT::i32));
1664 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1665 DAG.getConstant(1, dl, MVT::i32));
1667 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1668 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1670 VA = ArgLocs[++i]; // skip ahead to next loc
1671 if (VA.isRegLoc()) {
1672 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1673 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1675 assert(VA.isMemLoc());
1677 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1678 dl, DAG, VA, Flags));
1681 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1682 StackPtr, MemOpChains, Flags);
1684 } else if (VA.isRegLoc()) {
1685 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1686 assert(VA.getLocVT() == MVT::i32 &&
1687 "unexpected calling convention register assignment");
1688 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1689 "unexpected use of 'returned'");
1690 isThisReturn = true;
1692 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1693 } else if (isByVal) {
1694 assert(VA.isMemLoc());
1695 unsigned offset = 0;
1697 // True if this byval aggregate will be split between registers
1699 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1700 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1702 if (CurByValIdx < ByValArgsCount) {
1704 unsigned RegBegin, RegEnd;
1705 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1708 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1710 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1711 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1712 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1713 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1714 MachinePointerInfo(),
1715 false, false, false,
1716 DAG.InferPtrAlignment(AddArg));
1717 MemOpChains.push_back(Load.getValue(1));
1718 RegsToPass.push_back(std::make_pair(j, Load));
1721 // If parameter size outsides register area, "offset" value
1722 // helps us to calculate stack slot for remained part properly.
1723 offset = RegEnd - RegBegin;
1725 CCInfo.nextInRegsParam();
1728 if (Flags.getByValSize() > 4*offset) {
1729 auto PtrVT = getPointerTy(DAG.getDataLayout());
1730 unsigned LocMemOffset = VA.getLocMemOffset();
1731 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1732 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1733 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1734 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1735 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1737 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1740 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1741 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1742 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1745 } else if (!isSibCall) {
1746 assert(VA.isMemLoc());
1748 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1749 dl, DAG, VA, Flags));
1753 if (!MemOpChains.empty())
1754 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1756 // Build a sequence of copy-to-reg nodes chained together with token chain
1757 // and flag operands which copy the outgoing args into the appropriate regs.
1759 // Tail call byval lowering might overwrite argument registers so in case of
1760 // tail call optimization the copies to registers are lowered later.
1762 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1763 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1764 RegsToPass[i].second, InFlag);
1765 InFlag = Chain.getValue(1);
1768 // For tail calls lower the arguments to the 'real' stack slot.
1770 // Force all the incoming stack arguments to be loaded from the stack
1771 // before any new outgoing arguments are stored to the stack, because the
1772 // outgoing stack slots may alias the incoming argument stack slots, and
1773 // the alias isn't otherwise explicit. This is slightly more conservative
1774 // than necessary, because it means that each store effectively depends
1775 // on every argument instead of just those arguments it would clobber.
1777 // Do not flag preceding copytoreg stuff together with the following stuff.
1779 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1780 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1781 RegsToPass[i].second, InFlag);
1782 InFlag = Chain.getValue(1);
1787 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1788 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1789 // node so that legalize doesn't hack it.
1790 bool isDirect = false;
1791 bool isARMFunc = false;
1792 bool isLocalARMFunc = false;
1793 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1794 auto PtrVt = getPointerTy(DAG.getDataLayout());
1796 if (Subtarget->genLongCalls()) {
1797 assert((Subtarget->isTargetWindows() ||
1798 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1799 "long-calls with non-static relocation model!");
1800 // Handle a global address or an external symbol. If it's not one of
1801 // those, the target's already in a register, so we don't need to do
1803 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1804 const GlobalValue *GV = G->getGlobal();
1805 // Create a constant pool entry for the callee address
1806 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1807 ARMConstantPoolValue *CPV =
1808 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1810 // Get the address of the callee into a register
1811 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1812 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1813 Callee = DAG.getLoad(
1814 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1815 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1817 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1818 const char *Sym = S->getSymbol();
1820 // Create a constant pool entry for the callee address
1821 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1822 ARMConstantPoolValue *CPV =
1823 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1824 ARMPCLabelIndex, 0);
1825 // Get the address of the callee into a register
1826 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1827 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1828 Callee = DAG.getLoad(
1829 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1830 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1833 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1834 const GlobalValue *GV = G->getGlobal();
1836 bool isDef = GV->isStrongDefinitionForLinker();
1837 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1838 getTargetMachine().getRelocationModel() != Reloc::Static;
1839 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1840 // ARM call to a local ARM function is predicable.
1841 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1842 // tBX takes a register source operand.
1843 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1844 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1845 Callee = DAG.getNode(
1846 ARMISD::WrapperPIC, dl, PtrVt,
1847 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1848 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1849 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1850 false, false, true, 0);
1851 } else if (Subtarget->isTargetCOFF()) {
1852 assert(Subtarget->isTargetWindows() &&
1853 "Windows is the only supported COFF target");
1854 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1855 ? ARMII::MO_DLLIMPORT
1856 : ARMII::MO_NO_FLAG;
1858 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1859 if (GV->hasDLLImportStorageClass())
1861 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1862 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1863 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1864 false, false, false, 0);
1866 // On ELF targets for PIC code, direct calls should go through the PLT
1867 unsigned OpFlags = 0;
1868 if (Subtarget->isTargetELF() &&
1869 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1870 OpFlags = ARMII::MO_PLT;
1871 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1873 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1875 bool isStub = Subtarget->isTargetMachO() &&
1876 getTargetMachine().getRelocationModel() != Reloc::Static;
1877 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1878 // tBX takes a register source operand.
1879 const char *Sym = S->getSymbol();
1880 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1881 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1882 ARMConstantPoolValue *CPV =
1883 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1884 ARMPCLabelIndex, 4);
1885 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1886 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1887 Callee = DAG.getLoad(
1888 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1889 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1891 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1892 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1894 unsigned OpFlags = 0;
1895 // On ELF targets for PIC code, direct calls should go through the PLT
1896 if (Subtarget->isTargetELF() &&
1897 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1898 OpFlags = ARMII::MO_PLT;
1899 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1903 // FIXME: handle tail calls differently.
1905 if (Subtarget->isThumb()) {
1906 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1907 CallOpc = ARMISD::CALL_NOLINK;
1909 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1911 if (!isDirect && !Subtarget->hasV5TOps())
1912 CallOpc = ARMISD::CALL_NOLINK;
1913 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1914 // Emit regular call when code size is the priority
1915 !MF.getFunction()->optForMinSize())
1916 // "mov lr, pc; b _foo" to avoid confusing the RSP
1917 CallOpc = ARMISD::CALL_NOLINK;
1919 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1922 std::vector<SDValue> Ops;
1923 Ops.push_back(Chain);
1924 Ops.push_back(Callee);
1926 // Add argument registers to the end of the list so that they are known live
1928 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1929 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1930 RegsToPass[i].second.getValueType()));
1932 // Add a register mask operand representing the call-preserved registers.
1934 const uint32_t *Mask;
1935 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1937 // For 'this' returns, use the R0-preserving mask if applicable
1938 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1940 // Set isThisReturn to false if the calling convention is not one that
1941 // allows 'returned' to be modeled in this way, so LowerCallResult does
1942 // not try to pass 'this' straight through
1943 isThisReturn = false;
1944 Mask = ARI->getCallPreservedMask(MF, CallConv);
1947 Mask = ARI->getCallPreservedMask(MF, CallConv);
1949 assert(Mask && "Missing call preserved mask for calling convention");
1950 Ops.push_back(DAG.getRegisterMask(Mask));
1953 if (InFlag.getNode())
1954 Ops.push_back(InFlag);
1956 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1958 MF.getFrameInfo()->setHasTailCall();
1959 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1962 // Returns a chain and a flag for retval copy to use.
1963 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1964 InFlag = Chain.getValue(1);
1966 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1967 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1969 InFlag = Chain.getValue(1);
1971 // Handle result values, copying them out of physregs into vregs that we
1973 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1974 InVals, isThisReturn,
1975 isThisReturn ? OutVals[0] : SDValue());
1978 /// HandleByVal - Every parameter *after* a byval parameter is passed
1979 /// on the stack. Remember the next parameter register to allocate,
1980 /// and then confiscate the rest of the parameter registers to insure
1982 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1983 unsigned Align) const {
1984 assert((State->getCallOrPrologue() == Prologue ||
1985 State->getCallOrPrologue() == Call) &&
1986 "unhandled ParmContext");
1988 // Byval (as with any stack) slots are always at least 4 byte aligned.
1989 Align = std::max(Align, 4U);
1991 unsigned Reg = State->AllocateReg(GPRArgRegs);
1995 unsigned AlignInRegs = Align / 4;
1996 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1997 for (unsigned i = 0; i < Waste; ++i)
1998 Reg = State->AllocateReg(GPRArgRegs);
2003 unsigned Excess = 4 * (ARM::R4 - Reg);
2005 // Special case when NSAA != SP and parameter size greater than size of
2006 // all remained GPR regs. In that case we can't split parameter, we must
2007 // send it to stack. We also must set NCRN to R4, so waste all
2008 // remained registers.
2009 const unsigned NSAAOffset = State->getNextStackOffset();
2010 if (NSAAOffset != 0 && Size > Excess) {
2011 while (State->AllocateReg(GPRArgRegs))
2016 // First register for byval parameter is the first register that wasn't
2017 // allocated before this method call, so it would be "reg".
2018 // If parameter is small enough to be saved in range [reg, r4), then
2019 // the end (first after last) register would be reg + param-size-in-regs,
2020 // else parameter would be splitted between registers and stack,
2021 // end register would be r4 in this case.
2022 unsigned ByValRegBegin = Reg;
2023 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2024 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2025 // Note, first register is allocated in the beginning of function already,
2026 // allocate remained amount of registers we need.
2027 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2028 State->AllocateReg(GPRArgRegs);
2029 // A byval parameter that is split between registers and memory needs its
2030 // size truncated here.
2031 // In the case where the entire structure fits in registers, we set the
2032 // size in memory to zero.
2033 Size = std::max<int>(Size - Excess, 0);
2036 /// MatchingStackOffset - Return true if the given stack call argument is
2037 /// already available in the same position (relatively) of the caller's
2038 /// incoming argument stack.
2040 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2041 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2042 const TargetInstrInfo *TII) {
2043 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2045 if (Arg.getOpcode() == ISD::CopyFromReg) {
2046 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2047 if (!TargetRegisterInfo::isVirtualRegister(VR))
2049 MachineInstr *Def = MRI->getVRegDef(VR);
2052 if (!Flags.isByVal()) {
2053 if (!TII->isLoadFromStackSlot(Def, FI))
2058 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2059 if (Flags.isByVal())
2060 // ByVal argument is passed in as a pointer but it's now being
2061 // dereferenced. e.g.
2062 // define @foo(%struct.X* %A) {
2063 // tail call @bar(%struct.X* byval %A)
2066 SDValue Ptr = Ld->getBasePtr();
2067 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2070 FI = FINode->getIndex();
2074 assert(FI != INT_MAX);
2075 if (!MFI->isFixedObjectIndex(FI))
2077 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2080 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2081 /// for tail call optimization. Targets which want to do tail call
2082 /// optimization should implement this function.
2084 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2085 CallingConv::ID CalleeCC,
2087 bool isCalleeStructRet,
2088 bool isCallerStructRet,
2089 const SmallVectorImpl<ISD::OutputArg> &Outs,
2090 const SmallVectorImpl<SDValue> &OutVals,
2091 const SmallVectorImpl<ISD::InputArg> &Ins,
2092 SelectionDAG& DAG) const {
2093 const Function *CallerF = DAG.getMachineFunction().getFunction();
2094 CallingConv::ID CallerCC = CallerF->getCallingConv();
2095 bool CCMatch = CallerCC == CalleeCC;
2097 assert(Subtarget->supportsTailCall());
2099 // Look for obvious safe cases to perform tail call optimization that do not
2100 // require ABI changes. This is what gcc calls sibcall.
2102 // Do not sibcall optimize vararg calls unless the call site is not passing
2104 if (isVarArg && !Outs.empty())
2107 // Exception-handling functions need a special set of instructions to indicate
2108 // a return to the hardware. Tail-calling another function would probably
2110 if (CallerF->hasFnAttribute("interrupt"))
2113 // Also avoid sibcall optimization if either caller or callee uses struct
2114 // return semantics.
2115 if (isCalleeStructRet || isCallerStructRet)
2118 // Externally-defined functions with weak linkage should not be
2119 // tail-called on ARM when the OS does not support dynamic
2120 // pre-emption of symbols, as the AAELF spec requires normal calls
2121 // to undefined weak functions to be replaced with a NOP or jump to the
2122 // next instruction. The behaviour of branch instructions in this
2123 // situation (as used for tail calls) is implementation-defined, so we
2124 // cannot rely on the linker replacing the tail call with a return.
2125 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2126 const GlobalValue *GV = G->getGlobal();
2127 const Triple &TT = getTargetMachine().getTargetTriple();
2128 if (GV->hasExternalWeakLinkage() &&
2129 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2133 // If the calling conventions do not match, then we'd better make sure the
2134 // results are returned in the same way as what the caller expects.
2136 SmallVector<CCValAssign, 16> RVLocs1;
2137 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2138 *DAG.getContext(), Call);
2139 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2141 SmallVector<CCValAssign, 16> RVLocs2;
2142 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2143 *DAG.getContext(), Call);
2144 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2146 if (RVLocs1.size() != RVLocs2.size())
2148 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2149 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2151 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2153 if (RVLocs1[i].isRegLoc()) {
2154 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2157 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2163 // If Caller's vararg or byval argument has been split between registers and
2164 // stack, do not perform tail call, since part of the argument is in caller's
2166 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2167 getInfo<ARMFunctionInfo>();
2168 if (AFI_Caller->getArgRegsSaveSize())
2171 // If the callee takes no arguments then go on to check the results of the
2173 if (!Outs.empty()) {
2174 // Check if stack adjustment is needed. For now, do not do this if any
2175 // argument is passed on the stack.
2176 SmallVector<CCValAssign, 16> ArgLocs;
2177 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2178 *DAG.getContext(), Call);
2179 CCInfo.AnalyzeCallOperands(Outs,
2180 CCAssignFnForNode(CalleeCC, false, isVarArg));
2181 if (CCInfo.getNextStackOffset()) {
2182 MachineFunction &MF = DAG.getMachineFunction();
2184 // Check if the arguments are already laid out in the right way as
2185 // the caller's fixed stack objects.
2186 MachineFrameInfo *MFI = MF.getFrameInfo();
2187 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2188 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2189 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2191 ++i, ++realArgIdx) {
2192 CCValAssign &VA = ArgLocs[i];
2193 EVT RegVT = VA.getLocVT();
2194 SDValue Arg = OutVals[realArgIdx];
2195 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2196 if (VA.getLocInfo() == CCValAssign::Indirect)
2198 if (VA.needsCustom()) {
2199 // f64 and vector types are split into multiple registers or
2200 // register/stack-slot combinations. The types will not match
2201 // the registers; give up on memory f64 refs until we figure
2202 // out what to do about this.
2205 if (!ArgLocs[++i].isRegLoc())
2207 if (RegVT == MVT::v2f64) {
2208 if (!ArgLocs[++i].isRegLoc())
2210 if (!ArgLocs[++i].isRegLoc())
2213 } else if (!VA.isRegLoc()) {
2214 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2226 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2227 MachineFunction &MF, bool isVarArg,
2228 const SmallVectorImpl<ISD::OutputArg> &Outs,
2229 LLVMContext &Context) const {
2230 SmallVector<CCValAssign, 16> RVLocs;
2231 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2232 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2236 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2237 SDLoc DL, SelectionDAG &DAG) {
2238 const MachineFunction &MF = DAG.getMachineFunction();
2239 const Function *F = MF.getFunction();
2241 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2243 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2244 // version of the "preferred return address". These offsets affect the return
2245 // instruction if this is a return from PL1 without hypervisor extensions.
2246 // IRQ/FIQ: +4 "subs pc, lr, #4"
2247 // SWI: 0 "subs pc, lr, #0"
2248 // ABORT: +4 "subs pc, lr, #4"
2249 // UNDEF: +4/+2 "subs pc, lr, #0"
2250 // UNDEF varies depending on where the exception came from ARM or Thumb
2251 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2254 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2257 else if (IntKind == "SWI" || IntKind == "UNDEF")
2260 report_fatal_error("Unsupported interrupt attribute. If present, value "
2261 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2263 RetOps.insert(RetOps.begin() + 1,
2264 DAG.getConstant(LROffset, DL, MVT::i32, false));
2266 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2270 ARMTargetLowering::LowerReturn(SDValue Chain,
2271 CallingConv::ID CallConv, bool isVarArg,
2272 const SmallVectorImpl<ISD::OutputArg> &Outs,
2273 const SmallVectorImpl<SDValue> &OutVals,
2274 SDLoc dl, SelectionDAG &DAG) const {
2276 // CCValAssign - represent the assignment of the return value to a location.
2277 SmallVector<CCValAssign, 16> RVLocs;
2279 // CCState - Info about the registers and stack slots.
2280 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2281 *DAG.getContext(), Call);
2283 // Analyze outgoing return values.
2284 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2288 SmallVector<SDValue, 4> RetOps;
2289 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2290 bool isLittleEndian = Subtarget->isLittle();
2292 MachineFunction &MF = DAG.getMachineFunction();
2293 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2294 AFI->setReturnRegsCount(RVLocs.size());
2296 // Copy the result values into the output registers.
2297 for (unsigned i = 0, realRVLocIdx = 0;
2299 ++i, ++realRVLocIdx) {
2300 CCValAssign &VA = RVLocs[i];
2301 assert(VA.isRegLoc() && "Can only return in registers!");
2303 SDValue Arg = OutVals[realRVLocIdx];
2305 switch (VA.getLocInfo()) {
2306 default: llvm_unreachable("Unknown loc info!");
2307 case CCValAssign::Full: break;
2308 case CCValAssign::BCvt:
2309 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2313 if (VA.needsCustom()) {
2314 if (VA.getLocVT() == MVT::v2f64) {
2315 // Extract the first half and return it in two registers.
2316 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2317 DAG.getConstant(0, dl, MVT::i32));
2318 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2319 DAG.getVTList(MVT::i32, MVT::i32), Half);
2321 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2322 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2324 Flag = Chain.getValue(1);
2325 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2326 VA = RVLocs[++i]; // skip ahead to next loc
2327 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2328 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2330 Flag = Chain.getValue(1);
2331 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2332 VA = RVLocs[++i]; // skip ahead to next loc
2334 // Extract the 2nd half and fall through to handle it as an f64 value.
2335 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2336 DAG.getConstant(1, dl, MVT::i32));
2338 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2340 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2341 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2342 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2343 fmrrd.getValue(isLittleEndian ? 0 : 1),
2345 Flag = Chain.getValue(1);
2346 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2347 VA = RVLocs[++i]; // skip ahead to next loc
2348 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2349 fmrrd.getValue(isLittleEndian ? 1 : 0),
2352 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2354 // Guarantee that all emitted copies are
2355 // stuck together, avoiding something bad.
2356 Flag = Chain.getValue(1);
2357 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2360 // Update chain and glue.
2363 RetOps.push_back(Flag);
2365 // CPUs which aren't M-class use a special sequence to return from
2366 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2367 // though we use "subs pc, lr, #N").
2369 // M-class CPUs actually use a normal return sequence with a special
2370 // (hardware-provided) value in LR, so the normal code path works.
2371 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2372 !Subtarget->isMClass()) {
2373 if (Subtarget->isThumb1Only())
2374 report_fatal_error("interrupt attribute is not supported in Thumb1");
2375 return LowerInterruptReturn(RetOps, dl, DAG);
2378 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2381 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2382 if (N->getNumValues() != 1)
2384 if (!N->hasNUsesOfValue(1, 0))
2387 SDValue TCChain = Chain;
2388 SDNode *Copy = *N->use_begin();
2389 if (Copy->getOpcode() == ISD::CopyToReg) {
2390 // If the copy has a glue operand, we conservatively assume it isn't safe to
2391 // perform a tail call.
2392 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2394 TCChain = Copy->getOperand(0);
2395 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2396 SDNode *VMov = Copy;
2397 // f64 returned in a pair of GPRs.
2398 SmallPtrSet<SDNode*, 2> Copies;
2399 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2401 if (UI->getOpcode() != ISD::CopyToReg)
2405 if (Copies.size() > 2)
2408 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2410 SDValue UseChain = UI->getOperand(0);
2411 if (Copies.count(UseChain.getNode()))
2415 // We are at the top of this chain.
2416 // If the copy has a glue operand, we conservatively assume it
2417 // isn't safe to perform a tail call.
2418 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2424 } else if (Copy->getOpcode() == ISD::BITCAST) {
2425 // f32 returned in a single GPR.
2426 if (!Copy->hasOneUse())
2428 Copy = *Copy->use_begin();
2429 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2431 // If the copy has a glue operand, we conservatively assume it isn't safe to
2432 // perform a tail call.
2433 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2435 TCChain = Copy->getOperand(0);
2440 bool HasRet = false;
2441 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2443 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2444 UI->getOpcode() != ARMISD::INTRET_FLAG)
2456 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2457 if (!Subtarget->supportsTailCall())
2461 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2462 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2468 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2469 // and pass the lower and high parts through.
2470 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2472 SDValue WriteValue = Op->getOperand(2);
2474 // This function is only supposed to be called for i64 type argument.
2475 assert(WriteValue.getValueType() == MVT::i64
2476 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2478 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2479 DAG.getConstant(0, DL, MVT::i32));
2480 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2481 DAG.getConstant(1, DL, MVT::i32));
2482 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2483 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2486 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2487 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2488 // one of the above mentioned nodes. It has to be wrapped because otherwise
2489 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2490 // be used to form addressing mode. These wrapped nodes will be selected
2492 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2493 EVT PtrVT = Op.getValueType();
2494 // FIXME there is no actual debug info here
2496 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2498 if (CP->isMachineConstantPoolEntry())
2499 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2500 CP->getAlignment());
2502 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2503 CP->getAlignment());
2504 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2507 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2508 return MachineJumpTableInfo::EK_Inline;
2511 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2512 SelectionDAG &DAG) const {
2513 MachineFunction &MF = DAG.getMachineFunction();
2514 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2515 unsigned ARMPCLabelIndex = 0;
2517 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2518 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2519 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2521 if (RelocM == Reloc::Static) {
2522 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2524 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2525 ARMPCLabelIndex = AFI->createPICLabelUId();
2526 ARMConstantPoolValue *CPV =
2527 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2528 ARMCP::CPBlockAddress, PCAdj);
2529 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2531 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2533 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2534 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2535 false, false, false, 0);
2536 if (RelocM == Reloc::Static)
2538 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2539 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2542 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2544 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2545 SelectionDAG &DAG) const {
2547 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2548 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2549 MachineFunction &MF = DAG.getMachineFunction();
2550 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2551 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2552 ARMConstantPoolValue *CPV =
2553 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2554 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2555 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2556 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2558 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2559 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2560 false, false, false, 0);
2561 SDValue Chain = Argument.getValue(1);
2563 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2564 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2566 // call __tls_get_addr.
2569 Entry.Node = Argument;
2570 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2571 Args.push_back(Entry);
2573 // FIXME: is there useful debug info available here?
2574 TargetLowering::CallLoweringInfo CLI(DAG);
2575 CLI.setDebugLoc(dl).setChain(Chain)
2576 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2577 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2580 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2581 return CallResult.first;
2584 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2585 // "local exec" model.
2587 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2589 TLSModel::Model model) const {
2590 const GlobalValue *GV = GA->getGlobal();
2593 SDValue Chain = DAG.getEntryNode();
2594 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2595 // Get the Thread Pointer
2596 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2598 if (model == TLSModel::InitialExec) {
2599 MachineFunction &MF = DAG.getMachineFunction();
2600 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2601 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2602 // Initial exec model.
2603 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2604 ARMConstantPoolValue *CPV =
2605 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2606 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2608 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2609 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2610 Offset = DAG.getLoad(
2611 PtrVT, dl, Chain, Offset,
2612 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2614 Chain = Offset.getValue(1);
2616 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2617 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2619 Offset = DAG.getLoad(
2620 PtrVT, dl, Chain, Offset,
2621 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2625 assert(model == TLSModel::LocalExec);
2626 ARMConstantPoolValue *CPV =
2627 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2628 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2629 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2630 Offset = DAG.getLoad(
2631 PtrVT, dl, Chain, Offset,
2632 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2636 // The address of the thread local variable is the add of the thread
2637 // pointer with the offset of the variable.
2638 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2642 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2643 // TODO: implement the "local dynamic" model
2644 assert(Subtarget->isTargetELF() &&
2645 "TLS not implemented for non-ELF targets");
2646 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2647 if (DAG.getTarget().Options.EmulatedTLS)
2648 return LowerToTLSEmulatedModel(GA, DAG);
2650 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2653 case TLSModel::GeneralDynamic:
2654 case TLSModel::LocalDynamic:
2655 return LowerToTLSGeneralDynamicModel(GA, DAG);
2656 case TLSModel::InitialExec:
2657 case TLSModel::LocalExec:
2658 return LowerToTLSExecModels(GA, DAG, model);
2660 llvm_unreachable("bogus TLS model");
2663 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2664 SelectionDAG &DAG) const {
2665 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2667 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2668 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2670 !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
2672 MachineFunction &MF = DAG.getMachineFunction();
2673 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2674 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2675 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2677 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2678 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2679 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2680 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2681 /*AddCurrentAddress=*/UseGOT_PREL);
2682 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2683 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2684 SDValue Result = DAG.getLoad(
2685 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2686 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2688 SDValue Chain = Result.getValue(1);
2689 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2690 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2692 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2693 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2694 false, false, false, 0);
2698 // If we have T2 ops, we can materialize the address directly via movt/movw
2699 // pair. This is always cheaper.
2700 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2702 // FIXME: Once remat is capable of dealing with instructions with register
2703 // operands, expand this into two nodes.
2704 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2705 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2707 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2708 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2710 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2711 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2716 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2717 SelectionDAG &DAG) const {
2718 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2720 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2721 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2723 if (Subtarget->useMovt(DAG.getMachineFunction()))
2726 // FIXME: Once remat is capable of dealing with instructions with register
2727 // operands, expand this into multiple nodes
2729 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2731 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2732 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2734 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2735 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2736 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2737 false, false, false, 0);
2741 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2742 SelectionDAG &DAG) const {
2743 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2744 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2745 "Windows on ARM expects to use movw/movt");
2747 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2748 const ARMII::TOF TargetFlags =
2749 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2750 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2756 // FIXME: Once remat is capable of dealing with instructions with register
2757 // operands, expand this into two nodes.
2758 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2759 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2761 if (GV->hasDLLImportStorageClass())
2762 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2763 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2764 false, false, false, 0);
2769 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2771 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2772 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2773 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2774 Op.getOperand(1), Val);
2778 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2780 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2781 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2784 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2785 SelectionDAG &DAG) const {
2787 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2792 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2793 const ARMSubtarget *Subtarget) const {
2794 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2797 default: return SDValue(); // Don't custom lower most intrinsics.
2798 case Intrinsic::arm_rbit: {
2799 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2800 "RBIT intrinsic must have i32 type!");
2801 return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
2803 case Intrinsic::arm_thread_pointer: {
2804 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2805 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2807 case Intrinsic::eh_sjlj_lsda: {
2808 MachineFunction &MF = DAG.getMachineFunction();
2809 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2810 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2811 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2812 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2814 unsigned PCAdj = (RelocM != Reloc::PIC_)
2815 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2816 ARMConstantPoolValue *CPV =
2817 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2818 ARMCP::CPLSDA, PCAdj);
2819 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2820 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2821 SDValue Result = DAG.getLoad(
2822 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2823 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2826 if (RelocM == Reloc::PIC_) {
2827 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2828 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2832 case Intrinsic::arm_neon_vmulls:
2833 case Intrinsic::arm_neon_vmullu: {
2834 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2835 ? ARMISD::VMULLs : ARMISD::VMULLu;
2836 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2837 Op.getOperand(1), Op.getOperand(2));
2839 case Intrinsic::arm_neon_vminnm:
2840 case Intrinsic::arm_neon_vmaxnm: {
2841 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2842 ? ISD::FMINNUM : ISD::FMAXNUM;
2843 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2844 Op.getOperand(1), Op.getOperand(2));
2846 case Intrinsic::arm_neon_vminu:
2847 case Intrinsic::arm_neon_vmaxu: {
2848 if (Op.getValueType().isFloatingPoint())
2850 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2851 ? ISD::UMIN : ISD::UMAX;
2852 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2853 Op.getOperand(1), Op.getOperand(2));
2855 case Intrinsic::arm_neon_vmins:
2856 case Intrinsic::arm_neon_vmaxs: {
2857 // v{min,max}s is overloaded between signed integers and floats.
2858 if (!Op.getValueType().isFloatingPoint()) {
2859 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2860 ? ISD::SMIN : ISD::SMAX;
2861 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2862 Op.getOperand(1), Op.getOperand(2));
2864 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2865 ? ISD::FMINNAN : ISD::FMAXNAN;
2866 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2867 Op.getOperand(1), Op.getOperand(2));
2872 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2873 const ARMSubtarget *Subtarget) {
2874 // FIXME: handle "fence singlethread" more efficiently.
2876 if (!Subtarget->hasDataBarrier()) {
2877 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2878 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2880 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2881 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2882 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2883 DAG.getConstant(0, dl, MVT::i32));
2886 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2887 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2888 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2889 if (Subtarget->isMClass()) {
2890 // Only a full system barrier exists in the M-class architectures.
2891 Domain = ARM_MB::SY;
2892 } else if (Subtarget->isSwift() && Ord == Release) {
2893 // Swift happens to implement ISHST barriers in a way that's compatible with
2894 // Release semantics but weaker than ISH so we'd be fools not to use
2895 // it. Beware: other processors probably don't!
2896 Domain = ARM_MB::ISHST;
2899 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2900 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2901 DAG.getConstant(Domain, dl, MVT::i32));
2904 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2905 const ARMSubtarget *Subtarget) {
2906 // ARM pre v5TE and Thumb1 does not have preload instructions.
2907 if (!(Subtarget->isThumb2() ||
2908 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2909 // Just preserve the chain.
2910 return Op.getOperand(0);
2913 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2915 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2916 // ARMv7 with MP extension has PLDW.
2917 return Op.getOperand(0);
2919 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2920 if (Subtarget->isThumb()) {
2922 isRead = ~isRead & 1;
2923 isData = ~isData & 1;
2926 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2927 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2928 DAG.getConstant(isData, dl, MVT::i32));
2931 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2932 MachineFunction &MF = DAG.getMachineFunction();
2933 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2935 // vastart just stores the address of the VarArgsFrameIndex slot into the
2936 // memory location argument.
2938 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2939 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2940 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2941 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2942 MachinePointerInfo(SV), false, false, 0);
2946 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2947 SDValue &Root, SelectionDAG &DAG,
2949 MachineFunction &MF = DAG.getMachineFunction();
2950 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2952 const TargetRegisterClass *RC;
2953 if (AFI->isThumb1OnlyFunction())
2954 RC = &ARM::tGPRRegClass;
2956 RC = &ARM::GPRRegClass;
2958 // Transform the arguments stored in physical registers into virtual ones.
2959 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2960 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2963 if (NextVA.isMemLoc()) {
2964 MachineFrameInfo *MFI = MF.getFrameInfo();
2965 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2967 // Create load node to retrieve arguments from the stack.
2968 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2969 ArgValue2 = DAG.getLoad(
2970 MVT::i32, dl, Root, FIN,
2971 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2974 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2975 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2977 if (!Subtarget->isLittle())
2978 std::swap (ArgValue, ArgValue2);
2979 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2982 // The remaining GPRs hold either the beginning of variable-argument
2983 // data, or the beginning of an aggregate passed by value (usually
2984 // byval). Either way, we allocate stack slots adjacent to the data
2985 // provided by our caller, and store the unallocated registers there.
2986 // If this is a variadic function, the va_list pointer will begin with
2987 // these values; otherwise, this reassembles a (byval) structure that
2988 // was split between registers and memory.
2989 // Return: The frame index registers were stored into.
2991 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2992 SDLoc dl, SDValue &Chain,
2993 const Value *OrigArg,
2994 unsigned InRegsParamRecordIdx,
2996 unsigned ArgSize) const {
2997 // Currently, two use-cases possible:
2998 // Case #1. Non-var-args function, and we meet first byval parameter.
2999 // Setup first unallocated register as first byval register;
3000 // eat all remained registers
3001 // (these two actions are performed by HandleByVal method).
3002 // Then, here, we initialize stack frame with
3003 // "store-reg" instructions.
3004 // Case #2. Var-args function, that doesn't contain byval parameters.
3005 // The same: eat all remained unallocated registers,
3006 // initialize stack frame.
3008 MachineFunction &MF = DAG.getMachineFunction();
3009 MachineFrameInfo *MFI = MF.getFrameInfo();
3010 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3011 unsigned RBegin, REnd;
3012 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3013 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3015 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3016 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3021 ArgOffset = -4 * (ARM::R4 - RBegin);
3023 auto PtrVT = getPointerTy(DAG.getDataLayout());
3024 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3025 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3027 SmallVector<SDValue, 4> MemOps;
3028 const TargetRegisterClass *RC =
3029 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3031 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3032 unsigned VReg = MF.addLiveIn(Reg, RC);
3033 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3035 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3036 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3037 MemOps.push_back(Store);
3038 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3041 if (!MemOps.empty())
3042 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3046 // Setup stack frame, the va_list pointer will start from.
3048 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3049 SDLoc dl, SDValue &Chain,
3051 unsigned TotalArgRegsSaveSize,
3052 bool ForceMutable) const {
3053 MachineFunction &MF = DAG.getMachineFunction();
3054 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3056 // Try to store any remaining integer argument regs
3057 // to their spots on the stack so that they may be loaded by deferencing
3058 // the result of va_next.
3059 // If there is no regs to be stored, just point address after last
3060 // argument passed via stack.
3061 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3062 CCInfo.getInRegsParamsCount(),
3063 CCInfo.getNextStackOffset(), 4);
3064 AFI->setVarArgsFrameIndex(FrameIndex);
3068 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3069 CallingConv::ID CallConv, bool isVarArg,
3070 const SmallVectorImpl<ISD::InputArg>
3072 SDLoc dl, SelectionDAG &DAG,
3073 SmallVectorImpl<SDValue> &InVals)
3075 MachineFunction &MF = DAG.getMachineFunction();
3076 MachineFrameInfo *MFI = MF.getFrameInfo();
3078 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3080 // Assign locations to all of the incoming arguments.
3081 SmallVector<CCValAssign, 16> ArgLocs;
3082 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3083 *DAG.getContext(), Prologue);
3084 CCInfo.AnalyzeFormalArguments(Ins,
3085 CCAssignFnForNode(CallConv, /* Return*/ false,
3088 SmallVector<SDValue, 16> ArgValues;
3090 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3091 unsigned CurArgIdx = 0;
3093 // Initially ArgRegsSaveSize is zero.
3094 // Then we increase this value each time we meet byval parameter.
3095 // We also increase this value in case of varargs function.
3096 AFI->setArgRegsSaveSize(0);
3098 // Calculate the amount of stack space that we need to allocate to store
3099 // byval and variadic arguments that are passed in registers.
3100 // We need to know this before we allocate the first byval or variadic
3101 // argument, as they will be allocated a stack slot below the CFA (Canonical
3102 // Frame Address, the stack pointer at entry to the function).
3103 unsigned ArgRegBegin = ARM::R4;
3104 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3105 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3108 CCValAssign &VA = ArgLocs[i];
3109 unsigned Index = VA.getValNo();
3110 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3111 if (!Flags.isByVal())
3114 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3115 unsigned RBegin, REnd;
3116 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3117 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3119 CCInfo.nextInRegsParam();
3121 CCInfo.rewindByValRegsInfo();
3123 int lastInsIndex = -1;
3124 if (isVarArg && MFI->hasVAStart()) {
3125 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3126 if (RegIdx != array_lengthof(GPRArgRegs))
3127 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3130 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3131 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3132 auto PtrVT = getPointerTy(DAG.getDataLayout());
3134 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3135 CCValAssign &VA = ArgLocs[i];
3136 if (Ins[VA.getValNo()].isOrigArg()) {
3137 std::advance(CurOrigArg,
3138 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3139 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3141 // Arguments stored in registers.
3142 if (VA.isRegLoc()) {
3143 EVT RegVT = VA.getLocVT();
3145 if (VA.needsCustom()) {
3146 // f64 and vector types are split up into multiple registers or
3147 // combinations of registers and stack slots.
3148 if (VA.getLocVT() == MVT::v2f64) {
3149 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3151 VA = ArgLocs[++i]; // skip ahead to next loc
3153 if (VA.isMemLoc()) {
3154 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3155 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3156 ArgValue2 = DAG.getLoad(
3157 MVT::f64, dl, Chain, FIN,
3158 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3159 false, false, false, 0);
3161 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3164 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3165 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3166 ArgValue, ArgValue1,
3167 DAG.getIntPtrConstant(0, dl));
3168 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3169 ArgValue, ArgValue2,
3170 DAG.getIntPtrConstant(1, dl));
3172 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3175 const TargetRegisterClass *RC;
3177 if (RegVT == MVT::f32)
3178 RC = &ARM::SPRRegClass;
3179 else if (RegVT == MVT::f64)
3180 RC = &ARM::DPRRegClass;
3181 else if (RegVT == MVT::v2f64)
3182 RC = &ARM::QPRRegClass;
3183 else if (RegVT == MVT::i32)
3184 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3185 : &ARM::GPRRegClass;
3187 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3189 // Transform the arguments in physical registers into virtual ones.
3190 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3191 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3194 // If this is an 8 or 16-bit value, it is really passed promoted
3195 // to 32 bits. Insert an assert[sz]ext to capture this, then
3196 // truncate to the right size.
3197 switch (VA.getLocInfo()) {
3198 default: llvm_unreachable("Unknown loc info!");
3199 case CCValAssign::Full: break;
3200 case CCValAssign::BCvt:
3201 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3203 case CCValAssign::SExt:
3204 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3205 DAG.getValueType(VA.getValVT()));
3206 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3208 case CCValAssign::ZExt:
3209 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3210 DAG.getValueType(VA.getValVT()));
3211 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3215 InVals.push_back(ArgValue);
3217 } else { // VA.isRegLoc()
3220 assert(VA.isMemLoc());
3221 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3223 int index = VA.getValNo();
3225 // Some Ins[] entries become multiple ArgLoc[] entries.
3226 // Process them only once.
3227 if (index != lastInsIndex)
3229 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3230 // FIXME: For now, all byval parameter objects are marked mutable.
3231 // This can be changed with more analysis.
3232 // In case of tail call optimization mark all arguments mutable.
3233 // Since they could be overwritten by lowering of arguments in case of
3235 if (Flags.isByVal()) {
3236 assert(Ins[index].isOrigArg() &&
3237 "Byval arguments cannot be implicit");
3238 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3240 int FrameIndex = StoreByValRegs(
3241 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3242 VA.getLocMemOffset(), Flags.getByValSize());
3243 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3244 CCInfo.nextInRegsParam();
3246 unsigned FIOffset = VA.getLocMemOffset();
3247 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3250 // Create load nodes to retrieve arguments from the stack.
3251 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3252 InVals.push_back(DAG.getLoad(
3253 VA.getValVT(), dl, Chain, FIN,
3254 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3255 false, false, false, 0));
3257 lastInsIndex = index;
3263 if (isVarArg && MFI->hasVAStart())
3264 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3265 CCInfo.getNextStackOffset(),
3266 TotalArgRegsSaveSize);
3268 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3273 /// isFloatingPointZero - Return true if this is +0.0.
3274 static bool isFloatingPointZero(SDValue Op) {
3275 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3276 return CFP->getValueAPF().isPosZero();
3277 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3278 // Maybe this has already been legalized into the constant pool?
3279 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3280 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3281 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3282 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3283 return CFP->getValueAPF().isPosZero();
3285 } else if (Op->getOpcode() == ISD::BITCAST &&
3286 Op->getValueType(0) == MVT::f64) {
3287 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3288 // created by LowerConstantFP().
3289 SDValue BitcastOp = Op->getOperand(0);
3290 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3291 isNullConstant(BitcastOp->getOperand(0)))
3297 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3298 /// the given operands.
3300 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3301 SDValue &ARMcc, SelectionDAG &DAG,
3303 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3304 unsigned C = RHSC->getZExtValue();
3305 if (!isLegalICmpImmediate(C)) {
3306 // Constant does not fit, try adjusting it by one?
3311 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3312 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3313 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3318 if (C != 0 && isLegalICmpImmediate(C-1)) {
3319 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3320 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3325 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3326 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3327 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3332 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3333 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3334 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3341 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3342 ARMISD::NodeType CompareType;
3345 CompareType = ARMISD::CMP;
3350 CompareType = ARMISD::CMPZ;
3353 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3354 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3357 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3359 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3361 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3363 if (!isFloatingPointZero(RHS))
3364 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3366 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3367 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3370 /// duplicateCmp - Glue values can have only one use, so this function
3371 /// duplicates a comparison node.
3373 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3374 unsigned Opc = Cmp.getOpcode();
3376 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3377 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3379 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3380 Cmp = Cmp.getOperand(0);
3381 Opc = Cmp.getOpcode();
3382 if (Opc == ARMISD::CMPFP)
3383 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3385 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3386 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3388 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3391 std::pair<SDValue, SDValue>
3392 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3393 SDValue &ARMcc) const {
3394 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3396 SDValue Value, OverflowCmp;
3397 SDValue LHS = Op.getOperand(0);
3398 SDValue RHS = Op.getOperand(1);
3401 // FIXME: We are currently always generating CMPs because we don't support
3402 // generating CMN through the backend. This is not as good as the natural
3403 // CMP case because it causes a register dependency and cannot be folded
3406 switch (Op.getOpcode()) {
3408 llvm_unreachable("Unknown overflow instruction!");
3410 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3411 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3412 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3415 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3416 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3417 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3420 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3421 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3422 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3425 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3426 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3427 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3431 return std::make_pair(Value, OverflowCmp);
3436 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3437 // Let legalize expand this if it isn't a legal type yet.
3438 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3441 SDValue Value, OverflowCmp;
3443 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3444 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3446 // We use 0 and 1 as false and true values.
3447 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3448 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3449 EVT VT = Op.getValueType();
3451 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3452 ARMcc, CCR, OverflowCmp);
3454 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3455 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3459 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3460 SDValue Cond = Op.getOperand(0);
3461 SDValue SelectTrue = Op.getOperand(1);
3462 SDValue SelectFalse = Op.getOperand(2);
3464 unsigned Opc = Cond.getOpcode();
3466 if (Cond.getResNo() == 1 &&
3467 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3468 Opc == ISD::USUBO)) {
3469 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3472 SDValue Value, OverflowCmp;
3474 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3475 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3476 EVT VT = Op.getValueType();
3478 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3484 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3485 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3487 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3488 const ConstantSDNode *CMOVTrue =
3489 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3490 const ConstantSDNode *CMOVFalse =
3491 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3493 if (CMOVTrue && CMOVFalse) {
3494 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3495 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3499 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3501 False = SelectFalse;
3502 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3507 if (True.getNode() && False.getNode()) {
3508 EVT VT = Op.getValueType();
3509 SDValue ARMcc = Cond.getOperand(2);
3510 SDValue CCR = Cond.getOperand(3);
3511 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3512 assert(True.getValueType() == VT);
3513 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3518 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3519 // undefined bits before doing a full-word comparison with zero.
3520 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3521 DAG.getConstant(1, dl, Cond.getValueType()));
3523 return DAG.getSelectCC(dl, Cond,
3524 DAG.getConstant(0, dl, Cond.getValueType()),
3525 SelectTrue, SelectFalse, ISD::SETNE);
3528 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3529 bool &swpCmpOps, bool &swpVselOps) {
3530 // Start by selecting the GE condition code for opcodes that return true for
3532 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3534 CondCode = ARMCC::GE;
3536 // and GT for opcodes that return false for 'equality'.
3537 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3539 CondCode = ARMCC::GT;
3541 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3542 // to swap the compare operands.
3543 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3547 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3548 // If we have an unordered opcode, we need to swap the operands to the VSEL
3549 // instruction (effectively negating the condition).
3551 // This also has the effect of swapping which one of 'less' or 'greater'
3552 // returns true, so we also swap the compare operands. It also switches
3553 // whether we return true for 'equality', so we compensate by picking the
3554 // opposite condition code to our original choice.
3555 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3556 CC == ISD::SETUGT) {
3557 swpCmpOps = !swpCmpOps;
3558 swpVselOps = !swpVselOps;
3559 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3562 // 'ordered' is 'anything but unordered', so use the VS condition code and
3563 // swap the VSEL operands.
3564 if (CC == ISD::SETO) {
3565 CondCode = ARMCC::VS;
3569 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3570 // code and swap the VSEL operands.
3571 if (CC == ISD::SETUNE) {
3572 CondCode = ARMCC::EQ;
3577 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3578 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3579 SDValue Cmp, SelectionDAG &DAG) const {
3580 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3581 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3582 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3583 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3584 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3586 SDValue TrueLow = TrueVal.getValue(0);
3587 SDValue TrueHigh = TrueVal.getValue(1);
3588 SDValue FalseLow = FalseVal.getValue(0);
3589 SDValue FalseHigh = FalseVal.getValue(1);
3591 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3593 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3594 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3596 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3598 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3603 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3604 EVT VT = Op.getValueType();
3605 SDValue LHS = Op.getOperand(0);
3606 SDValue RHS = Op.getOperand(1);
3607 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3608 SDValue TrueVal = Op.getOperand(2);
3609 SDValue FalseVal = Op.getOperand(3);
3612 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3613 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3616 // If softenSetCCOperands only returned one value, we should compare it to
3618 if (!RHS.getNode()) {
3619 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3624 if (LHS.getValueType() == MVT::i32) {
3625 // Try to generate VSEL on ARMv8.
3626 // The VSEL instruction can't use all the usual ARM condition
3627 // codes: it only has two bits to select the condition code, so it's
3628 // constrained to use only GE, GT, VS and EQ.
3630 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3631 // swap the operands of the previous compare instruction (effectively
3632 // inverting the compare condition, swapping 'less' and 'greater') and
3633 // sometimes need to swap the operands to the VSEL (which inverts the
3634 // condition in the sense of firing whenever the previous condition didn't)
3635 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3636 TrueVal.getValueType() == MVT::f64)) {
3637 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3638 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3639 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3640 CC = ISD::getSetCCInverse(CC, true);
3641 std::swap(TrueVal, FalseVal);
3646 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3647 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3648 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3651 ARMCC::CondCodes CondCode, CondCode2;
3652 FPCCToARMCC(CC, CondCode, CondCode2);
3654 // Try to generate VMAXNM/VMINNM on ARMv8.
3655 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3656 TrueVal.getValueType() == MVT::f64)) {
3657 bool swpCmpOps = false;
3658 bool swpVselOps = false;
3659 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3661 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3662 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3664 std::swap(LHS, RHS);
3666 std::swap(TrueVal, FalseVal);
3670 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3671 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3672 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3673 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3674 if (CondCode2 != ARMCC::AL) {
3675 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3676 // FIXME: Needs another CMP because flag can have but one use.
3677 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3678 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3683 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3684 /// to morph to an integer compare sequence.
3685 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3686 const ARMSubtarget *Subtarget) {
3687 SDNode *N = Op.getNode();
3688 if (!N->hasOneUse())
3689 // Otherwise it requires moving the value from fp to integer registers.
3691 if (!N->getNumValues())
3693 EVT VT = Op.getValueType();
3694 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3695 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3696 // vmrs are very slow, e.g. cortex-a8.
3699 if (isFloatingPointZero(Op)) {
3703 return ISD::isNormalLoad(N);
3706 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3707 if (isFloatingPointZero(Op))
3708 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3710 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3711 return DAG.getLoad(MVT::i32, SDLoc(Op),
3712 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3713 Ld->isVolatile(), Ld->isNonTemporal(),
3714 Ld->isInvariant(), Ld->getAlignment());
3716 llvm_unreachable("Unknown VFP cmp argument!");
3719 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3720 SDValue &RetVal1, SDValue &RetVal2) {
3723 if (isFloatingPointZero(Op)) {
3724 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3725 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3729 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3730 SDValue Ptr = Ld->getBasePtr();
3731 RetVal1 = DAG.getLoad(MVT::i32, dl,
3732 Ld->getChain(), Ptr,
3733 Ld->getPointerInfo(),
3734 Ld->isVolatile(), Ld->isNonTemporal(),
3735 Ld->isInvariant(), Ld->getAlignment());
3737 EVT PtrType = Ptr.getValueType();
3738 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3739 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3740 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3741 RetVal2 = DAG.getLoad(MVT::i32, dl,
3742 Ld->getChain(), NewPtr,
3743 Ld->getPointerInfo().getWithOffset(4),
3744 Ld->isVolatile(), Ld->isNonTemporal(),
3745 Ld->isInvariant(), NewAlign);
3749 llvm_unreachable("Unknown VFP cmp argument!");
3752 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3753 /// f32 and even f64 comparisons to integer ones.
3755 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3756 SDValue Chain = Op.getOperand(0);
3757 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3758 SDValue LHS = Op.getOperand(2);
3759 SDValue RHS = Op.getOperand(3);
3760 SDValue Dest = Op.getOperand(4);
3763 bool LHSSeenZero = false;
3764 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3765 bool RHSSeenZero = false;
3766 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3767 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3768 // If unsafe fp math optimization is enabled and there are no other uses of
3769 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3770 // to an integer comparison.
3771 if (CC == ISD::SETOEQ)
3773 else if (CC == ISD::SETUNE)
3776 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3778 if (LHS.getValueType() == MVT::f32) {
3779 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3780 bitcastf32Toi32(LHS, DAG), Mask);
3781 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3782 bitcastf32Toi32(RHS, DAG), Mask);
3783 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3784 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3785 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3786 Chain, Dest, ARMcc, CCR, Cmp);
3791 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3792 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3793 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3794 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3795 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3796 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3797 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3798 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3799 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3805 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3806 SDValue Chain = Op.getOperand(0);
3807 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3808 SDValue LHS = Op.getOperand(2);
3809 SDValue RHS = Op.getOperand(3);
3810 SDValue Dest = Op.getOperand(4);
3813 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3814 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3817 // If softenSetCCOperands only returned one value, we should compare it to
3819 if (!RHS.getNode()) {
3820 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3825 if (LHS.getValueType() == MVT::i32) {
3827 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3828 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3829 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3830 Chain, Dest, ARMcc, CCR, Cmp);
3833 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3835 if (getTargetMachine().Options.UnsafeFPMath &&
3836 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3837 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3838 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3839 if (Result.getNode())
3843 ARMCC::CondCodes CondCode, CondCode2;
3844 FPCCToARMCC(CC, CondCode, CondCode2);
3846 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3847 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3848 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3849 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3850 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3851 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3852 if (CondCode2 != ARMCC::AL) {
3853 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3854 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3855 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3860 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3861 SDValue Chain = Op.getOperand(0);
3862 SDValue Table = Op.getOperand(1);
3863 SDValue Index = Op.getOperand(2);
3866 EVT PTy = getPointerTy(DAG.getDataLayout());
3867 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3868 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3869 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3870 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3871 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3872 if (Subtarget->isThumb2()) {
3873 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3874 // which does another jump to the destination. This also makes it easier
3875 // to translate it to TBB / TBH later.
3876 // FIXME: This might not work if the function is extremely large.
3877 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3878 Addr, Op.getOperand(2), JTI);
3880 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3882 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3883 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3884 false, false, false, 0);
3885 Chain = Addr.getValue(1);
3886 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3887 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3890 DAG.getLoad(PTy, dl, Chain, Addr,
3891 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3892 false, false, false, 0);
3893 Chain = Addr.getValue(1);
3894 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3898 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3899 EVT VT = Op.getValueType();
3902 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3903 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3905 return DAG.UnrollVectorOp(Op.getNode());
3908 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3909 "Invalid type for custom lowering!");
3910 if (VT != MVT::v4i16)
3911 return DAG.UnrollVectorOp(Op.getNode());
3913 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3914 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3917 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3918 EVT VT = Op.getValueType();
3920 return LowerVectorFP_TO_INT(Op, DAG);
3921 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3923 if (Op.getOpcode() == ISD::FP_TO_SINT)
3924 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3927 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3929 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3930 /*isSigned*/ false, SDLoc(Op)).first;
3936 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3937 EVT VT = Op.getValueType();
3940 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3941 if (VT.getVectorElementType() == MVT::f32)
3943 return DAG.UnrollVectorOp(Op.getNode());
3946 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3947 "Invalid type for custom lowering!");
3948 if (VT != MVT::v4f32)
3949 return DAG.UnrollVectorOp(Op.getNode());
3953 switch (Op.getOpcode()) {
3954 default: llvm_unreachable("Invalid opcode!");
3955 case ISD::SINT_TO_FP:
3956 CastOpc = ISD::SIGN_EXTEND;
3957 Opc = ISD::SINT_TO_FP;
3959 case ISD::UINT_TO_FP:
3960 CastOpc = ISD::ZERO_EXTEND;
3961 Opc = ISD::UINT_TO_FP;
3965 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3966 return DAG.getNode(Opc, dl, VT, Op);
3969 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3970 EVT VT = Op.getValueType();
3972 return LowerVectorINT_TO_FP(Op, DAG);
3973 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3975 if (Op.getOpcode() == ISD::SINT_TO_FP)
3976 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3979 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3981 return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3982 /*isSigned*/ false, SDLoc(Op)).first;
3988 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3989 // Implement fcopysign with a fabs and a conditional fneg.
3990 SDValue Tmp0 = Op.getOperand(0);
3991 SDValue Tmp1 = Op.getOperand(1);
3993 EVT VT = Op.getValueType();
3994 EVT SrcVT = Tmp1.getValueType();
3995 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3996 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3997 bool UseNEON = !InGPR && Subtarget->hasNEON();
4000 // Use VBSL to copy the sign bit.
4001 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4002 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4003 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4004 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4006 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4007 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4008 DAG.getConstant(32, dl, MVT::i32));
4009 else /*if (VT == MVT::f32)*/
4010 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4011 if (SrcVT == MVT::f32) {
4012 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4014 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4015 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4016 DAG.getConstant(32, dl, MVT::i32));
4017 } else if (VT == MVT::f32)
4018 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4019 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4020 DAG.getConstant(32, dl, MVT::i32));
4021 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4022 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4024 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4026 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4027 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4028 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4030 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4031 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4032 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4033 if (VT == MVT::f32) {
4034 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4035 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4036 DAG.getConstant(0, dl, MVT::i32));
4038 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4044 // Bitcast operand 1 to i32.
4045 if (SrcVT == MVT::f64)
4046 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4048 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4050 // Or in the signbit with integer operations.
4051 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4052 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4053 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4054 if (VT == MVT::f32) {
4055 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4056 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4057 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4058 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4061 // f64: Or the high part with signbit and then combine two parts.
4062 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4064 SDValue Lo = Tmp0.getValue(0);
4065 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4066 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4067 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4070 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4071 MachineFunction &MF = DAG.getMachineFunction();
4072 MachineFrameInfo *MFI = MF.getFrameInfo();
4073 MFI->setReturnAddressIsTaken(true);
4075 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4078 EVT VT = Op.getValueType();
4080 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4082 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4083 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4084 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4085 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4086 MachinePointerInfo(), false, false, false, 0);
4089 // Return LR, which contains the return address. Mark it an implicit live-in.
4090 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4091 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4094 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4095 const ARMBaseRegisterInfo &ARI =
4096 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4097 MachineFunction &MF = DAG.getMachineFunction();
4098 MachineFrameInfo *MFI = MF.getFrameInfo();
4099 MFI->setFrameAddressIsTaken(true);
4101 EVT VT = Op.getValueType();
4102 SDLoc dl(Op); // FIXME probably not meaningful
4103 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4104 unsigned FrameReg = ARI.getFrameRegister(MF);
4105 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4107 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4108 MachinePointerInfo(),
4109 false, false, false, 0);
4113 // FIXME? Maybe this could be a TableGen attribute on some registers and
4114 // this table could be generated automatically from RegInfo.
4115 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4116 SelectionDAG &DAG) const {
4117 unsigned Reg = StringSwitch<unsigned>(RegName)
4118 .Case("sp", ARM::SP)
4122 report_fatal_error(Twine("Invalid register name \""
4123 + StringRef(RegName) + "\"."));
4126 // Result is 64 bit value so split into two 32 bit values and return as a
4128 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4129 SelectionDAG &DAG) {
4132 // This function is only supposed to be called for i64 type destination.
4133 assert(N->getValueType(0) == MVT::i64
4134 && "ExpandREAD_REGISTER called for non-i64 type result.");
4136 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4137 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4141 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4143 Results.push_back(Read.getOperand(0));
4146 /// ExpandBITCAST - If the target supports VFP, this function is called to
4147 /// expand a bit convert where either the source or destination type is i64 to
4148 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4149 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4150 /// vectors), since the legalizer won't know what to do with that.
4151 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4152 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4154 SDValue Op = N->getOperand(0);
4156 // This function is only supposed to be called for i64 types, either as the
4157 // source or destination of the bit convert.
4158 EVT SrcVT = Op.getValueType();
4159 EVT DstVT = N->getValueType(0);
4160 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4161 "ExpandBITCAST called for non-i64 type");
4163 // Turn i64->f64 into VMOVDRR.
4164 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4165 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4166 DAG.getConstant(0, dl, MVT::i32));
4167 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4168 DAG.getConstant(1, dl, MVT::i32));
4169 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4170 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4173 // Turn f64->i64 into VMOVRRD.
4174 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4176 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4177 SrcVT.getVectorNumElements() > 1)
4178 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4179 DAG.getVTList(MVT::i32, MVT::i32),
4180 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4182 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4183 DAG.getVTList(MVT::i32, MVT::i32), Op);
4184 // Merge the pieces into a single i64 value.
4185 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4191 /// getZeroVector - Returns a vector of specified type with all zero elements.
4192 /// Zero vectors are used to represent vector negation and in those cases
4193 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4194 /// not support i64 elements, so sometimes the zero vectors will need to be
4195 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4197 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4198 assert(VT.isVector() && "Expected a vector type");
4199 // The canonical modified immediate encoding of a zero vector is....0!
4200 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4201 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4202 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4203 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4206 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4207 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4208 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4209 SelectionDAG &DAG) const {
4210 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4211 EVT VT = Op.getValueType();
4212 unsigned VTBits = VT.getSizeInBits();
4214 SDValue ShOpLo = Op.getOperand(0);
4215 SDValue ShOpHi = Op.getOperand(1);
4216 SDValue ShAmt = Op.getOperand(2);
4218 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4220 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4222 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4223 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4224 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4225 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4226 DAG.getConstant(VTBits, dl, MVT::i32));
4227 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4228 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4229 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4231 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4232 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4233 ISD::SETGE, ARMcc, DAG, dl);
4234 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4235 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4238 SDValue Ops[2] = { Lo, Hi };
4239 return DAG.getMergeValues(Ops, dl);
4242 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4243 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4244 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4245 SelectionDAG &DAG) const {
4246 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4247 EVT VT = Op.getValueType();
4248 unsigned VTBits = VT.getSizeInBits();
4250 SDValue ShOpLo = Op.getOperand(0);
4251 SDValue ShOpHi = Op.getOperand(1);
4252 SDValue ShAmt = Op.getOperand(2);
4255 assert(Op.getOpcode() == ISD::SHL_PARTS);
4256 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4257 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4258 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4259 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4260 DAG.getConstant(VTBits, dl, MVT::i32));
4261 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4262 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4264 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4265 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4266 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4267 ISD::SETGE, ARMcc, DAG, dl);
4268 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4269 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4272 SDValue Ops[2] = { Lo, Hi };
4273 return DAG.getMergeValues(Ops, dl);
4276 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4277 SelectionDAG &DAG) const {
4278 // The rounding mode is in bits 23:22 of the FPSCR.
4279 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4280 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4281 // so that the shift + and get folded into a bitfield extract.
4283 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4284 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4286 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4287 DAG.getConstant(1U << 22, dl, MVT::i32));
4288 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4289 DAG.getConstant(22, dl, MVT::i32));
4290 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4291 DAG.getConstant(3, dl, MVT::i32));
4294 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4295 const ARMSubtarget *ST) {
4297 EVT VT = N->getValueType(0);
4298 if (VT.isVector()) {
4299 assert(ST->hasNEON());
4301 // Compute the least significant set bit: LSB = X & -X
4302 SDValue X = N->getOperand(0);
4303 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4304 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4306 EVT ElemTy = VT.getVectorElementType();
4308 if (ElemTy == MVT::i8) {
4309 // Compute with: cttz(x) = ctpop(lsb - 1)
4310 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4311 DAG.getTargetConstant(1, dl, ElemTy));
4312 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4313 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4316 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4317 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4318 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4319 unsigned NumBits = ElemTy.getSizeInBits();
4320 SDValue WidthMinus1 =
4321 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4322 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4323 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4324 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4327 // Compute with: cttz(x) = ctpop(lsb - 1)
4329 // Since we can only compute the number of bits in a byte with vcnt.8, we
4330 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4335 if (ElemTy == MVT::i64) {
4336 // Load constant 0xffff'ffff'ffff'ffff to register.
4337 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4338 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4339 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4341 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4342 DAG.getTargetConstant(1, dl, ElemTy));
4343 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4346 // Count #bits with vcnt.8.
4347 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4348 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4349 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4351 // Gather the #bits with vpaddl (pairwise add.)
4352 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4353 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4354 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4356 if (ElemTy == MVT::i16)
4359 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4360 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4361 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4363 if (ElemTy == MVT::i32)
4366 assert(ElemTy == MVT::i64);
4367 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4368 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4373 if (!ST->hasV6T2Ops())
4376 SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4377 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4380 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4381 /// for each 16-bit element from operand, repeated. The basic idea is to
4382 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4384 /// Trace for v4i16:
4385 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4386 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4387 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4388 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4389 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4390 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4391 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4392 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4393 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4394 EVT VT = N->getValueType(0);
4397 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4398 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4399 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4400 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4401 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4402 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4405 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4406 /// bit-count for each 16-bit element from the operand. We need slightly
4407 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4408 /// 64/128-bit registers.
4410 /// Trace for v4i16:
4411 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4412 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4413 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4414 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4415 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4416 EVT VT = N->getValueType(0);
4419 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4420 if (VT.is64BitVector()) {
4421 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4422 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4423 DAG.getIntPtrConstant(0, DL));
4425 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4426 BitCounts, DAG.getIntPtrConstant(0, DL));
4427 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4431 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4432 /// bit-count for each 32-bit element from the operand. The idea here is
4433 /// to split the vector into 16-bit elements, leverage the 16-bit count
4434 /// routine, and then combine the results.
4436 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4437 /// input = [v0 v1 ] (vi: 32-bit elements)
4438 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4439 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4440 /// vrev: N0 = [k1 k0 k3 k2 ]
4442 /// N1 =+[k1 k0 k3 k2 ]
4444 /// N2 =+[k1 k3 k0 k2 ]
4446 /// Extended =+[k1 k3 k0 k2 ]
4448 /// Extracted=+[k1 k3 ]
4450 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4451 EVT VT = N->getValueType(0);
4454 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4456 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4457 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4458 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4459 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4460 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4462 if (VT.is64BitVector()) {
4463 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4464 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4465 DAG.getIntPtrConstant(0, DL));
4467 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4468 DAG.getIntPtrConstant(0, DL));
4469 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4473 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4474 const ARMSubtarget *ST) {
4475 EVT VT = N->getValueType(0);
4477 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4478 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4479 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4480 "Unexpected type for custom ctpop lowering");
4482 if (VT.getVectorElementType() == MVT::i32)
4483 return lowerCTPOP32BitElements(N, DAG);
4485 return lowerCTPOP16BitElements(N, DAG);
4488 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4489 const ARMSubtarget *ST) {
4490 EVT VT = N->getValueType(0);
4496 // Lower vector shifts on NEON to use VSHL.
4497 assert(ST->hasNEON() && "unexpected vector shift");
4499 // Left shifts translate directly to the vshiftu intrinsic.
4500 if (N->getOpcode() == ISD::SHL)
4501 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4502 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4504 N->getOperand(0), N->getOperand(1));
4506 assert((N->getOpcode() == ISD::SRA ||
4507 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4509 // NEON uses the same intrinsics for both left and right shifts. For
4510 // right shifts, the shift amounts are negative, so negate the vector of
4512 EVT ShiftVT = N->getOperand(1).getValueType();
4513 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4514 getZeroVector(ShiftVT, DAG, dl),
4516 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4517 Intrinsic::arm_neon_vshifts :
4518 Intrinsic::arm_neon_vshiftu);
4519 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4520 DAG.getConstant(vshiftInt, dl, MVT::i32),
4521 N->getOperand(0), NegatedCount);
4524 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4525 const ARMSubtarget *ST) {
4526 EVT VT = N->getValueType(0);
4529 // We can get here for a node like i32 = ISD::SHL i32, i64
4533 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4534 "Unknown shift to lower!");
4536 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4537 if (!isOneConstant(N->getOperand(1)))
4540 // If we are in thumb mode, we don't have RRX.
4541 if (ST->isThumb1Only()) return SDValue();
4543 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4544 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4545 DAG.getConstant(0, dl, MVT::i32));
4546 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4547 DAG.getConstant(1, dl, MVT::i32));
4549 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4550 // captures the result into a carry flag.
4551 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4552 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4554 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4555 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4557 // Merge the pieces into a single i64 value.
4558 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4561 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4562 SDValue TmpOp0, TmpOp1;
4563 bool Invert = false;
4567 SDValue Op0 = Op.getOperand(0);
4568 SDValue Op1 = Op.getOperand(1);
4569 SDValue CC = Op.getOperand(2);
4570 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4571 EVT VT = Op.getValueType();
4572 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4575 if (CmpVT.getVectorElementType() == MVT::i64)
4576 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4577 // but it's possible that our operands are 64-bit but our result is 32-bit.
4578 // Bail in this case.
4581 if (Op1.getValueType().isFloatingPoint()) {
4582 switch (SetCCOpcode) {
4583 default: llvm_unreachable("Illegal FP comparison");
4585 case ISD::SETNE: Invert = true; // Fallthrough
4587 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4589 case ISD::SETLT: Swap = true; // Fallthrough
4591 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4593 case ISD::SETLE: Swap = true; // Fallthrough
4595 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4596 case ISD::SETUGE: Swap = true; // Fallthrough
4597 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4598 case ISD::SETUGT: Swap = true; // Fallthrough
4599 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4600 case ISD::SETUEQ: Invert = true; // Fallthrough
4602 // Expand this to (OLT | OGT).
4606 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4607 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4609 case ISD::SETUO: Invert = true; // Fallthrough
4611 // Expand this to (OLT | OGE).
4615 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4616 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4620 // Integer comparisons.
4621 switch (SetCCOpcode) {
4622 default: llvm_unreachable("Illegal integer comparison");
4623 case ISD::SETNE: Invert = true;
4624 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4625 case ISD::SETLT: Swap = true;
4626 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4627 case ISD::SETLE: Swap = true;
4628 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4629 case ISD::SETULT: Swap = true;
4630 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4631 case ISD::SETULE: Swap = true;
4632 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4635 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4636 if (Opc == ARMISD::VCEQ) {
4639 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4641 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4644 // Ignore bitconvert.
4645 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4646 AndOp = AndOp.getOperand(0);
4648 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4650 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4651 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4658 std::swap(Op0, Op1);
4660 // If one of the operands is a constant vector zero, attempt to fold the
4661 // comparison to a specialized compare-against-zero form.
4663 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4665 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4666 if (Opc == ARMISD::VCGE)
4667 Opc = ARMISD::VCLEZ;
4668 else if (Opc == ARMISD::VCGT)
4669 Opc = ARMISD::VCLTZ;
4674 if (SingleOp.getNode()) {
4677 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4679 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4681 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4683 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4685 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4687 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4690 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4693 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4696 Result = DAG.getNOT(dl, Result, VT);
4701 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4702 /// valid vector constant for a NEON instruction with a "modified immediate"
4703 /// operand (e.g., VMOV). If so, return the encoded value.
4704 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4705 unsigned SplatBitSize, SelectionDAG &DAG,
4706 SDLoc dl, EVT &VT, bool is128Bits,
4707 NEONModImmType type) {
4708 unsigned OpCmode, Imm;
4710 // SplatBitSize is set to the smallest size that splats the vector, so a
4711 // zero vector will always have SplatBitSize == 8. However, NEON modified
4712 // immediate instructions others than VMOV do not support the 8-bit encoding
4713 // of a zero vector, and the default encoding of zero is supposed to be the
4718 switch (SplatBitSize) {
4720 if (type != VMOVModImm)
4722 // Any 1-byte value is OK. Op=0, Cmode=1110.
4723 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4726 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4730 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4731 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4732 if ((SplatBits & ~0xff) == 0) {
4733 // Value = 0x00nn: Op=x, Cmode=100x.
4738 if ((SplatBits & ~0xff00) == 0) {
4739 // Value = 0xnn00: Op=x, Cmode=101x.
4741 Imm = SplatBits >> 8;
4747 // NEON's 32-bit VMOV supports splat values where:
4748 // * only one byte is nonzero, or
4749 // * the least significant byte is 0xff and the second byte is nonzero, or
4750 // * the least significant 2 bytes are 0xff and the third is nonzero.
4751 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4752 if ((SplatBits & ~0xff) == 0) {
4753 // Value = 0x000000nn: Op=x, Cmode=000x.
4758 if ((SplatBits & ~0xff00) == 0) {
4759 // Value = 0x0000nn00: Op=x, Cmode=001x.
4761 Imm = SplatBits >> 8;
4764 if ((SplatBits & ~0xff0000) == 0) {
4765 // Value = 0x00nn0000: Op=x, Cmode=010x.
4767 Imm = SplatBits >> 16;
4770 if ((SplatBits & ~0xff000000) == 0) {
4771 // Value = 0xnn000000: Op=x, Cmode=011x.
4773 Imm = SplatBits >> 24;
4777 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4778 if (type == OtherModImm) return SDValue();
4780 if ((SplatBits & ~0xffff) == 0 &&
4781 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4782 // Value = 0x0000nnff: Op=x, Cmode=1100.
4784 Imm = SplatBits >> 8;
4788 if ((SplatBits & ~0xffffff) == 0 &&
4789 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4790 // Value = 0x00nnffff: Op=x, Cmode=1101.
4792 Imm = SplatBits >> 16;
4796 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4797 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4798 // VMOV.I32. A (very) minor optimization would be to replicate the value
4799 // and fall through here to test for a valid 64-bit splat. But, then the
4800 // caller would also need to check and handle the change in size.
4804 if (type != VMOVModImm)
4806 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4807 uint64_t BitMask = 0xff;
4809 unsigned ImmMask = 1;
4811 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4812 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4815 } else if ((SplatBits & BitMask) != 0) {
4822 if (DAG.getDataLayout().isBigEndian())
4823 // swap higher and lower 32 bit word
4824 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4826 // Op=1, Cmode=1110.
4828 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4833 llvm_unreachable("unexpected size for isNEONModifiedImm");
4836 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4837 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4840 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4841 const ARMSubtarget *ST) const {
4845 bool IsDouble = Op.getValueType() == MVT::f64;
4846 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4848 // Use the default (constant pool) lowering for double constants when we have
4850 if (IsDouble && Subtarget->isFPOnlySP())
4853 // Try splatting with a VMOV.f32...
4854 APFloat FPVal = CFP->getValueAPF();
4855 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4858 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4859 // We have code in place to select a valid ConstantFP already, no need to
4864 // It's a float and we are trying to use NEON operations where
4865 // possible. Lower it to a splat followed by an extract.
4867 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4868 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4870 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4871 DAG.getConstant(0, DL, MVT::i32));
4874 // The rest of our options are NEON only, make sure that's allowed before
4876 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4880 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4882 // It wouldn't really be worth bothering for doubles except for one very
4883 // important value, which does happen to match: 0.0. So make sure we don't do
4885 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4888 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4889 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4890 VMovVT, false, VMOVModImm);
4891 if (NewVal != SDValue()) {
4893 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4896 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4898 // It's a float: cast and extract a vector element.
4899 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4901 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4902 DAG.getConstant(0, DL, MVT::i32));
4905 // Finally, try a VMVN.i32
4906 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4908 if (NewVal != SDValue()) {
4910 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4913 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4915 // It's a float: cast and extract a vector element.
4916 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4918 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4919 DAG.getConstant(0, DL, MVT::i32));
4925 // check if an VEXT instruction can handle the shuffle mask when the
4926 // vector sources of the shuffle are the same.
4927 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4928 unsigned NumElts = VT.getVectorNumElements();
4930 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4936 // If this is a VEXT shuffle, the immediate value is the index of the first
4937 // element. The other shuffle indices must be the successive elements after
4939 unsigned ExpectedElt = Imm;
4940 for (unsigned i = 1; i < NumElts; ++i) {
4941 // Increment the expected index. If it wraps around, just follow it
4942 // back to index zero and keep going.
4944 if (ExpectedElt == NumElts)
4947 if (M[i] < 0) continue; // ignore UNDEF indices
4948 if (ExpectedElt != static_cast<unsigned>(M[i]))
4956 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4957 bool &ReverseVEXT, unsigned &Imm) {
4958 unsigned NumElts = VT.getVectorNumElements();
4959 ReverseVEXT = false;
4961 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4967 // If this is a VEXT shuffle, the immediate value is the index of the first
4968 // element. The other shuffle indices must be the successive elements after
4970 unsigned ExpectedElt = Imm;
4971 for (unsigned i = 1; i < NumElts; ++i) {
4972 // Increment the expected index. If it wraps around, it may still be
4973 // a VEXT but the source vectors must be swapped.
4975 if (ExpectedElt == NumElts * 2) {
4980 if (M[i] < 0) continue; // ignore UNDEF indices
4981 if (ExpectedElt != static_cast<unsigned>(M[i]))
4985 // Adjust the index value if the source operands will be swapped.
4992 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4993 /// instruction with the specified blocksize. (The order of the elements
4994 /// within each block of the vector is reversed.)
4995 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4996 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4997 "Only possible block sizes for VREV are: 16, 32, 64");
4999 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5003 unsigned NumElts = VT.getVectorNumElements();
5004 unsigned BlockElts = M[0] + 1;
5005 // If the first shuffle index is UNDEF, be optimistic.
5007 BlockElts = BlockSize / EltSz;
5009 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5012 for (unsigned i = 0; i < NumElts; ++i) {
5013 if (M[i] < 0) continue; // ignore UNDEF indices
5014 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5021 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5022 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5023 // range, then 0 is placed into the resulting vector. So pretty much any mask
5024 // of 8 elements can work here.
5025 return VT == MVT::v8i8 && M.size() == 8;
5028 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5029 // checking that pairs of elements in the shuffle mask represent the same index
5030 // in each vector, incrementing the expected index by 2 at each step.
5031 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5032 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5034 // WhichResult gives the offset for each element in the mask based on which
5035 // of the two results it belongs to.
5037 // The transpose can be represented either as:
5038 // result1 = shufflevector v1, v2, result1_shuffle_mask
5039 // result2 = shufflevector v1, v2, result2_shuffle_mask
5040 // where v1/v2 and the shuffle masks have the same number of elements
5041 // (here WhichResult (see below) indicates which result is being checked)
5044 // results = shufflevector v1, v2, shuffle_mask
5045 // where both results are returned in one vector and the shuffle mask has twice
5046 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5047 // want to check the low half and high half of the shuffle mask as if it were
5049 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5050 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5054 unsigned NumElts = VT.getVectorNumElements();
5055 if (M.size() != NumElts && M.size() != NumElts*2)
5058 // If the mask is twice as long as the input vector then we need to check the
5059 // upper and lower parts of the mask with a matching value for WhichResult
5060 // FIXME: A mask with only even values will be rejected in case the first
5061 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5062 // M[0] is used to determine WhichResult
5063 for (unsigned i = 0; i < M.size(); i += NumElts) {
5064 if (M.size() == NumElts * 2)
5065 WhichResult = i / NumElts;
5067 WhichResult = M[i] == 0 ? 0 : 1;
5068 for (unsigned j = 0; j < NumElts; j += 2) {
5069 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5070 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5075 if (M.size() == NumElts*2)
5081 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5082 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5083 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5084 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5085 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5089 unsigned NumElts = VT.getVectorNumElements();
5090 if (M.size() != NumElts && M.size() != NumElts*2)
5093 for (unsigned i = 0; i < M.size(); i += NumElts) {
5094 if (M.size() == NumElts * 2)
5095 WhichResult = i / NumElts;
5097 WhichResult = M[i] == 0 ? 0 : 1;
5098 for (unsigned j = 0; j < NumElts; j += 2) {
5099 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5100 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5105 if (M.size() == NumElts*2)
5111 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5112 // that the mask elements are either all even and in steps of size 2 or all odd
5113 // and in steps of size 2.
5114 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5115 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5117 // Requires similar checks to that of isVTRNMask with
5118 // respect the how results are returned.
5119 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5120 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5124 unsigned NumElts = VT.getVectorNumElements();
5125 if (M.size() != NumElts && M.size() != NumElts*2)
5128 for (unsigned i = 0; i < M.size(); i += NumElts) {
5129 WhichResult = M[i] == 0 ? 0 : 1;
5130 for (unsigned j = 0; j < NumElts; ++j) {
5131 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5136 if (M.size() == NumElts*2)
5139 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5140 if (VT.is64BitVector() && EltSz == 32)
5146 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5147 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5148 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5149 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5150 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5154 unsigned NumElts = VT.getVectorNumElements();
5155 if (M.size() != NumElts && M.size() != NumElts*2)
5158 unsigned Half = NumElts / 2;
5159 for (unsigned i = 0; i < M.size(); i += NumElts) {
5160 WhichResult = M[i] == 0 ? 0 : 1;
5161 for (unsigned j = 0; j < NumElts; j += Half) {
5162 unsigned Idx = WhichResult;
5163 for (unsigned k = 0; k < Half; ++k) {
5164 int MIdx = M[i + j + k];
5165 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5172 if (M.size() == NumElts*2)
5175 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5176 if (VT.is64BitVector() && EltSz == 32)
5182 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5183 // that pairs of elements of the shufflemask represent the same index in each
5184 // vector incrementing sequentially through the vectors.
5185 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5186 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5188 // Requires similar checks to that of isVTRNMask with respect the how results
5190 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5191 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5195 unsigned NumElts = VT.getVectorNumElements();
5196 if (M.size() != NumElts && M.size() != NumElts*2)
5199 for (unsigned i = 0; i < M.size(); i += NumElts) {
5200 WhichResult = M[i] == 0 ? 0 : 1;
5201 unsigned Idx = WhichResult * NumElts / 2;
5202 for (unsigned j = 0; j < NumElts; j += 2) {
5203 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5204 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5210 if (M.size() == NumElts*2)
5213 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5214 if (VT.is64BitVector() && EltSz == 32)
5220 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5221 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5222 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5223 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5224 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5228 unsigned NumElts = VT.getVectorNumElements();
5229 if (M.size() != NumElts && M.size() != NumElts*2)
5232 for (unsigned i = 0; i < M.size(); i += NumElts) {
5233 WhichResult = M[i] == 0 ? 0 : 1;
5234 unsigned Idx = WhichResult * NumElts / 2;
5235 for (unsigned j = 0; j < NumElts; j += 2) {
5236 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5237 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5243 if (M.size() == NumElts*2)
5246 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5247 if (VT.is64BitVector() && EltSz == 32)
5253 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5254 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5255 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5256 unsigned &WhichResult,
5259 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5260 return ARMISD::VTRN;
5261 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5262 return ARMISD::VUZP;
5263 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5264 return ARMISD::VZIP;
5267 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5268 return ARMISD::VTRN;
5269 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5270 return ARMISD::VUZP;
5271 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5272 return ARMISD::VZIP;
5277 /// \return true if this is a reverse operation on an vector.
5278 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5279 unsigned NumElts = VT.getVectorNumElements();
5280 // Make sure the mask has the right size.
5281 if (NumElts != M.size())
5284 // Look for <15, ..., 3, -1, 1, 0>.
5285 for (unsigned i = 0; i != NumElts; ++i)
5286 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5292 // If N is an integer constant that can be moved into a register in one
5293 // instruction, return an SDValue of such a constant (will become a MOV
5294 // instruction). Otherwise return null.
5295 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5296 const ARMSubtarget *ST, SDLoc dl) {
5298 if (!isa<ConstantSDNode>(N))
5300 Val = cast<ConstantSDNode>(N)->getZExtValue();
5302 if (ST->isThumb1Only()) {
5303 if (Val <= 255 || ~Val <= 255)
5304 return DAG.getConstant(Val, dl, MVT::i32);
5306 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5307 return DAG.getConstant(Val, dl, MVT::i32);
5312 // If this is a case we can't handle, return null and let the default
5313 // expansion code take care of it.
5314 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5315 const ARMSubtarget *ST) const {
5316 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5318 EVT VT = Op.getValueType();
5320 APInt SplatBits, SplatUndef;
5321 unsigned SplatBitSize;
5323 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5324 if (SplatBitSize <= 64) {
5325 // Check if an immediate VMOV works.
5327 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5328 SplatUndef.getZExtValue(), SplatBitSize,
5329 DAG, dl, VmovVT, VT.is128BitVector(),
5331 if (Val.getNode()) {
5332 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5333 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5336 // Try an immediate VMVN.
5337 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5338 Val = isNEONModifiedImm(NegatedImm,
5339 SplatUndef.getZExtValue(), SplatBitSize,
5340 DAG, dl, VmovVT, VT.is128BitVector(),
5342 if (Val.getNode()) {
5343 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5344 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5347 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5348 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5349 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5351 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5352 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5358 // Scan through the operands to see if only one value is used.
5360 // As an optimisation, even if more than one value is used it may be more
5361 // profitable to splat with one value then change some lanes.
5363 // Heuristically we decide to do this if the vector has a "dominant" value,
5364 // defined as splatted to more than half of the lanes.
5365 unsigned NumElts = VT.getVectorNumElements();
5366 bool isOnlyLowElement = true;
5367 bool usesOnlyOneValue = true;
5368 bool hasDominantValue = false;
5369 bool isConstant = true;
5371 // Map of the number of times a particular SDValue appears in the
5373 DenseMap<SDValue, unsigned> ValueCounts;
5375 for (unsigned i = 0; i < NumElts; ++i) {
5376 SDValue V = Op.getOperand(i);
5377 if (V.getOpcode() == ISD::UNDEF)
5380 isOnlyLowElement = false;
5381 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5384 ValueCounts.insert(std::make_pair(V, 0));
5385 unsigned &Count = ValueCounts[V];
5387 // Is this value dominant? (takes up more than half of the lanes)
5388 if (++Count > (NumElts / 2)) {
5389 hasDominantValue = true;
5393 if (ValueCounts.size() != 1)
5394 usesOnlyOneValue = false;
5395 if (!Value.getNode() && ValueCounts.size() > 0)
5396 Value = ValueCounts.begin()->first;
5398 if (ValueCounts.size() == 0)
5399 return DAG.getUNDEF(VT);
5401 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5402 // Keep going if we are hitting this case.
5403 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5404 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5406 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5408 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5409 // i32 and try again.
5410 if (hasDominantValue && EltSize <= 32) {
5414 // If we are VDUPing a value that comes directly from a vector, that will
5415 // cause an unnecessary move to and from a GPR, where instead we could
5416 // just use VDUPLANE. We can only do this if the lane being extracted
5417 // is at a constant index, as the VDUP from lane instructions only have
5418 // constant-index forms.
5419 ConstantSDNode *constIndex;
5420 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5421 (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
5422 // We need to create a new undef vector to use for the VDUPLANE if the
5423 // size of the vector from which we get the value is different than the
5424 // size of the vector that we need to create. We will insert the element
5425 // such that the register coalescer will remove unnecessary copies.
5426 if (VT != Value->getOperand(0).getValueType()) {
5427 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5428 VT.getVectorNumElements();
5429 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5430 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5431 Value, DAG.getConstant(index, dl, MVT::i32)),
5432 DAG.getConstant(index, dl, MVT::i32));
5434 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5435 Value->getOperand(0), Value->getOperand(1));
5437 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5439 if (!usesOnlyOneValue) {
5440 // The dominant value was splatted as 'N', but we now have to insert
5441 // all differing elements.
5442 for (unsigned I = 0; I < NumElts; ++I) {
5443 if (Op.getOperand(I) == Value)
5445 SmallVector<SDValue, 3> Ops;
5447 Ops.push_back(Op.getOperand(I));
5448 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5449 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5454 if (VT.getVectorElementType().isFloatingPoint()) {
5455 SmallVector<SDValue, 8> Ops;
5456 for (unsigned i = 0; i < NumElts; ++i)
5457 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5459 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5460 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5461 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5463 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5465 if (usesOnlyOneValue) {
5466 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5467 if (isConstant && Val.getNode())
5468 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5472 // If all elements are constants and the case above didn't get hit, fall back
5473 // to the default expansion, which will generate a load from the constant
5478 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5480 SDValue shuffle = ReconstructShuffle(Op, DAG);
5481 if (shuffle != SDValue())
5485 // Vectors with 32- or 64-bit elements can be built by directly assigning
5486 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5487 // will be legalized.
5488 if (EltSize >= 32) {
5489 // Do the expansion with floating-point types, since that is what the VFP
5490 // registers are defined to use, and since i64 is not legal.
5491 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5492 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5493 SmallVector<SDValue, 8> Ops;
5494 for (unsigned i = 0; i < NumElts; ++i)
5495 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5496 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5497 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5500 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5501 // know the default expansion would otherwise fall back on something even
5502 // worse. For a vector with one or two non-undef values, that's
5503 // scalar_to_vector for the elements followed by a shuffle (provided the
5504 // shuffle is valid for the target) and materialization element by element
5505 // on the stack followed by a load for everything else.
5506 if (!isConstant && !usesOnlyOneValue) {
5507 SDValue Vec = DAG.getUNDEF(VT);
5508 for (unsigned i = 0 ; i < NumElts; ++i) {
5509 SDValue V = Op.getOperand(i);
5510 if (V.getOpcode() == ISD::UNDEF)
5512 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5513 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5521 // Gather data to see if the operation can be modelled as a
5522 // shuffle in combination with VEXTs.
5523 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5524 SelectionDAG &DAG) const {
5525 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5527 EVT VT = Op.getValueType();
5528 unsigned NumElts = VT.getVectorNumElements();
5530 struct ShuffleSourceInfo {
5535 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5536 // be compatible with the shuffle we intend to construct. As a result
5537 // ShuffleVec will be some sliding window into the original Vec.
5540 // Code should guarantee that element i in Vec starts at element "WindowBase
5541 // + i * WindowScale in ShuffleVec".
5545 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5546 ShuffleSourceInfo(SDValue Vec)
5547 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5551 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5553 SmallVector<ShuffleSourceInfo, 2> Sources;
5554 for (unsigned i = 0; i < NumElts; ++i) {
5555 SDValue V = Op.getOperand(i);
5556 if (V.getOpcode() == ISD::UNDEF)
5558 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5559 // A shuffle can only come from building a vector from various
5560 // elements of other vectors.
5562 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5563 // Furthermore, shuffles require a constant mask, whereas extractelts
5564 // accept variable indices.
5568 // Add this element source to the list if it's not already there.
5569 SDValue SourceVec = V.getOperand(0);
5570 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5571 if (Source == Sources.end())
5572 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5574 // Update the minimum and maximum lane number seen.
5575 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5576 Source->MinElt = std::min(Source->MinElt, EltNo);
5577 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5580 // Currently only do something sane when at most two source vectors
5582 if (Sources.size() > 2)
5585 // Find out the smallest element size among result and two sources, and use
5586 // it as element size to build the shuffle_vector.
5587 EVT SmallestEltTy = VT.getVectorElementType();
5588 for (auto &Source : Sources) {
5589 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5590 if (SrcEltTy.bitsLT(SmallestEltTy))
5591 SmallestEltTy = SrcEltTy;
5593 unsigned ResMultiplier =
5594 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5595 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5596 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5598 // If the source vector is too wide or too narrow, we may nevertheless be able
5599 // to construct a compatible shuffle either by concatenating it with UNDEF or
5600 // extracting a suitable range of elements.
5601 for (auto &Src : Sources) {
5602 EVT SrcVT = Src.ShuffleVec.getValueType();
5604 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5607 // This stage of the search produces a source with the same element type as
5608 // the original, but with a total width matching the BUILD_VECTOR output.
5609 EVT EltVT = SrcVT.getVectorElementType();
5610 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5611 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5613 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5614 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5616 // We can pad out the smaller vector for free, so if it's part of a
5619 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5620 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5624 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5627 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5628 // Span too large for a VEXT to cope
5632 if (Src.MinElt >= NumSrcElts) {
5633 // The extraction can just take the second half
5635 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5636 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5637 Src.WindowBase = -NumSrcElts;
5638 } else if (Src.MaxElt < NumSrcElts) {
5639 // The extraction can just take the first half
5641 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5642 DAG.getConstant(0, dl, MVT::i32));
5644 // An actual VEXT is needed
5646 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5647 DAG.getConstant(0, dl, MVT::i32));
5649 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5650 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5652 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5654 DAG.getConstant(Src.MinElt, dl, MVT::i32));
5655 Src.WindowBase = -Src.MinElt;
5659 // Another possible incompatibility occurs from the vector element types. We
5660 // can fix this by bitcasting the source vectors to the same type we intend
5662 for (auto &Src : Sources) {
5663 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5664 if (SrcEltTy == SmallestEltTy)
5666 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5667 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5668 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5669 Src.WindowBase *= Src.WindowScale;
5672 // Final sanity check before we try to actually produce a shuffle.
5674 for (auto Src : Sources)
5675 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5678 // The stars all align, our next step is to produce the mask for the shuffle.
5679 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5680 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5681 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5682 SDValue Entry = Op.getOperand(i);
5683 if (Entry.getOpcode() == ISD::UNDEF)
5686 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5687 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5689 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5690 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5692 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5693 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5694 VT.getVectorElementType().getSizeInBits());
5695 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5697 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5698 // starting at the appropriate offset.
5699 int *LaneMask = &Mask[i * ResMultiplier];
5701 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5702 ExtractBase += NumElts * (Src - Sources.begin());
5703 for (int j = 0; j < LanesDefined; ++j)
5704 LaneMask[j] = ExtractBase + j;
5707 // Final check before we try to produce nonsense...
5708 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5711 // We can't handle more than two sources. This should have already
5712 // been checked before this point.
5713 assert(Sources.size() <= 2 && "Too many sources!");
5715 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5716 for (unsigned i = 0; i < Sources.size(); ++i)
5717 ShuffleOps[i] = Sources[i].ShuffleVec;
5719 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5720 ShuffleOps[1], &Mask[0]);
5721 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5724 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5725 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5726 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5727 /// are assumed to be legal.
5729 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5731 if (VT.getVectorNumElements() == 4 &&
5732 (VT.is128BitVector() || VT.is64BitVector())) {
5733 unsigned PFIndexes[4];
5734 for (unsigned i = 0; i != 4; ++i) {
5738 PFIndexes[i] = M[i];
5741 // Compute the index in the perfect shuffle table.
5742 unsigned PFTableIndex =
5743 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5744 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5745 unsigned Cost = (PFEntry >> 30);
5751 bool ReverseVEXT, isV_UNDEF;
5752 unsigned Imm, WhichResult;
5754 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5755 return (EltSize >= 32 ||
5756 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5757 isVREVMask(M, VT, 64) ||
5758 isVREVMask(M, VT, 32) ||
5759 isVREVMask(M, VT, 16) ||
5760 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5761 isVTBLMask(M, VT) ||
5762 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5763 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5766 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5767 /// the specified operations to build the shuffle.
5768 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5769 SDValue RHS, SelectionDAG &DAG,
5771 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5772 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5773 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5776 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5785 OP_VUZPL, // VUZP, left result
5786 OP_VUZPR, // VUZP, right result
5787 OP_VZIPL, // VZIP, left result
5788 OP_VZIPR, // VZIP, right result
5789 OP_VTRNL, // VTRN, left result
5790 OP_VTRNR // VTRN, right result
5793 if (OpNum == OP_COPY) {
5794 if (LHSID == (1*9+2)*9+3) return LHS;
5795 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5799 SDValue OpLHS, OpRHS;
5800 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5801 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5802 EVT VT = OpLHS.getValueType();
5805 default: llvm_unreachable("Unknown shuffle opcode!");
5807 // VREV divides the vector in half and swaps within the half.
5808 if (VT.getVectorElementType() == MVT::i32 ||
5809 VT.getVectorElementType() == MVT::f32)
5810 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5811 // vrev <4 x i16> -> VREV32
5812 if (VT.getVectorElementType() == MVT::i16)
5813 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5814 // vrev <4 x i8> -> VREV16
5815 assert(VT.getVectorElementType() == MVT::i8);
5816 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5821 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5822 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5826 return DAG.getNode(ARMISD::VEXT, dl, VT,
5828 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5831 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5832 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5835 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5836 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5839 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5840 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5844 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5845 ArrayRef<int> ShuffleMask,
5846 SelectionDAG &DAG) {
5847 // Check to see if we can use the VTBL instruction.
5848 SDValue V1 = Op.getOperand(0);
5849 SDValue V2 = Op.getOperand(1);
5852 SmallVector<SDValue, 8> VTBLMask;
5853 for (ArrayRef<int>::iterator
5854 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5855 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5857 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5858 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5859 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5861 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5862 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5865 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5866 SelectionDAG &DAG) {
5868 SDValue OpLHS = Op.getOperand(0);
5869 EVT VT = OpLHS.getValueType();
5871 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5872 "Expect an v8i16/v16i8 type");
5873 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5874 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5875 // extract the first 8 bytes into the top double word and the last 8 bytes
5876 // into the bottom double word. The v8i16 case is similar.
5877 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5878 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5879 DAG.getConstant(ExtractNum, DL, MVT::i32));
5882 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5883 SDValue V1 = Op.getOperand(0);
5884 SDValue V2 = Op.getOperand(1);
5886 EVT VT = Op.getValueType();
5887 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5889 // Convert shuffles that are directly supported on NEON to target-specific
5890 // DAG nodes, instead of keeping them as shuffles and matching them again
5891 // during code selection. This is more efficient and avoids the possibility
5892 // of inconsistencies between legalization and selection.
5893 // FIXME: floating-point vectors should be canonicalized to integer vectors
5894 // of the same time so that they get CSEd properly.
5895 ArrayRef<int> ShuffleMask = SVN->getMask();
5897 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5898 if (EltSize <= 32) {
5899 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5900 int Lane = SVN->getSplatIndex();
5901 // If this is undef splat, generate it via "just" vdup, if possible.
5902 if (Lane == -1) Lane = 0;
5904 // Test if V1 is a SCALAR_TO_VECTOR.
5905 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5906 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5908 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5909 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5911 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5912 !isa<ConstantSDNode>(V1.getOperand(0))) {
5913 bool IsScalarToVector = true;
5914 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5915 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5916 IsScalarToVector = false;
5919 if (IsScalarToVector)
5920 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5922 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5923 DAG.getConstant(Lane, dl, MVT::i32));
5928 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5931 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5932 DAG.getConstant(Imm, dl, MVT::i32));
5935 if (isVREVMask(ShuffleMask, VT, 64))
5936 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5937 if (isVREVMask(ShuffleMask, VT, 32))
5938 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5939 if (isVREVMask(ShuffleMask, VT, 16))
5940 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5942 if (V2->getOpcode() == ISD::UNDEF &&
5943 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5944 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5945 DAG.getConstant(Imm, dl, MVT::i32));
5948 // Check for Neon shuffles that modify both input vectors in place.
5949 // If both results are used, i.e., if there are two shuffles with the same
5950 // source operands and with masks corresponding to both results of one of
5951 // these operations, DAG memoization will ensure that a single node is
5952 // used for both shuffles.
5953 unsigned WhichResult;
5955 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5956 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5959 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5960 .getValue(WhichResult);
5963 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5964 // shuffles that produce a result larger than their operands with:
5965 // shuffle(concat(v1, undef), concat(v2, undef))
5967 // shuffle(concat(v1, v2), undef)
5968 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5970 // This is useful in the general case, but there are special cases where
5971 // native shuffles produce larger results: the two-result ops.
5973 // Look through the concat when lowering them:
5974 // shuffle(concat(v1, v2), undef)
5976 // concat(VZIP(v1, v2):0, :1)
5978 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5979 V2->getOpcode() == ISD::UNDEF) {
5980 SDValue SubV1 = V1->getOperand(0);
5981 SDValue SubV2 = V1->getOperand(1);
5982 EVT SubVT = SubV1.getValueType();
5984 // We expect these to have been canonicalized to -1.
5985 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5986 return i < (int)VT.getVectorNumElements();
5987 }) && "Unexpected shuffle index into UNDEF operand!");
5989 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5990 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5993 assert((WhichResult == 0) &&
5994 "In-place shuffle of concat can only have one result!");
5995 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5997 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6003 // If the shuffle is not directly supported and it has 4 elements, use
6004 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6005 unsigned NumElts = VT.getVectorNumElements();
6007 unsigned PFIndexes[4];
6008 for (unsigned i = 0; i != 4; ++i) {
6009 if (ShuffleMask[i] < 0)
6012 PFIndexes[i] = ShuffleMask[i];
6015 // Compute the index in the perfect shuffle table.
6016 unsigned PFTableIndex =
6017 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6018 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6019 unsigned Cost = (PFEntry >> 30);
6022 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6025 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6026 if (EltSize >= 32) {
6027 // Do the expansion with floating-point types, since that is what the VFP
6028 // registers are defined to use, and since i64 is not legal.
6029 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6030 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6031 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6032 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6033 SmallVector<SDValue, 8> Ops;
6034 for (unsigned i = 0; i < NumElts; ++i) {
6035 if (ShuffleMask[i] < 0)
6036 Ops.push_back(DAG.getUNDEF(EltVT));
6038 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6039 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6040 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6043 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6044 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6047 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6048 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6050 if (VT == MVT::v8i8) {
6051 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6052 if (NewOp.getNode())
6059 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6060 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6061 SDValue Lane = Op.getOperand(2);
6062 if (!isa<ConstantSDNode>(Lane))
6068 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6069 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6070 SDValue Lane = Op.getOperand(1);
6071 if (!isa<ConstantSDNode>(Lane))
6074 SDValue Vec = Op.getOperand(0);
6075 if (Op.getValueType() == MVT::i32 &&
6076 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6078 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6084 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6085 // The only time a CONCAT_VECTORS operation can have legal types is when
6086 // two 64-bit vectors are concatenated to a 128-bit vector.
6087 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6088 "unexpected CONCAT_VECTORS");
6090 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6091 SDValue Op0 = Op.getOperand(0);
6092 SDValue Op1 = Op.getOperand(1);
6093 if (Op0.getOpcode() != ISD::UNDEF)
6094 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6095 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6096 DAG.getIntPtrConstant(0, dl));
6097 if (Op1.getOpcode() != ISD::UNDEF)
6098 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6099 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6100 DAG.getIntPtrConstant(1, dl));
6101 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6104 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6105 /// element has been zero/sign-extended, depending on the isSigned parameter,
6106 /// from an integer type half its size.
6107 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6109 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6110 EVT VT = N->getValueType(0);
6111 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6112 SDNode *BVN = N->getOperand(0).getNode();
6113 if (BVN->getValueType(0) != MVT::v4i32 ||
6114 BVN->getOpcode() != ISD::BUILD_VECTOR)
6116 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6117 unsigned HiElt = 1 - LoElt;
6118 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6119 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6120 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6121 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6122 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6125 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6126 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6129 if (Hi0->isNullValue() && Hi1->isNullValue())
6135 if (N->getOpcode() != ISD::BUILD_VECTOR)
6138 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6139 SDNode *Elt = N->getOperand(i).getNode();
6140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6141 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6142 unsigned HalfSize = EltSize / 2;
6144 if (!isIntN(HalfSize, C->getSExtValue()))
6147 if (!isUIntN(HalfSize, C->getZExtValue()))
6158 /// isSignExtended - Check if a node is a vector value that is sign-extended
6159 /// or a constant BUILD_VECTOR with sign-extended elements.
6160 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6161 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6163 if (isExtendedBUILD_VECTOR(N, DAG, true))
6168 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6169 /// or a constant BUILD_VECTOR with zero-extended elements.
6170 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6171 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6173 if (isExtendedBUILD_VECTOR(N, DAG, false))
6178 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6179 if (OrigVT.getSizeInBits() >= 64)
6182 assert(OrigVT.isSimple() && "Expecting a simple value type");
6184 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6185 switch (OrigSimpleTy) {
6186 default: llvm_unreachable("Unexpected Vector Type");
6195 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6196 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6197 /// We insert the required extension here to get the vector to fill a D register.
6198 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6201 unsigned ExtOpcode) {
6202 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6203 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6204 // 64-bits we need to insert a new extension so that it will be 64-bits.
6205 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6206 if (OrigTy.getSizeInBits() >= 64)
6209 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6210 EVT NewVT = getExtensionTo64Bits(OrigTy);
6212 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6215 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6216 /// does not do any sign/zero extension. If the original vector is less
6217 /// than 64 bits, an appropriate extension will be added after the load to
6218 /// reach a total size of 64 bits. We have to add the extension separately
6219 /// because ARM does not have a sign/zero extending load for vectors.
6220 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6221 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6223 // The load already has the right type.
6224 if (ExtendedTy == LD->getMemoryVT())
6225 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6226 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6227 LD->isNonTemporal(), LD->isInvariant(),
6228 LD->getAlignment());
6230 // We need to create a zextload/sextload. We cannot just create a load
6231 // followed by a zext/zext node because LowerMUL is also run during normal
6232 // operation legalization where we can't create illegal types.
6233 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6234 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6235 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6236 LD->isNonTemporal(), LD->getAlignment());
6239 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6240 /// extending load, or BUILD_VECTOR with extended elements, return the
6241 /// unextended value. The unextended vector should be 64 bits so that it can
6242 /// be used as an operand to a VMULL instruction. If the original vector size
6243 /// before extension is less than 64 bits we add a an extension to resize
6244 /// the vector to 64 bits.
6245 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6246 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6247 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6248 N->getOperand(0)->getValueType(0),
6252 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6253 return SkipLoadExtensionForVMULL(LD, DAG);
6255 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6256 // have been legalized as a BITCAST from v4i32.
6257 if (N->getOpcode() == ISD::BITCAST) {
6258 SDNode *BVN = N->getOperand(0).getNode();
6259 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6260 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6261 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6262 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6263 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6265 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6266 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6267 EVT VT = N->getValueType(0);
6268 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6269 unsigned NumElts = VT.getVectorNumElements();
6270 MVT TruncVT = MVT::getIntegerVT(EltSize);
6271 SmallVector<SDValue, 8> Ops;
6273 for (unsigned i = 0; i != NumElts; ++i) {
6274 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6275 const APInt &CInt = C->getAPIntValue();
6276 // Element types smaller than 32 bits are not legal, so use i32 elements.
6277 // The values are implicitly truncated so sext vs. zext doesn't matter.
6278 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6280 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6281 MVT::getVectorVT(TruncVT, NumElts), Ops);
6284 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6285 unsigned Opcode = N->getOpcode();
6286 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6287 SDNode *N0 = N->getOperand(0).getNode();
6288 SDNode *N1 = N->getOperand(1).getNode();
6289 return N0->hasOneUse() && N1->hasOneUse() &&
6290 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6295 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6296 unsigned Opcode = N->getOpcode();
6297 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6298 SDNode *N0 = N->getOperand(0).getNode();
6299 SDNode *N1 = N->getOperand(1).getNode();
6300 return N0->hasOneUse() && N1->hasOneUse() &&
6301 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6306 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6307 // Multiplications are only custom-lowered for 128-bit vectors so that
6308 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6309 EVT VT = Op.getValueType();
6310 assert(VT.is128BitVector() && VT.isInteger() &&
6311 "unexpected type for custom-lowering ISD::MUL");
6312 SDNode *N0 = Op.getOperand(0).getNode();
6313 SDNode *N1 = Op.getOperand(1).getNode();
6314 unsigned NewOpc = 0;
6316 bool isN0SExt = isSignExtended(N0, DAG);
6317 bool isN1SExt = isSignExtended(N1, DAG);
6318 if (isN0SExt && isN1SExt)
6319 NewOpc = ARMISD::VMULLs;
6321 bool isN0ZExt = isZeroExtended(N0, DAG);
6322 bool isN1ZExt = isZeroExtended(N1, DAG);
6323 if (isN0ZExt && isN1ZExt)
6324 NewOpc = ARMISD::VMULLu;
6325 else if (isN1SExt || isN1ZExt) {
6326 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6327 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6328 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6329 NewOpc = ARMISD::VMULLs;
6331 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6332 NewOpc = ARMISD::VMULLu;
6334 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6336 NewOpc = ARMISD::VMULLu;
6342 if (VT == MVT::v2i64)
6343 // Fall through to expand this. It is not legal.
6346 // Other vector multiplications are legal.
6351 // Legalize to a VMULL instruction.
6354 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6356 Op0 = SkipExtensionForVMULL(N0, DAG);
6357 assert(Op0.getValueType().is64BitVector() &&
6358 Op1.getValueType().is64BitVector() &&
6359 "unexpected types for extended operands to VMULL");
6360 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6363 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6364 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6371 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6372 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6373 EVT Op1VT = Op1.getValueType();
6374 return DAG.getNode(N0->getOpcode(), DL, VT,
6375 DAG.getNode(NewOpc, DL, VT,
6376 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6377 DAG.getNode(NewOpc, DL, VT,
6378 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6382 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6383 // TODO: Should this propagate fast-math-flags?
6386 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6387 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6388 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6389 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6390 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6391 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6392 // Get reciprocal estimate.
6393 // float4 recip = vrecpeq_f32(yf);
6394 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6395 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6397 // Because char has a smaller range than uchar, we can actually get away
6398 // without any newton steps. This requires that we use a weird bias
6399 // of 0xb000, however (again, this has been exhaustively tested).
6400 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6401 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6402 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6403 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6404 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6405 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6406 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6407 // Convert back to short.
6408 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6409 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6414 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6415 // TODO: Should this propagate fast-math-flags?
6418 // Convert to float.
6419 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6420 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6421 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6422 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6423 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6424 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6426 // Use reciprocal estimate and one refinement step.
6427 // float4 recip = vrecpeq_f32(yf);
6428 // recip *= vrecpsq_f32(yf, recip);
6429 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6430 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6432 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6433 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6435 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6436 // Because short has a smaller range than ushort, we can actually get away
6437 // with only a single newton step. This requires that we use a weird bias
6438 // of 89, however (again, this has been exhaustively tested).
6439 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6440 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6441 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6442 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6443 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6444 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6445 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6446 // Convert back to integer and return.
6447 // return vmovn_s32(vcvt_s32_f32(result));
6448 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6449 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6453 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6454 EVT VT = Op.getValueType();
6455 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6456 "unexpected type for custom-lowering ISD::SDIV");
6459 SDValue N0 = Op.getOperand(0);
6460 SDValue N1 = Op.getOperand(1);
6463 if (VT == MVT::v8i8) {
6464 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6465 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6467 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6468 DAG.getIntPtrConstant(4, dl));
6469 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6470 DAG.getIntPtrConstant(4, dl));
6471 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6472 DAG.getIntPtrConstant(0, dl));
6473 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6474 DAG.getIntPtrConstant(0, dl));
6476 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6477 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6479 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6480 N0 = LowerCONCAT_VECTORS(N0, DAG);
6482 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6485 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6488 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6489 // TODO: Should this propagate fast-math-flags?
6490 EVT VT = Op.getValueType();
6491 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6492 "unexpected type for custom-lowering ISD::UDIV");
6495 SDValue N0 = Op.getOperand(0);
6496 SDValue N1 = Op.getOperand(1);
6499 if (VT == MVT::v8i8) {
6500 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6501 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6503 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6504 DAG.getIntPtrConstant(4, dl));
6505 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6506 DAG.getIntPtrConstant(4, dl));
6507 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6508 DAG.getIntPtrConstant(0, dl));
6509 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6510 DAG.getIntPtrConstant(0, dl));
6512 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6513 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6515 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6516 N0 = LowerCONCAT_VECTORS(N0, DAG);
6518 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6519 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6525 // v4i16 sdiv ... Convert to float.
6526 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6527 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6528 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6529 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6530 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6531 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6533 // Use reciprocal estimate and two refinement steps.
6534 // float4 recip = vrecpeq_f32(yf);
6535 // recip *= vrecpsq_f32(yf, recip);
6536 // recip *= vrecpsq_f32(yf, recip);
6537 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6538 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6540 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6541 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6543 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6544 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6545 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6547 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6548 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6549 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6550 // and that it will never cause us to return an answer too large).
6551 // float4 result = as_float4(as_int4(xf*recip) + 2);
6552 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6553 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6554 N1 = DAG.getConstant(2, dl, MVT::i32);
6555 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6556 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6557 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6558 // Convert back to integer and return.
6559 // return vmovn_u32(vcvt_s32_f32(result));
6560 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6561 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6565 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6566 EVT VT = Op.getNode()->getValueType(0);
6567 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6570 bool ExtraOp = false;
6571 switch (Op.getOpcode()) {
6572 default: llvm_unreachable("Invalid code");
6573 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6574 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6575 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6576 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6580 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6582 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6583 Op.getOperand(1), Op.getOperand(2));
6586 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6587 assert(Subtarget->isTargetDarwin());
6589 // For iOS, we want to call an alternative entry point: __sincos_stret,
6590 // return values are passed via sret.
6592 SDValue Arg = Op.getOperand(0);
6593 EVT ArgVT = Arg.getValueType();
6594 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6595 auto PtrVT = getPointerTy(DAG.getDataLayout());
6597 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6598 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6600 // Pair of floats / doubles used to pass the result.
6601 Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6602 auto &DL = DAG.getDataLayout();
6605 bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6607 if (ShouldUseSRet) {
6608 // Create stack object for sret.
6609 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6610 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6611 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6612 SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6616 Entry.Ty = RetTy->getPointerTo();
6617 Entry.isSExt = false;
6618 Entry.isZExt = false;
6619 Entry.isSRet = true;
6620 Args.push_back(Entry);
6621 RetTy = Type::getVoidTy(*DAG.getContext());
6627 Entry.isSExt = false;
6628 Entry.isZExt = false;
6629 Args.push_back(Entry);
6631 const char *LibcallName =
6632 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6634 (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6635 CallingConv::ID CC = getLibcallCallingConv(LC);
6636 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6638 TargetLowering::CallLoweringInfo CLI(DAG);
6640 .setChain(DAG.getEntryNode())
6641 .setCallee(CC, RetTy, Callee, std::move(Args), 0)
6642 .setDiscardResult(ShouldUseSRet);
6643 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6646 return CallResult.first;
6648 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6649 MachinePointerInfo(), false, false, false, 0);
6651 // Address of cos field.
6652 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6653 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6654 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6655 MachinePointerInfo(), false, false, false, 0);
6657 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6658 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6659 LoadSin.getValue(0), LoadCos.getValue(0));
6662 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6663 SDValue &Chain) const {
6664 EVT VT = Op.getValueType();
6665 assert((VT == MVT::i32 || VT == MVT::i64) &&
6666 "unexpected type for custom lowering DIV");
6669 const auto &DL = DAG.getDataLayout();
6670 const auto &TLI = DAG.getTargetLoweringInfo();
6672 const char *Name = nullptr;
6673 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6675 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6677 ARMTargetLowering::ArgListTy Args;
6679 for (auto AI : {1, 0}) {
6681 Arg.Node = Op.getOperand(AI);
6682 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6683 Args.push_back(Arg);
6686 CallLoweringInfo CLI(DAG);
6689 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6690 ES, std::move(Args), 0);
6692 return LowerCallTo(CLI).first;
6695 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op,
6696 SelectionDAG &DAG) const {
6697 assert(Op.getValueType() == MVT::i32 &&
6698 "unexpected type for custom lowering DIV");
6701 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6702 DAG.getEntryNode(), Op.getOperand(1));
6704 return LowerWindowsDIVLibCall(Op, DAG, DBZCHK);
6707 void ARMTargetLowering::ExpandDIV_Windows(
6708 SDValue Op, SelectionDAG &DAG,
6709 SmallVectorImpl<SDValue> &Results) const {
6710 const auto &DL = DAG.getDataLayout();
6711 const auto &TLI = DAG.getTargetLoweringInfo();
6713 assert(Op.getValueType() == MVT::i64 &&
6714 "unexpected type for custom lowering DIV");
6717 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6718 DAG.getConstant(0, dl, MVT::i32));
6719 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6720 DAG.getConstant(1, dl, MVT::i32));
6721 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6724 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6726 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, DBZCHK);
6728 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6729 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6730 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6731 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6733 Results.push_back(Lower);
6734 Results.push_back(Upper);
6737 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6738 // Monotonic load/store is legal for all targets
6739 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6742 // Acquire/Release load/store is not legal for targets without a
6743 // dmb or equivalent available.
6747 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6748 SmallVectorImpl<SDValue> &Results,
6750 const ARMSubtarget *Subtarget) {
6752 // Under Power Management extensions, the cycle-count is:
6753 // mrc p15, #0, <Rt>, c9, c13, #0
6754 SDValue Ops[] = { N->getOperand(0), // Chain
6755 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6756 DAG.getConstant(15, DL, MVT::i32),
6757 DAG.getConstant(0, DL, MVT::i32),
6758 DAG.getConstant(9, DL, MVT::i32),
6759 DAG.getConstant(13, DL, MVT::i32),
6760 DAG.getConstant(0, DL, MVT::i32)
6763 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6764 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6765 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6766 DAG.getConstant(0, DL, MVT::i32)));
6767 Results.push_back(Cycles32.getValue(1));
6770 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6771 switch (Op.getOpcode()) {
6772 default: llvm_unreachable("Don't know how to custom lower this!");
6773 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6774 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6775 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6776 case ISD::GlobalAddress:
6777 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6778 default: llvm_unreachable("unknown object format");
6780 return LowerGlobalAddressWindows(Op, DAG);
6782 return LowerGlobalAddressELF(Op, DAG);
6784 return LowerGlobalAddressDarwin(Op, DAG);
6786 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6787 case ISD::SELECT: return LowerSELECT(Op, DAG);
6788 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6789 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6790 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6791 case ISD::VASTART: return LowerVASTART(Op, DAG);
6792 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6793 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6794 case ISD::SINT_TO_FP:
6795 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6796 case ISD::FP_TO_SINT:
6797 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6798 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6799 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6800 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6801 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6802 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6803 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6804 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6806 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6809 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6810 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
6811 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
6812 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6813 case ISD::SRL_PARTS:
6814 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6816 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6817 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6818 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6819 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6820 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6821 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6822 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6823 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6824 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6825 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6826 case ISD::MUL: return LowerMUL(Op, DAG);
6827 case ISD::SDIV: return LowerSDIV(Op, DAG);
6829 if (Subtarget->isTargetWindows())
6830 return LowerDIV_Windows(Op, DAG);
6831 return LowerUDIV(Op, DAG);
6835 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6840 return LowerXALUO(Op, DAG);
6841 case ISD::ATOMIC_LOAD:
6842 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6843 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6845 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6846 case ISD::DYNAMIC_STACKALLOC:
6847 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6848 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6849 llvm_unreachable("Don't know how to custom lower this!");
6850 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6851 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6852 case ARMISD::WIN__DBZCHK: return SDValue();
6856 /// ReplaceNodeResults - Replace the results of node with an illegal result
6857 /// type with new values built out of custom code.
6858 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6859 SmallVectorImpl<SDValue> &Results,
6860 SelectionDAG &DAG) const {
6862 switch (N->getOpcode()) {
6864 llvm_unreachable("Don't know how to custom expand this!");
6865 case ISD::READ_REGISTER:
6866 ExpandREAD_REGISTER(N, Results, DAG);
6869 Res = ExpandBITCAST(N, DAG);
6873 Res = Expand64BitShift(N, DAG, Subtarget);
6877 Res = LowerREM(N, DAG);
6879 case ISD::READCYCLECOUNTER:
6880 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6883 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6884 return ExpandDIV_Windows(SDValue(N, 0), DAG, Results);
6887 Results.push_back(Res);
6890 //===----------------------------------------------------------------------===//
6891 // ARM Scheduler Hooks
6892 //===----------------------------------------------------------------------===//
6894 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6895 /// registers the function context.
6896 void ARMTargetLowering::
6897 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6898 MachineBasicBlock *DispatchBB, int FI) const {
6899 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6900 DebugLoc dl = MI->getDebugLoc();
6901 MachineFunction *MF = MBB->getParent();
6902 MachineRegisterInfo *MRI = &MF->getRegInfo();
6903 MachineConstantPool *MCP = MF->getConstantPool();
6904 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6905 const Function *F = MF->getFunction();
6907 bool isThumb = Subtarget->isThumb();
6908 bool isThumb2 = Subtarget->isThumb2();
6910 unsigned PCLabelId = AFI->createPICLabelUId();
6911 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6912 ARMConstantPoolValue *CPV =
6913 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6914 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6916 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6917 : &ARM::GPRRegClass;
6919 // Grab constant pool and fixed stack memory operands.
6920 MachineMemOperand *CPMMO =
6921 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6922 MachineMemOperand::MOLoad, 4, 4);
6924 MachineMemOperand *FIMMOSt =
6925 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6926 MachineMemOperand::MOStore, 4, 4);
6928 // Load the address of the dispatch MBB into the jump buffer.
6930 // Incoming value: jbuf
6931 // ldr.n r5, LCPI1_1
6934 // str r5, [$jbuf, #+4] ; &jbuf[1]
6935 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6936 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6937 .addConstantPoolIndex(CPI)
6938 .addMemOperand(CPMMO));
6939 // Set the low bit because of thumb mode.
6940 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6942 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6943 .addReg(NewVReg1, RegState::Kill)
6945 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6946 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6947 .addReg(NewVReg2, RegState::Kill)
6949 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6950 .addReg(NewVReg3, RegState::Kill)
6952 .addImm(36) // &jbuf[1] :: pc
6953 .addMemOperand(FIMMOSt));
6954 } else if (isThumb) {
6955 // Incoming value: jbuf
6956 // ldr.n r1, LCPI1_4
6960 // add r2, $jbuf, #+4 ; &jbuf[1]
6962 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6963 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6964 .addConstantPoolIndex(CPI)
6965 .addMemOperand(CPMMO));
6966 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6967 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6968 .addReg(NewVReg1, RegState::Kill)
6970 // Set the low bit because of thumb mode.
6971 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6972 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6973 .addReg(ARM::CPSR, RegState::Define)
6975 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6976 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6977 .addReg(ARM::CPSR, RegState::Define)
6978 .addReg(NewVReg2, RegState::Kill)
6979 .addReg(NewVReg3, RegState::Kill));
6980 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6981 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6983 .addImm(36); // &jbuf[1] :: pc
6984 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6985 .addReg(NewVReg4, RegState::Kill)
6986 .addReg(NewVReg5, RegState::Kill)
6988 .addMemOperand(FIMMOSt));
6990 // Incoming value: jbuf
6993 // str r1, [$jbuf, #+4] ; &jbuf[1]
6994 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6995 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6996 .addConstantPoolIndex(CPI)
6998 .addMemOperand(CPMMO));
6999 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7000 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7001 .addReg(NewVReg1, RegState::Kill)
7002 .addImm(PCLabelId));
7003 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7004 .addReg(NewVReg2, RegState::Kill)
7006 .addImm(36) // &jbuf[1] :: pc
7007 .addMemOperand(FIMMOSt));
7011 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7012 MachineBasicBlock *MBB) const {
7013 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7014 DebugLoc dl = MI->getDebugLoc();
7015 MachineFunction *MF = MBB->getParent();
7016 MachineRegisterInfo *MRI = &MF->getRegInfo();
7017 MachineFrameInfo *MFI = MF->getFrameInfo();
7018 int FI = MFI->getFunctionContextIndex();
7020 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7021 : &ARM::GPRnopcRegClass;
7023 // Get a mapping of the call site numbers to all of the landing pads they're
7025 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7026 unsigned MaxCSNum = 0;
7027 MachineModuleInfo &MMI = MF->getMMI();
7028 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7030 if (!BB->isEHPad()) continue;
7032 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7034 for (MachineBasicBlock::iterator
7035 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7036 if (!II->isEHLabel()) continue;
7038 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7039 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7041 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7042 for (SmallVectorImpl<unsigned>::iterator
7043 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7044 CSI != CSE; ++CSI) {
7045 CallSiteNumToLPad[*CSI].push_back(&*BB);
7046 MaxCSNum = std::max(MaxCSNum, *CSI);
7052 // Get an ordered list of the machine basic blocks for the jump table.
7053 std::vector<MachineBasicBlock*> LPadList;
7054 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7055 LPadList.reserve(CallSiteNumToLPad.size());
7056 for (unsigned I = 1; I <= MaxCSNum; ++I) {
7057 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7058 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7059 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7060 LPadList.push_back(*II);
7061 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7065 assert(!LPadList.empty() &&
7066 "No landing pad destinations for the dispatch jump table!");
7068 // Create the jump table and associated information.
7069 MachineJumpTableInfo *JTI =
7070 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7071 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7072 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7074 // Create the MBBs for the dispatch code.
7076 // Shove the dispatch's address into the return slot in the function context.
7077 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7078 DispatchBB->setIsEHPad();
7080 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7081 unsigned trap_opcode;
7082 if (Subtarget->isThumb())
7083 trap_opcode = ARM::tTRAP;
7085 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7087 BuildMI(TrapBB, dl, TII->get(trap_opcode));
7088 DispatchBB->addSuccessor(TrapBB);
7090 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7091 DispatchBB->addSuccessor(DispContBB);
7094 MF->insert(MF->end(), DispatchBB);
7095 MF->insert(MF->end(), DispContBB);
7096 MF->insert(MF->end(), TrapBB);
7098 // Insert code into the entry block that creates and registers the function
7100 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7102 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7103 MachinePointerInfo::getFixedStack(*MF, FI),
7104 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7106 MachineInstrBuilder MIB;
7107 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7109 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7110 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7112 // Add a register mask with no preserved registers. This results in all
7113 // registers being marked as clobbered.
7114 MIB.addRegMask(RI.getNoPreservedMask());
7116 unsigned NumLPads = LPadList.size();
7117 if (Subtarget->isThumb2()) {
7118 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7119 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7122 .addMemOperand(FIMMOLd));
7124 if (NumLPads < 256) {
7125 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7127 .addImm(LPadList.size()));
7129 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7130 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7131 .addImm(NumLPads & 0xFFFF));
7133 unsigned VReg2 = VReg1;
7134 if ((NumLPads & 0xFFFF0000) != 0) {
7135 VReg2 = MRI->createVirtualRegister(TRC);
7136 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7138 .addImm(NumLPads >> 16));
7141 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7146 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7151 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7152 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7153 .addJumpTableIndex(MJTI));
7155 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7158 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7159 .addReg(NewVReg3, RegState::Kill)
7161 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7163 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7164 .addReg(NewVReg4, RegState::Kill)
7166 .addJumpTableIndex(MJTI);
7167 } else if (Subtarget->isThumb()) {
7168 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7169 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7172 .addMemOperand(FIMMOLd));
7174 if (NumLPads < 256) {
7175 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7179 MachineConstantPool *ConstantPool = MF->getConstantPool();
7180 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7181 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7183 // MachineConstantPool wants an explicit alignment.
7184 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7186 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7187 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7189 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7190 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7191 .addReg(VReg1, RegState::Define)
7192 .addConstantPoolIndex(Idx));
7193 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7198 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7203 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7204 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7205 .addReg(ARM::CPSR, RegState::Define)
7209 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7210 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7211 .addJumpTableIndex(MJTI));
7213 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7214 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7215 .addReg(ARM::CPSR, RegState::Define)
7216 .addReg(NewVReg2, RegState::Kill)
7219 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7220 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7222 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7223 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7224 .addReg(NewVReg4, RegState::Kill)
7226 .addMemOperand(JTMMOLd));
7228 unsigned NewVReg6 = NewVReg5;
7229 if (RelocM == Reloc::PIC_) {
7230 NewVReg6 = MRI->createVirtualRegister(TRC);
7231 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7232 .addReg(ARM::CPSR, RegState::Define)
7233 .addReg(NewVReg5, RegState::Kill)
7237 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7238 .addReg(NewVReg6, RegState::Kill)
7239 .addJumpTableIndex(MJTI);
7241 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7242 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7245 .addMemOperand(FIMMOLd));
7247 if (NumLPads < 256) {
7248 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7251 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7252 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7253 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7254 .addImm(NumLPads & 0xFFFF));
7256 unsigned VReg2 = VReg1;
7257 if ((NumLPads & 0xFFFF0000) != 0) {
7258 VReg2 = MRI->createVirtualRegister(TRC);
7259 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7261 .addImm(NumLPads >> 16));
7264 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7268 MachineConstantPool *ConstantPool = MF->getConstantPool();
7269 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7270 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7272 // MachineConstantPool wants an explicit alignment.
7273 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7275 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7276 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7278 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7279 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7280 .addReg(VReg1, RegState::Define)
7281 .addConstantPoolIndex(Idx)
7283 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7285 .addReg(VReg1, RegState::Kill));
7288 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7293 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7295 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7297 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7298 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7299 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7300 .addJumpTableIndex(MJTI));
7302 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7303 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7304 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7306 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7307 .addReg(NewVReg3, RegState::Kill)
7310 .addMemOperand(JTMMOLd));
7312 if (RelocM == Reloc::PIC_) {
7313 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7314 .addReg(NewVReg5, RegState::Kill)
7316 .addJumpTableIndex(MJTI);
7318 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7319 .addReg(NewVReg5, RegState::Kill)
7320 .addJumpTableIndex(MJTI);
7324 // Add the jump table entries as successors to the MBB.
7325 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7326 for (std::vector<MachineBasicBlock*>::iterator
7327 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7328 MachineBasicBlock *CurMBB = *I;
7329 if (SeenMBBs.insert(CurMBB).second)
7330 DispContBB->addSuccessor(CurMBB);
7333 // N.B. the order the invoke BBs are processed in doesn't matter here.
7334 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7335 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7336 for (MachineBasicBlock *BB : InvokeBBs) {
7338 // Remove the landing pad successor from the invoke block and replace it
7339 // with the new dispatch block.
7340 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7342 while (!Successors.empty()) {
7343 MachineBasicBlock *SMBB = Successors.pop_back_val();
7344 if (SMBB->isEHPad()) {
7345 BB->removeSuccessor(SMBB);
7346 MBBLPads.push_back(SMBB);
7350 BB->addSuccessor(DispatchBB);
7352 // Find the invoke call and mark all of the callee-saved registers as
7353 // 'implicit defined' so that they're spilled. This prevents code from
7354 // moving instructions to before the EH block, where they will never be
7356 for (MachineBasicBlock::reverse_iterator
7357 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7358 if (!II->isCall()) continue;
7360 DenseMap<unsigned, bool> DefRegs;
7361 for (MachineInstr::mop_iterator
7362 OI = II->operands_begin(), OE = II->operands_end();
7364 if (!OI->isReg()) continue;
7365 DefRegs[OI->getReg()] = true;
7368 MachineInstrBuilder MIB(*MF, &*II);
7370 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7371 unsigned Reg = SavedRegs[i];
7372 if (Subtarget->isThumb2() &&
7373 !ARM::tGPRRegClass.contains(Reg) &&
7374 !ARM::hGPRRegClass.contains(Reg))
7376 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7378 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7381 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7388 // Mark all former landing pads as non-landing pads. The dispatch is the only
7390 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7391 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7392 (*I)->setIsEHPad(false);
7394 // The instruction is gone now.
7395 MI->eraseFromParent();
7399 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7400 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7401 E = MBB->succ_end(); I != E; ++I)
7404 llvm_unreachable("Expecting a BB with two successors!");
7407 /// Return the load opcode for a given load size. If load size >= 8,
7408 /// neon opcode will be returned.
7409 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7411 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7412 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7414 return LdSize == 4 ? ARM::tLDRi
7415 : LdSize == 2 ? ARM::tLDRHi
7416 : LdSize == 1 ? ARM::tLDRBi : 0;
7418 return LdSize == 4 ? ARM::t2LDR_POST
7419 : LdSize == 2 ? ARM::t2LDRH_POST
7420 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7421 return LdSize == 4 ? ARM::LDR_POST_IMM
7422 : LdSize == 2 ? ARM::LDRH_POST
7423 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7426 /// Return the store opcode for a given store size. If store size >= 8,
7427 /// neon opcode will be returned.
7428 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7430 return StSize == 16 ? ARM::VST1q32wb_fixed
7431 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7433 return StSize == 4 ? ARM::tSTRi
7434 : StSize == 2 ? ARM::tSTRHi
7435 : StSize == 1 ? ARM::tSTRBi : 0;
7437 return StSize == 4 ? ARM::t2STR_POST
7438 : StSize == 2 ? ARM::t2STRH_POST
7439 : StSize == 1 ? ARM::t2STRB_POST : 0;
7440 return StSize == 4 ? ARM::STR_POST_IMM
7441 : StSize == 2 ? ARM::STRH_POST
7442 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7445 /// Emit a post-increment load operation with given size. The instructions
7446 /// will be added to BB at Pos.
7447 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7448 const TargetInstrInfo *TII, DebugLoc dl,
7449 unsigned LdSize, unsigned Data, unsigned AddrIn,
7450 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7451 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7452 assert(LdOpc != 0 && "Should have a load opcode");
7454 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7455 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7457 } else if (IsThumb1) {
7458 // load + update AddrIn
7459 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7460 .addReg(AddrIn).addImm(0));
7461 MachineInstrBuilder MIB =
7462 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7463 MIB = AddDefaultT1CC(MIB);
7464 MIB.addReg(AddrIn).addImm(LdSize);
7465 AddDefaultPred(MIB);
7466 } else if (IsThumb2) {
7467 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7468 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7471 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7472 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7473 .addReg(0).addImm(LdSize));
7477 /// Emit a post-increment store operation with given size. The instructions
7478 /// will be added to BB at Pos.
7479 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7480 const TargetInstrInfo *TII, DebugLoc dl,
7481 unsigned StSize, unsigned Data, unsigned AddrIn,
7482 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7483 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7484 assert(StOpc != 0 && "Should have a store opcode");
7486 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7487 .addReg(AddrIn).addImm(0).addReg(Data));
7488 } else if (IsThumb1) {
7489 // store + update AddrIn
7490 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7491 .addReg(AddrIn).addImm(0));
7492 MachineInstrBuilder MIB =
7493 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7494 MIB = AddDefaultT1CC(MIB);
7495 MIB.addReg(AddrIn).addImm(StSize);
7496 AddDefaultPred(MIB);
7497 } else if (IsThumb2) {
7498 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7499 .addReg(Data).addReg(AddrIn).addImm(StSize));
7501 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7502 .addReg(Data).addReg(AddrIn).addReg(0)
7508 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7509 MachineBasicBlock *BB) const {
7510 // This pseudo instruction has 3 operands: dst, src, size
7511 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7512 // Otherwise, we will generate unrolled scalar copies.
7513 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7514 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7515 MachineFunction::iterator It = ++BB->getIterator();
7517 unsigned dest = MI->getOperand(0).getReg();
7518 unsigned src = MI->getOperand(1).getReg();
7519 unsigned SizeVal = MI->getOperand(2).getImm();
7520 unsigned Align = MI->getOperand(3).getImm();
7521 DebugLoc dl = MI->getDebugLoc();
7523 MachineFunction *MF = BB->getParent();
7524 MachineRegisterInfo &MRI = MF->getRegInfo();
7525 unsigned UnitSize = 0;
7526 const TargetRegisterClass *TRC = nullptr;
7527 const TargetRegisterClass *VecTRC = nullptr;
7529 bool IsThumb1 = Subtarget->isThumb1Only();
7530 bool IsThumb2 = Subtarget->isThumb2();
7534 } else if (Align & 2) {
7537 // Check whether we can use NEON instructions.
7538 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7539 Subtarget->hasNEON()) {
7540 if ((Align % 16 == 0) && SizeVal >= 16)
7542 else if ((Align % 8 == 0) && SizeVal >= 8)
7545 // Can't use NEON instructions.
7550 // Select the correct opcode and register class for unit size load/store
7551 bool IsNeon = UnitSize >= 8;
7552 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7554 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7555 : UnitSize == 8 ? &ARM::DPRRegClass
7558 unsigned BytesLeft = SizeVal % UnitSize;
7559 unsigned LoopSize = SizeVal - BytesLeft;
7561 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7562 // Use LDR and STR to copy.
7563 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7564 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7565 unsigned srcIn = src;
7566 unsigned destIn = dest;
7567 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7568 unsigned srcOut = MRI.createVirtualRegister(TRC);
7569 unsigned destOut = MRI.createVirtualRegister(TRC);
7570 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7571 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7572 IsThumb1, IsThumb2);
7573 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7574 IsThumb1, IsThumb2);
7579 // Handle the leftover bytes with LDRB and STRB.
7580 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7581 // [destOut] = STRB_POST(scratch, destIn, 1)
7582 for (unsigned i = 0; i < BytesLeft; i++) {
7583 unsigned srcOut = MRI.createVirtualRegister(TRC);
7584 unsigned destOut = MRI.createVirtualRegister(TRC);
7585 unsigned scratch = MRI.createVirtualRegister(TRC);
7586 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7587 IsThumb1, IsThumb2);
7588 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7589 IsThumb1, IsThumb2);
7593 MI->eraseFromParent(); // The instruction is gone now.
7597 // Expand the pseudo op to a loop.
7600 // movw varEnd, # --> with thumb2
7602 // ldrcp varEnd, idx --> without thumb2
7603 // fallthrough --> loopMBB
7605 // PHI varPhi, varEnd, varLoop
7606 // PHI srcPhi, src, srcLoop
7607 // PHI destPhi, dst, destLoop
7608 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7609 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7610 // subs varLoop, varPhi, #UnitSize
7612 // fallthrough --> exitMBB
7614 // epilogue to handle left-over bytes
7615 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7616 // [destOut] = STRB_POST(scratch, destLoop, 1)
7617 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7618 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7619 MF->insert(It, loopMBB);
7620 MF->insert(It, exitMBB);
7622 // Transfer the remainder of BB and its successor edges to exitMBB.
7623 exitMBB->splice(exitMBB->begin(), BB,
7624 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7625 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7627 // Load an immediate to varEnd.
7628 unsigned varEnd = MRI.createVirtualRegister(TRC);
7629 if (Subtarget->useMovt(*MF)) {
7630 unsigned Vtmp = varEnd;
7631 if ((LoopSize & 0xFFFF0000) != 0)
7632 Vtmp = MRI.createVirtualRegister(TRC);
7633 AddDefaultPred(BuildMI(BB, dl,
7634 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7635 Vtmp).addImm(LoopSize & 0xFFFF));
7637 if ((LoopSize & 0xFFFF0000) != 0)
7638 AddDefaultPred(BuildMI(BB, dl,
7639 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7642 .addImm(LoopSize >> 16));
7644 MachineConstantPool *ConstantPool = MF->getConstantPool();
7645 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7646 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7648 // MachineConstantPool wants an explicit alignment.
7649 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7651 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7652 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7655 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7656 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7658 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7659 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7661 BB->addSuccessor(loopMBB);
7663 // Generate the loop body:
7664 // varPhi = PHI(varLoop, varEnd)
7665 // srcPhi = PHI(srcLoop, src)
7666 // destPhi = PHI(destLoop, dst)
7667 MachineBasicBlock *entryBB = BB;
7669 unsigned varLoop = MRI.createVirtualRegister(TRC);
7670 unsigned varPhi = MRI.createVirtualRegister(TRC);
7671 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7672 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7673 unsigned destLoop = MRI.createVirtualRegister(TRC);
7674 unsigned destPhi = MRI.createVirtualRegister(TRC);
7676 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7677 .addReg(varLoop).addMBB(loopMBB)
7678 .addReg(varEnd).addMBB(entryBB);
7679 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7680 .addReg(srcLoop).addMBB(loopMBB)
7681 .addReg(src).addMBB(entryBB);
7682 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7683 .addReg(destLoop).addMBB(loopMBB)
7684 .addReg(dest).addMBB(entryBB);
7686 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7687 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7688 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7689 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7690 IsThumb1, IsThumb2);
7691 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7692 IsThumb1, IsThumb2);
7694 // Decrement loop variable by UnitSize.
7696 MachineInstrBuilder MIB =
7697 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7698 MIB = AddDefaultT1CC(MIB);
7699 MIB.addReg(varPhi).addImm(UnitSize);
7700 AddDefaultPred(MIB);
7702 MachineInstrBuilder MIB =
7703 BuildMI(*BB, BB->end(), dl,
7704 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7705 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7706 MIB->getOperand(5).setReg(ARM::CPSR);
7707 MIB->getOperand(5).setIsDef(true);
7709 BuildMI(*BB, BB->end(), dl,
7710 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7711 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7713 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7714 BB->addSuccessor(loopMBB);
7715 BB->addSuccessor(exitMBB);
7717 // Add epilogue to handle BytesLeft.
7719 MachineInstr *StartOfExit = exitMBB->begin();
7721 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7722 // [destOut] = STRB_POST(scratch, destLoop, 1)
7723 unsigned srcIn = srcLoop;
7724 unsigned destIn = destLoop;
7725 for (unsigned i = 0; i < BytesLeft; i++) {
7726 unsigned srcOut = MRI.createVirtualRegister(TRC);
7727 unsigned destOut = MRI.createVirtualRegister(TRC);
7728 unsigned scratch = MRI.createVirtualRegister(TRC);
7729 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7730 IsThumb1, IsThumb2);
7731 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7732 IsThumb1, IsThumb2);
7737 MI->eraseFromParent(); // The instruction is gone now.
7742 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7743 MachineBasicBlock *MBB) const {
7744 const TargetMachine &TM = getTargetMachine();
7745 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7746 DebugLoc DL = MI->getDebugLoc();
7748 assert(Subtarget->isTargetWindows() &&
7749 "__chkstk is only supported on Windows");
7750 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7752 // __chkstk takes the number of words to allocate on the stack in R4, and
7753 // returns the stack adjustment in number of bytes in R4. This will not
7754 // clober any other registers (other than the obvious lr).
7756 // Although, technically, IP should be considered a register which may be
7757 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7758 // thumb-2 environment, so there is no interworking required. As a result, we
7759 // do not expect a veneer to be emitted by the linker, clobbering IP.
7761 // Each module receives its own copy of __chkstk, so no import thunk is
7762 // required, again, ensuring that IP is not clobbered.
7764 // Finally, although some linkers may theoretically provide a trampoline for
7765 // out of range calls (which is quite common due to a 32M range limitation of
7766 // branches for Thumb), we can generate the long-call version via
7767 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7770 switch (TM.getCodeModel()) {
7771 case CodeModel::Small:
7772 case CodeModel::Medium:
7773 case CodeModel::Default:
7774 case CodeModel::Kernel:
7775 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7776 .addImm((unsigned)ARMCC::AL).addReg(0)
7777 .addExternalSymbol("__chkstk")
7778 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7779 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7780 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7782 case CodeModel::Large:
7783 case CodeModel::JITDefault: {
7784 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7785 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7787 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7788 .addExternalSymbol("__chkstk");
7789 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7790 .addImm((unsigned)ARMCC::AL).addReg(0)
7791 .addReg(Reg, RegState::Kill)
7792 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7793 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7794 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7799 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7801 .addReg(ARM::SP).addReg(ARM::R4)));
7803 MI->eraseFromParent();
7808 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7809 MachineBasicBlock *MBB) const {
7810 DebugLoc DL = MI->getDebugLoc();
7811 MachineFunction *MF = MBB->getParent();
7812 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7814 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7815 MF->push_back(ContBB);
7816 ContBB->splice(ContBB->begin(), MBB,
7817 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7818 MBB->addSuccessor(ContBB);
7820 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7821 MF->push_back(TrapBB);
7822 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7823 MBB->addSuccessor(TrapBB);
7825 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7826 .addReg(MI->getOperand(0).getReg())
7829 MI->eraseFromParent();
7834 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7835 MachineBasicBlock *BB) const {
7836 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7837 DebugLoc dl = MI->getDebugLoc();
7838 bool isThumb2 = Subtarget->isThumb2();
7839 switch (MI->getOpcode()) {
7842 llvm_unreachable("Unexpected instr type to insert");
7844 // The Thumb2 pre-indexed stores have the same MI operands, they just
7845 // define them differently in the .td files from the isel patterns, so
7846 // they need pseudos.
7847 case ARM::t2STR_preidx:
7848 MI->setDesc(TII->get(ARM::t2STR_PRE));
7850 case ARM::t2STRB_preidx:
7851 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7853 case ARM::t2STRH_preidx:
7854 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7857 case ARM::STRi_preidx:
7858 case ARM::STRBi_preidx: {
7859 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7860 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7861 // Decode the offset.
7862 unsigned Offset = MI->getOperand(4).getImm();
7863 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7864 Offset = ARM_AM::getAM2Offset(Offset);
7868 MachineMemOperand *MMO = *MI->memoperands_begin();
7869 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7870 .addOperand(MI->getOperand(0)) // Rn_wb
7871 .addOperand(MI->getOperand(1)) // Rt
7872 .addOperand(MI->getOperand(2)) // Rn
7873 .addImm(Offset) // offset (skip GPR==zero_reg)
7874 .addOperand(MI->getOperand(5)) // pred
7875 .addOperand(MI->getOperand(6))
7876 .addMemOperand(MMO);
7877 MI->eraseFromParent();
7880 case ARM::STRr_preidx:
7881 case ARM::STRBr_preidx:
7882 case ARM::STRH_preidx: {
7884 switch (MI->getOpcode()) {
7885 default: llvm_unreachable("unexpected opcode!");
7886 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7887 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7888 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7890 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7891 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7892 MIB.addOperand(MI->getOperand(i));
7893 MI->eraseFromParent();
7897 case ARM::tMOVCCr_pseudo: {
7898 // To "insert" a SELECT_CC instruction, we actually have to insert the
7899 // diamond control-flow pattern. The incoming instruction knows the
7900 // destination vreg to set, the condition code register to branch on, the
7901 // true/false values to select between, and a branch opcode to use.
7902 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7903 MachineFunction::iterator It = ++BB->getIterator();
7908 // cmpTY ccX, r1, r2
7910 // fallthrough --> copy0MBB
7911 MachineBasicBlock *thisMBB = BB;
7912 MachineFunction *F = BB->getParent();
7913 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7914 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7915 F->insert(It, copy0MBB);
7916 F->insert(It, sinkMBB);
7918 // Transfer the remainder of BB and its successor edges to sinkMBB.
7919 sinkMBB->splice(sinkMBB->begin(), BB,
7920 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7921 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7923 BB->addSuccessor(copy0MBB);
7924 BB->addSuccessor(sinkMBB);
7926 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7927 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7930 // %FalseValue = ...
7931 // # fallthrough to sinkMBB
7934 // Update machine-CFG edges
7935 BB->addSuccessor(sinkMBB);
7938 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7941 BuildMI(*BB, BB->begin(), dl,
7942 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7943 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7944 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7946 MI->eraseFromParent(); // The pseudo instruction is gone now.
7951 case ARM::BCCZi64: {
7952 // If there is an unconditional branch to the other successor, remove it.
7953 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7955 // Compare both parts that make up the double comparison separately for
7957 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7959 unsigned LHS1 = MI->getOperand(1).getReg();
7960 unsigned LHS2 = MI->getOperand(2).getReg();
7962 AddDefaultPred(BuildMI(BB, dl,
7963 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7964 .addReg(LHS1).addImm(0));
7965 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7966 .addReg(LHS2).addImm(0)
7967 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7969 unsigned RHS1 = MI->getOperand(3).getReg();
7970 unsigned RHS2 = MI->getOperand(4).getReg();
7971 AddDefaultPred(BuildMI(BB, dl,
7972 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7973 .addReg(LHS1).addReg(RHS1));
7974 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7975 .addReg(LHS2).addReg(RHS2)
7976 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7979 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7980 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7981 if (MI->getOperand(0).getImm() == ARMCC::NE)
7982 std::swap(destMBB, exitMBB);
7984 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7985 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7987 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7989 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7991 MI->eraseFromParent(); // The pseudo instruction is gone now.
7995 case ARM::Int_eh_sjlj_setjmp:
7996 case ARM::Int_eh_sjlj_setjmp_nofp:
7997 case ARM::tInt_eh_sjlj_setjmp:
7998 case ARM::t2Int_eh_sjlj_setjmp:
7999 case ARM::t2Int_eh_sjlj_setjmp_nofp:
8002 case ARM::Int_eh_sjlj_setup_dispatch:
8003 EmitSjLjDispatchBlock(MI, BB);
8008 // To insert an ABS instruction, we have to insert the
8009 // diamond control-flow pattern. The incoming instruction knows the
8010 // source vreg to test against 0, the destination vreg to set,
8011 // the condition code register to branch on, the
8012 // true/false values to select between, and a branch opcode to use.
8017 // BCC (branch to SinkBB if V0 >= 0)
8018 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
8019 // SinkBB: V1 = PHI(V2, V3)
8020 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8021 MachineFunction::iterator BBI = ++BB->getIterator();
8022 MachineFunction *Fn = BB->getParent();
8023 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8024 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8025 Fn->insert(BBI, RSBBB);
8026 Fn->insert(BBI, SinkBB);
8028 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8029 unsigned int ABSDstReg = MI->getOperand(0).getReg();
8030 bool ABSSrcKIll = MI->getOperand(1).isKill();
8031 bool isThumb2 = Subtarget->isThumb2();
8032 MachineRegisterInfo &MRI = Fn->getRegInfo();
8033 // In Thumb mode S must not be specified if source register is the SP or
8034 // PC and if destination register is the SP, so restrict register class
8035 unsigned NewRsbDstReg =
8036 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8038 // Transfer the remainder of BB and its successor edges to sinkMBB.
8039 SinkBB->splice(SinkBB->begin(), BB,
8040 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8041 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8043 BB->addSuccessor(RSBBB);
8044 BB->addSuccessor(SinkBB);
8046 // fall through to SinkMBB
8047 RSBBB->addSuccessor(SinkBB);
8049 // insert a cmp at the end of BB
8050 AddDefaultPred(BuildMI(BB, dl,
8051 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8052 .addReg(ABSSrcReg).addImm(0));
8054 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8056 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8057 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8059 // insert rsbri in RSBBB
8060 // Note: BCC and rsbri will be converted into predicated rsbmi
8061 // by if-conversion pass
8062 BuildMI(*RSBBB, RSBBB->begin(), dl,
8063 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8064 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8065 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8067 // insert PHI in SinkBB,
8068 // reuse ABSDstReg to not change uses of ABS instruction
8069 BuildMI(*SinkBB, SinkBB->begin(), dl,
8070 TII->get(ARM::PHI), ABSDstReg)
8071 .addReg(NewRsbDstReg).addMBB(RSBBB)
8072 .addReg(ABSSrcReg).addMBB(BB);
8074 // remove ABS instruction
8075 MI->eraseFromParent();
8077 // return last added BB
8080 case ARM::COPY_STRUCT_BYVAL_I32:
8082 return EmitStructByval(MI, BB);
8083 case ARM::WIN__CHKSTK:
8084 return EmitLowered__chkstk(MI, BB);
8085 case ARM::WIN__DBZCHK:
8086 return EmitLowered__dbzchk(MI, BB);
8090 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8091 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8092 /// instead of as a custom inserter because we need the use list from the SDNode.
8093 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8094 MachineInstr *MI, const SDNode *Node) {
8095 bool isThumb1 = Subtarget->isThumb1Only();
8097 DebugLoc DL = MI->getDebugLoc();
8098 MachineFunction *MF = MI->getParent()->getParent();
8099 MachineRegisterInfo &MRI = MF->getRegInfo();
8100 MachineInstrBuilder MIB(*MF, MI);
8102 // If the new dst/src is unused mark it as dead.
8103 if (!Node->hasAnyUseOfValue(0)) {
8104 MI->getOperand(0).setIsDead(true);
8106 if (!Node->hasAnyUseOfValue(1)) {
8107 MI->getOperand(1).setIsDead(true);
8110 // The MEMCPY both defines and kills the scratch registers.
8111 for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8112 unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8113 : &ARM::GPRRegClass);
8114 MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8118 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8119 SDNode *Node) const {
8120 if (MI->getOpcode() == ARM::MEMCPY) {
8121 attachMEMCPYScratchRegs(Subtarget, MI, Node);
8125 const MCInstrDesc *MCID = &MI->getDesc();
8126 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8127 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8128 // operand is still set to noreg. If needed, set the optional operand's
8129 // register to CPSR, and remove the redundant implicit def.
8131 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8133 // Rename pseudo opcodes.
8134 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8136 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8137 MCID = &TII->get(NewOpc);
8139 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8140 "converted opcode should be the same except for cc_out");
8144 // Add the optional cc_out operand
8145 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8147 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8149 // Any ARM instruction that sets the 's' bit should specify an optional
8150 // "cc_out" operand in the last operand position.
8151 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8152 assert(!NewOpc && "Optional cc_out operand required");
8155 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8156 // since we already have an optional CPSR def.
8157 bool definesCPSR = false;
8158 bool deadCPSR = false;
8159 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8161 const MachineOperand &MO = MI->getOperand(i);
8162 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8166 MI->RemoveOperand(i);
8171 assert(!NewOpc && "Optional cc_out operand required");
8174 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8176 assert(!MI->getOperand(ccOutIdx).getReg() &&
8177 "expect uninitialized optional cc_out operand");
8181 // If this instruction was defined with an optional CPSR def and its dag node
8182 // had a live implicit CPSR def, then activate the optional CPSR def.
8183 MachineOperand &MO = MI->getOperand(ccOutIdx);
8184 MO.setReg(ARM::CPSR);
8188 //===----------------------------------------------------------------------===//
8189 // ARM Optimization Hooks
8190 //===----------------------------------------------------------------------===//
8192 // Helper function that checks if N is a null or all ones constant.
8193 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8194 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8197 // Return true if N is conditionally 0 or all ones.
8198 // Detects these expressions where cc is an i1 value:
8200 // (select cc 0, y) [AllOnes=0]
8201 // (select cc y, 0) [AllOnes=0]
8202 // (zext cc) [AllOnes=0]
8203 // (sext cc) [AllOnes=0/1]
8204 // (select cc -1, y) [AllOnes=1]
8205 // (select cc y, -1) [AllOnes=1]
8207 // Invert is set when N is the null/all ones constant when CC is false.
8208 // OtherOp is set to the alternative value of N.
8209 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8210 SDValue &CC, bool &Invert,
8212 SelectionDAG &DAG) {
8213 switch (N->getOpcode()) {
8214 default: return false;
8216 CC = N->getOperand(0);
8217 SDValue N1 = N->getOperand(1);
8218 SDValue N2 = N->getOperand(2);
8219 if (isZeroOrAllOnes(N1, AllOnes)) {
8224 if (isZeroOrAllOnes(N2, AllOnes)) {
8231 case ISD::ZERO_EXTEND:
8232 // (zext cc) can never be the all ones value.
8236 case ISD::SIGN_EXTEND: {
8238 EVT VT = N->getValueType(0);
8239 CC = N->getOperand(0);
8240 if (CC.getValueType() != MVT::i1)
8244 // When looking for an AllOnes constant, N is an sext, and the 'other'
8246 OtherOp = DAG.getConstant(0, dl, VT);
8247 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8248 // When looking for a 0 constant, N can be zext or sext.
8249 OtherOp = DAG.getConstant(1, dl, VT);
8251 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8258 // Combine a constant select operand into its use:
8260 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8261 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8262 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8263 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8264 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8266 // The transform is rejected if the select doesn't have a constant operand that
8267 // is null, or all ones when AllOnes is set.
8269 // Also recognize sext/zext from i1:
8271 // (add (zext cc), x) -> (select cc (add x, 1), x)
8272 // (add (sext cc), x) -> (select cc (add x, -1), x)
8274 // These transformations eventually create predicated instructions.
8276 // @param N The node to transform.
8277 // @param Slct The N operand that is a select.
8278 // @param OtherOp The other N operand (x above).
8279 // @param DCI Context.
8280 // @param AllOnes Require the select constant to be all ones instead of null.
8281 // @returns The new node, or SDValue() on failure.
8283 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8284 TargetLowering::DAGCombinerInfo &DCI,
8285 bool AllOnes = false) {
8286 SelectionDAG &DAG = DCI.DAG;
8287 EVT VT = N->getValueType(0);
8288 SDValue NonConstantVal;
8291 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8292 NonConstantVal, DAG))
8295 // Slct is now know to be the desired identity constant when CC is true.
8296 SDValue TrueVal = OtherOp;
8297 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8298 OtherOp, NonConstantVal);
8299 // Unless SwapSelectOps says CC should be false.
8301 std::swap(TrueVal, FalseVal);
8303 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8304 CCOp, TrueVal, FalseVal);
8307 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8309 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8310 TargetLowering::DAGCombinerInfo &DCI) {
8311 SDValue N0 = N->getOperand(0);
8312 SDValue N1 = N->getOperand(1);
8313 if (N0.getNode()->hasOneUse()) {
8314 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8315 if (Result.getNode())
8318 if (N1.getNode()->hasOneUse()) {
8319 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8320 if (Result.getNode())
8326 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8327 // (only after legalization).
8328 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8329 TargetLowering::DAGCombinerInfo &DCI,
8330 const ARMSubtarget *Subtarget) {
8332 // Only perform optimization if after legalize, and if NEON is available. We
8333 // also expected both operands to be BUILD_VECTORs.
8334 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8335 || N0.getOpcode() != ISD::BUILD_VECTOR
8336 || N1.getOpcode() != ISD::BUILD_VECTOR)
8339 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8340 EVT VT = N->getValueType(0);
8341 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8344 // Check that the vector operands are of the right form.
8345 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8346 // operands, where N is the size of the formed vector.
8347 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8348 // index such that we have a pair wise add pattern.
8350 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8351 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8353 SDValue Vec = N0->getOperand(0)->getOperand(0);
8354 SDNode *V = Vec.getNode();
8355 unsigned nextIndex = 0;
8357 // For each operands to the ADD which are BUILD_VECTORs,
8358 // check to see if each of their operands are an EXTRACT_VECTOR with
8359 // the same vector and appropriate index.
8360 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8361 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8362 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8364 SDValue ExtVec0 = N0->getOperand(i);
8365 SDValue ExtVec1 = N1->getOperand(i);
8367 // First operand is the vector, verify its the same.
8368 if (V != ExtVec0->getOperand(0).getNode() ||
8369 V != ExtVec1->getOperand(0).getNode())
8372 // Second is the constant, verify its correct.
8373 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8374 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8376 // For the constant, we want to see all the even or all the odd.
8377 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8378 || C1->getZExtValue() != nextIndex+1)
8387 // Create VPADDL node.
8388 SelectionDAG &DAG = DCI.DAG;
8389 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8393 // Build operand list.
8394 SmallVector<SDValue, 8> Ops;
8395 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8396 TLI.getPointerTy(DAG.getDataLayout())));
8398 // Input is the vector.
8401 // Get widened type and narrowed type.
8403 unsigned numElem = VT.getVectorNumElements();
8405 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8406 switch (inputLaneType.getSimpleVT().SimpleTy) {
8407 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8408 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8409 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8411 llvm_unreachable("Invalid vector element type for padd optimization.");
8414 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8415 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8416 return DAG.getNode(ExtOp, dl, VT, tmp);
8419 static SDValue findMUL_LOHI(SDValue V) {
8420 if (V->getOpcode() == ISD::UMUL_LOHI ||
8421 V->getOpcode() == ISD::SMUL_LOHI)
8426 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8427 TargetLowering::DAGCombinerInfo &DCI,
8428 const ARMSubtarget *Subtarget) {
8430 if (Subtarget->isThumb1Only()) return SDValue();
8432 // Only perform the checks after legalize when the pattern is available.
8433 if (DCI.isBeforeLegalize()) return SDValue();
8435 // Look for multiply add opportunities.
8436 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8437 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8438 // a glue link from the first add to the second add.
8439 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8440 // a S/UMLAL instruction.
8443 // / \ [no multiline comment]
8449 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8450 SDValue AddcOp0 = AddcNode->getOperand(0);
8451 SDValue AddcOp1 = AddcNode->getOperand(1);
8453 // Check if the two operands are from the same mul_lohi node.
8454 if (AddcOp0.getNode() == AddcOp1.getNode())
8457 assert(AddcNode->getNumValues() == 2 &&
8458 AddcNode->getValueType(0) == MVT::i32 &&
8459 "Expect ADDC with two result values. First: i32");
8461 // Check that we have a glued ADDC node.
8462 if (AddcNode->getValueType(1) != MVT::Glue)
8465 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8466 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8467 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8468 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8469 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8472 // Look for the glued ADDE.
8473 SDNode* AddeNode = AddcNode->getGluedUser();
8477 // Make sure it is really an ADDE.
8478 if (AddeNode->getOpcode() != ISD::ADDE)
8481 assert(AddeNode->getNumOperands() == 3 &&
8482 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8483 "ADDE node has the wrong inputs");
8485 // Check for the triangle shape.
8486 SDValue AddeOp0 = AddeNode->getOperand(0);
8487 SDValue AddeOp1 = AddeNode->getOperand(1);
8489 // Make sure that the ADDE operands are not coming from the same node.
8490 if (AddeOp0.getNode() == AddeOp1.getNode())
8493 // Find the MUL_LOHI node walking up ADDE's operands.
8494 bool IsLeftOperandMUL = false;
8495 SDValue MULOp = findMUL_LOHI(AddeOp0);
8496 if (MULOp == SDValue())
8497 MULOp = findMUL_LOHI(AddeOp1);
8499 IsLeftOperandMUL = true;
8500 if (MULOp == SDValue())
8503 // Figure out the right opcode.
8504 unsigned Opc = MULOp->getOpcode();
8505 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8507 // Figure out the high and low input values to the MLAL node.
8508 SDValue* HiAdd = nullptr;
8509 SDValue* LoMul = nullptr;
8510 SDValue* LowAdd = nullptr;
8512 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8513 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8516 if (IsLeftOperandMUL)
8522 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8523 // whose low result is fed to the ADDC we are checking.
8525 if (AddcOp0 == MULOp.getValue(0)) {
8529 if (AddcOp1 == MULOp.getValue(0)) {
8537 // Create the merged node.
8538 SelectionDAG &DAG = DCI.DAG;
8540 // Build operand list.
8541 SmallVector<SDValue, 8> Ops;
8542 Ops.push_back(LoMul->getOperand(0));
8543 Ops.push_back(LoMul->getOperand(1));
8544 Ops.push_back(*LowAdd);
8545 Ops.push_back(*HiAdd);
8547 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8548 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8550 // Replace the ADDs' nodes uses by the MLA node's values.
8551 SDValue HiMLALResult(MLALNode.getNode(), 1);
8552 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8554 SDValue LoMLALResult(MLALNode.getNode(), 0);
8555 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8557 // Return original node to notify the driver to stop replacing.
8558 SDValue resNode(AddcNode, 0);
8562 /// PerformADDCCombine - Target-specific dag combine transform from
8563 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8564 static SDValue PerformADDCCombine(SDNode *N,
8565 TargetLowering::DAGCombinerInfo &DCI,
8566 const ARMSubtarget *Subtarget) {
8568 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8572 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8573 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8574 /// called with the default operands, and if that fails, with commuted
8576 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8577 TargetLowering::DAGCombinerInfo &DCI,
8578 const ARMSubtarget *Subtarget){
8580 // Attempt to create vpaddl for this add.
8581 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8582 if (Result.getNode())
8585 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8586 if (N0.getNode()->hasOneUse()) {
8587 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8588 if (Result.getNode()) return Result;
8593 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8595 static SDValue PerformADDCombine(SDNode *N,
8596 TargetLowering::DAGCombinerInfo &DCI,
8597 const ARMSubtarget *Subtarget) {
8598 SDValue N0 = N->getOperand(0);
8599 SDValue N1 = N->getOperand(1);
8601 // First try with the default operand order.
8602 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8603 if (Result.getNode())
8606 // If that didn't work, try again with the operands commuted.
8607 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8610 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8612 static SDValue PerformSUBCombine(SDNode *N,
8613 TargetLowering::DAGCombinerInfo &DCI) {
8614 SDValue N0 = N->getOperand(0);
8615 SDValue N1 = N->getOperand(1);
8617 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8618 if (N1.getNode()->hasOneUse()) {
8619 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8620 if (Result.getNode()) return Result;
8626 /// PerformVMULCombine
8627 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8628 /// special multiplier accumulator forwarding.
8634 // However, for (A + B) * (A + B),
8641 static SDValue PerformVMULCombine(SDNode *N,
8642 TargetLowering::DAGCombinerInfo &DCI,
8643 const ARMSubtarget *Subtarget) {
8644 if (!Subtarget->hasVMLxForwarding())
8647 SelectionDAG &DAG = DCI.DAG;
8648 SDValue N0 = N->getOperand(0);
8649 SDValue N1 = N->getOperand(1);
8650 unsigned Opcode = N0.getOpcode();
8651 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8652 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8653 Opcode = N1.getOpcode();
8654 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8655 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8663 EVT VT = N->getValueType(0);
8665 SDValue N00 = N0->getOperand(0);
8666 SDValue N01 = N0->getOperand(1);
8667 return DAG.getNode(Opcode, DL, VT,
8668 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8669 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8672 static SDValue PerformMULCombine(SDNode *N,
8673 TargetLowering::DAGCombinerInfo &DCI,
8674 const ARMSubtarget *Subtarget) {
8675 SelectionDAG &DAG = DCI.DAG;
8677 if (Subtarget->isThumb1Only())
8680 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8683 EVT VT = N->getValueType(0);
8684 if (VT.is64BitVector() || VT.is128BitVector())
8685 return PerformVMULCombine(N, DCI, Subtarget);
8689 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8693 int64_t MulAmt = C->getSExtValue();
8694 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8696 ShiftAmt = ShiftAmt & (32 - 1);
8697 SDValue V = N->getOperand(0);
8701 MulAmt >>= ShiftAmt;
8704 if (isPowerOf2_32(MulAmt - 1)) {
8705 // (mul x, 2^N + 1) => (add (shl x, N), x)
8706 Res = DAG.getNode(ISD::ADD, DL, VT,
8708 DAG.getNode(ISD::SHL, DL, VT,
8710 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8712 } else if (isPowerOf2_32(MulAmt + 1)) {
8713 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8714 Res = DAG.getNode(ISD::SUB, DL, VT,
8715 DAG.getNode(ISD::SHL, DL, VT,
8717 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8723 uint64_t MulAmtAbs = -MulAmt;
8724 if (isPowerOf2_32(MulAmtAbs + 1)) {
8725 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8726 Res = DAG.getNode(ISD::SUB, DL, VT,
8728 DAG.getNode(ISD::SHL, DL, VT,
8730 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8732 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8733 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8734 Res = DAG.getNode(ISD::ADD, DL, VT,
8736 DAG.getNode(ISD::SHL, DL, VT,
8738 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8740 Res = DAG.getNode(ISD::SUB, DL, VT,
8741 DAG.getConstant(0, DL, MVT::i32), Res);
8748 Res = DAG.getNode(ISD::SHL, DL, VT,
8749 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8751 // Do not add new nodes to DAG combiner worklist.
8752 DCI.CombineTo(N, Res, false);
8756 static SDValue PerformANDCombine(SDNode *N,
8757 TargetLowering::DAGCombinerInfo &DCI,
8758 const ARMSubtarget *Subtarget) {
8760 // Attempt to use immediate-form VBIC
8761 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8763 EVT VT = N->getValueType(0);
8764 SelectionDAG &DAG = DCI.DAG;
8766 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8769 APInt SplatBits, SplatUndef;
8770 unsigned SplatBitSize;
8773 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8774 if (SplatBitSize <= 64) {
8776 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8777 SplatUndef.getZExtValue(), SplatBitSize,
8778 DAG, dl, VbicVT, VT.is128BitVector(),
8780 if (Val.getNode()) {
8782 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8783 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8784 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8789 if (!Subtarget->isThumb1Only()) {
8790 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8791 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8792 if (Result.getNode())
8799 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8800 static SDValue PerformORCombine(SDNode *N,
8801 TargetLowering::DAGCombinerInfo &DCI,
8802 const ARMSubtarget *Subtarget) {
8803 // Attempt to use immediate-form VORR
8804 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8806 EVT VT = N->getValueType(0);
8807 SelectionDAG &DAG = DCI.DAG;
8809 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8812 APInt SplatBits, SplatUndef;
8813 unsigned SplatBitSize;
8815 if (BVN && Subtarget->hasNEON() &&
8816 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8817 if (SplatBitSize <= 64) {
8819 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8820 SplatUndef.getZExtValue(), SplatBitSize,
8821 DAG, dl, VorrVT, VT.is128BitVector(),
8823 if (Val.getNode()) {
8825 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8826 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8827 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8832 if (!Subtarget->isThumb1Only()) {
8833 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8834 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8835 if (Result.getNode())
8839 // The code below optimizes (or (and X, Y), Z).
8840 // The AND operand needs to have a single user to make these optimizations
8842 SDValue N0 = N->getOperand(0);
8843 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8845 SDValue N1 = N->getOperand(1);
8847 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8848 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8849 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8851 unsigned SplatBitSize;
8854 APInt SplatBits0, SplatBits1;
8855 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8856 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8857 // Ensure that the second operand of both ands are constants
8858 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8859 HasAnyUndefs) && !HasAnyUndefs) {
8860 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8861 HasAnyUndefs) && !HasAnyUndefs) {
8862 // Ensure that the bit width of the constants are the same and that
8863 // the splat arguments are logical inverses as per the pattern we
8864 // are trying to simplify.
8865 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8866 SplatBits0 == ~SplatBits1) {
8867 // Canonicalize the vector type to make instruction selection
8869 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8870 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8874 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8880 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8883 // BFI is only available on V6T2+
8884 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8888 // 1) or (and A, mask), val => ARMbfi A, val, mask
8889 // iff (val & mask) == val
8891 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8892 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8893 // && mask == ~mask2
8894 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8895 // && ~mask == mask2
8896 // (i.e., copy a bitfield value into another bitfield of the same width)
8901 SDValue N00 = N0.getOperand(0);
8903 // The value and the mask need to be constants so we can verify this is
8904 // actually a bitfield set. If the mask is 0xffff, we can do better
8905 // via a movt instruction, so don't use BFI in that case.
8906 SDValue MaskOp = N0.getOperand(1);
8907 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8910 unsigned Mask = MaskC->getZExtValue();
8914 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8915 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8917 unsigned Val = N1C->getZExtValue();
8918 if ((Val & ~Mask) != Val)
8921 if (ARM::isBitFieldInvertedMask(Mask)) {
8922 Val >>= countTrailingZeros(~Mask);
8924 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8925 DAG.getConstant(Val, DL, MVT::i32),
8926 DAG.getConstant(Mask, DL, MVT::i32));
8928 // Do not add new nodes to DAG combiner worklist.
8929 DCI.CombineTo(N, Res, false);
8932 } else if (N1.getOpcode() == ISD::AND) {
8933 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8934 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8937 unsigned Mask2 = N11C->getZExtValue();
8939 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8941 if (ARM::isBitFieldInvertedMask(Mask) &&
8943 // The pack halfword instruction works better for masks that fit it,
8944 // so use that when it's available.
8945 if (Subtarget->hasT2ExtractPack() &&
8946 (Mask == 0xffff || Mask == 0xffff0000))
8949 unsigned amt = countTrailingZeros(Mask2);
8950 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8951 DAG.getConstant(amt, DL, MVT::i32));
8952 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8953 DAG.getConstant(Mask, DL, MVT::i32));
8954 // Do not add new nodes to DAG combiner worklist.
8955 DCI.CombineTo(N, Res, false);
8957 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8959 // The pack halfword instruction works better for masks that fit it,
8960 // so use that when it's available.
8961 if (Subtarget->hasT2ExtractPack() &&
8962 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8965 unsigned lsb = countTrailingZeros(Mask);
8966 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8967 DAG.getConstant(lsb, DL, MVT::i32));
8968 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8969 DAG.getConstant(Mask2, DL, MVT::i32));
8970 // Do not add new nodes to DAG combiner worklist.
8971 DCI.CombineTo(N, Res, false);
8976 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8977 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8978 ARM::isBitFieldInvertedMask(~Mask)) {
8979 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8980 // where lsb(mask) == #shamt and masked bits of B are known zero.
8981 SDValue ShAmt = N00.getOperand(1);
8982 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8983 unsigned LSB = countTrailingZeros(Mask);
8987 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8988 DAG.getConstant(~Mask, DL, MVT::i32));
8990 // Do not add new nodes to DAG combiner worklist.
8991 DCI.CombineTo(N, Res, false);
8997 static SDValue PerformXORCombine(SDNode *N,
8998 TargetLowering::DAGCombinerInfo &DCI,
8999 const ARMSubtarget *Subtarget) {
9000 EVT VT = N->getValueType(0);
9001 SelectionDAG &DAG = DCI.DAG;
9003 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9006 if (!Subtarget->isThumb1Only()) {
9007 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9008 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
9009 if (Result.getNode())
9016 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9017 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9018 // their position in "to" (Rd).
9019 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9020 assert(N->getOpcode() == ARMISD::BFI);
9022 SDValue From = N->getOperand(1);
9023 ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9024 FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9026 // If the Base came from a SHR #C, we can deduce that it is really testing bit
9027 // #C in the base of the SHR.
9028 if (From->getOpcode() == ISD::SRL &&
9029 isa<ConstantSDNode>(From->getOperand(1))) {
9030 APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9031 assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9032 FromMask <<= Shift.getLimitedValue(31);
9033 From = From->getOperand(0);
9039 // If A and B contain one contiguous set of bits, does A | B == A . B?
9041 // Neither A nor B must be zero.
9042 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9043 unsigned LastActiveBitInA = A.countTrailingZeros();
9044 unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9045 return LastActiveBitInA - 1 == FirstActiveBitInB;
9048 static SDValue FindBFIToCombineWith(SDNode *N) {
9049 // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9051 APInt ToMask, FromMask;
9052 SDValue From = ParseBFI(N, ToMask, FromMask);
9053 SDValue To = N->getOperand(0);
9055 // Now check for a compatible BFI to merge with. We can pass through BFIs that
9056 // aren't compatible, but not if they set the same bit in their destination as
9057 // we do (or that of any BFI we're going to combine with).
9059 APInt CombinedToMask = ToMask;
9060 while (V.getOpcode() == ARMISD::BFI) {
9061 APInt NewToMask, NewFromMask;
9062 SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9063 if (NewFrom != From) {
9064 // This BFI has a different base. Keep going.
9065 CombinedToMask |= NewToMask;
9066 V = V.getOperand(0);
9070 // Do the written bits conflict with any we've seen so far?
9071 if ((NewToMask & CombinedToMask).getBoolValue())
9072 // Conflicting bits - bail out because going further is unsafe.
9075 // Are the new bits contiguous when combined with the old bits?
9076 if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9077 BitsProperlyConcatenate(FromMask, NewFromMask))
9079 if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9080 BitsProperlyConcatenate(NewFromMask, FromMask))
9083 // We've seen a write to some bits, so track it.
9084 CombinedToMask |= NewToMask;
9086 V = V.getOperand(0);
9092 static SDValue PerformBFICombine(SDNode *N,
9093 TargetLowering::DAGCombinerInfo &DCI) {
9094 SDValue N1 = N->getOperand(1);
9095 if (N1.getOpcode() == ISD::AND) {
9096 // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9097 // the bits being cleared by the AND are not demanded by the BFI.
9098 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9101 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9102 unsigned LSB = countTrailingZeros(~InvMask);
9103 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9105 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9106 "undefined behavior");
9107 unsigned Mask = (1u << Width) - 1;
9108 unsigned Mask2 = N11C->getZExtValue();
9109 if ((Mask & (~Mask2)) == 0)
9110 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9111 N->getOperand(0), N1.getOperand(0),
9113 } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9114 // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9115 // Keep track of any consecutive bits set that all come from the same base
9116 // value. We can combine these together into a single BFI.
9117 SDValue CombineBFI = FindBFIToCombineWith(N);
9118 if (CombineBFI == SDValue())
9121 // We've found a BFI.
9122 APInt ToMask1, FromMask1;
9123 SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9125 APInt ToMask2, FromMask2;
9126 SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9127 assert(From1 == From2);
9130 // First, unlink CombineBFI.
9131 DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9132 // Then create a new BFI, combining the two together.
9133 APInt NewFromMask = FromMask1 | FromMask2;
9134 APInt NewToMask = ToMask1 | ToMask2;
9136 EVT VT = N->getValueType(0);
9139 if (NewFromMask[0] == 0)
9140 From1 = DCI.DAG.getNode(
9141 ISD::SRL, dl, VT, From1,
9142 DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
9143 return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
9144 DCI.DAG.getConstant(~NewToMask, dl, VT));
9149 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9150 /// ARMISD::VMOVRRD.
9151 static SDValue PerformVMOVRRDCombine(SDNode *N,
9152 TargetLowering::DAGCombinerInfo &DCI,
9153 const ARMSubtarget *Subtarget) {
9154 // vmovrrd(vmovdrr x, y) -> x,y
9155 SDValue InDouble = N->getOperand(0);
9156 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9157 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9159 // vmovrrd(load f64) -> (load i32), (load i32)
9160 SDNode *InNode = InDouble.getNode();
9161 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9162 InNode->getValueType(0) == MVT::f64 &&
9163 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9164 !cast<LoadSDNode>(InNode)->isVolatile()) {
9165 // TODO: Should this be done for non-FrameIndex operands?
9166 LoadSDNode *LD = cast<LoadSDNode>(InNode);
9168 SelectionDAG &DAG = DCI.DAG;
9170 SDValue BasePtr = LD->getBasePtr();
9171 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9172 LD->getPointerInfo(), LD->isVolatile(),
9173 LD->isNonTemporal(), LD->isInvariant(),
9174 LD->getAlignment());
9176 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9177 DAG.getConstant(4, DL, MVT::i32));
9178 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9179 LD->getPointerInfo(), LD->isVolatile(),
9180 LD->isNonTemporal(), LD->isInvariant(),
9181 std::min(4U, LD->getAlignment() / 2));
9183 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9184 if (DCI.DAG.getDataLayout().isBigEndian())
9185 std::swap (NewLD1, NewLD2);
9186 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9193 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9194 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
9195 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9196 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9197 SDValue Op0 = N->getOperand(0);
9198 SDValue Op1 = N->getOperand(1);
9199 if (Op0.getOpcode() == ISD::BITCAST)
9200 Op0 = Op0.getOperand(0);
9201 if (Op1.getOpcode() == ISD::BITCAST)
9202 Op1 = Op1.getOperand(0);
9203 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9204 Op0.getNode() == Op1.getNode() &&
9205 Op0.getResNo() == 0 && Op1.getResNo() == 1)
9206 return DAG.getNode(ISD::BITCAST, SDLoc(N),
9207 N->getValueType(0), Op0.getOperand(0));
9211 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9212 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9213 /// i64 vector to have f64 elements, since the value can then be loaded
9214 /// directly into a VFP register.
9215 static bool hasNormalLoadOperand(SDNode *N) {
9216 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9217 for (unsigned i = 0; i < NumElts; ++i) {
9218 SDNode *Elt = N->getOperand(i).getNode();
9219 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9225 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9226 /// ISD::BUILD_VECTOR.
9227 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9228 TargetLowering::DAGCombinerInfo &DCI,
9229 const ARMSubtarget *Subtarget) {
9230 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9231 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9232 // into a pair of GPRs, which is fine when the value is used as a scalar,
9233 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9234 SelectionDAG &DAG = DCI.DAG;
9235 if (N->getNumOperands() == 2) {
9236 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9241 // Load i64 elements as f64 values so that type legalization does not split
9242 // them up into i32 values.
9243 EVT VT = N->getValueType(0);
9244 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9247 SmallVector<SDValue, 8> Ops;
9248 unsigned NumElts = VT.getVectorNumElements();
9249 for (unsigned i = 0; i < NumElts; ++i) {
9250 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9252 // Make the DAGCombiner fold the bitcast.
9253 DCI.AddToWorklist(V.getNode());
9255 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9256 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9257 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9260 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9262 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9263 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9264 // At that time, we may have inserted bitcasts from integer to float.
9265 // If these bitcasts have survived DAGCombine, change the lowering of this
9266 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9267 // force to use floating point types.
9269 // Make sure we can change the type of the vector.
9270 // This is possible iff:
9271 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9272 // 1.1. Vector is used only once.
9273 // 1.2. Use is a bit convert to an integer type.
9274 // 2. The size of its operands are 32-bits (64-bits are not legal).
9275 EVT VT = N->getValueType(0);
9276 EVT EltVT = VT.getVectorElementType();
9278 // Check 1.1. and 2.
9279 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9282 // By construction, the input type must be float.
9283 assert(EltVT == MVT::f32 && "Unexpected type!");
9286 SDNode *Use = *N->use_begin();
9287 if (Use->getOpcode() != ISD::BITCAST ||
9288 Use->getValueType(0).isFloatingPoint())
9291 // Check profitability.
9292 // Model is, if more than half of the relevant operands are bitcast from
9293 // i32, turn the build_vector into a sequence of insert_vector_elt.
9294 // Relevant operands are everything that is not statically
9295 // (i.e., at compile time) bitcasted.
9296 unsigned NumOfBitCastedElts = 0;
9297 unsigned NumElts = VT.getVectorNumElements();
9298 unsigned NumOfRelevantElts = NumElts;
9299 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9300 SDValue Elt = N->getOperand(Idx);
9301 if (Elt->getOpcode() == ISD::BITCAST) {
9302 // Assume only bit cast to i32 will go away.
9303 if (Elt->getOperand(0).getValueType() == MVT::i32)
9304 ++NumOfBitCastedElts;
9305 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9306 // Constants are statically casted, thus do not count them as
9307 // relevant operands.
9308 --NumOfRelevantElts;
9311 // Check if more than half of the elements require a non-free bitcast.
9312 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9315 SelectionDAG &DAG = DCI.DAG;
9316 // Create the new vector type.
9317 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9318 // Check if the type is legal.
9319 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9320 if (!TLI.isTypeLegal(VecVT))
9324 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9325 // => BITCAST INSERT_VECTOR_ELT
9326 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9328 SDValue Vec = DAG.getUNDEF(VecVT);
9330 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9331 SDValue V = N->getOperand(Idx);
9332 if (V.getOpcode() == ISD::UNDEF)
9334 if (V.getOpcode() == ISD::BITCAST &&
9335 V->getOperand(0).getValueType() == MVT::i32)
9336 // Fold obvious case.
9337 V = V.getOperand(0);
9339 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9340 // Make the DAGCombiner fold the bitcasts.
9341 DCI.AddToWorklist(V.getNode());
9343 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9344 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9346 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9347 // Make the DAGCombiner fold the bitcasts.
9348 DCI.AddToWorklist(Vec.getNode());
9352 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9353 /// ISD::INSERT_VECTOR_ELT.
9354 static SDValue PerformInsertEltCombine(SDNode *N,
9355 TargetLowering::DAGCombinerInfo &DCI) {
9356 // Bitcast an i64 load inserted into a vector to f64.
9357 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9358 EVT VT = N->getValueType(0);
9359 SDNode *Elt = N->getOperand(1).getNode();
9360 if (VT.getVectorElementType() != MVT::i64 ||
9361 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9364 SelectionDAG &DAG = DCI.DAG;
9366 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9367 VT.getVectorNumElements());
9368 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9369 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9370 // Make the DAGCombiner fold the bitcasts.
9371 DCI.AddToWorklist(Vec.getNode());
9372 DCI.AddToWorklist(V.getNode());
9373 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9374 Vec, V, N->getOperand(2));
9375 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9378 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9379 /// ISD::VECTOR_SHUFFLE.
9380 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9381 // The LLVM shufflevector instruction does not require the shuffle mask
9382 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9383 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9384 // operands do not match the mask length, they are extended by concatenating
9385 // them with undef vectors. That is probably the right thing for other
9386 // targets, but for NEON it is better to concatenate two double-register
9387 // size vector operands into a single quad-register size vector. Do that
9388 // transformation here:
9389 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9390 // shuffle(concat(v1, v2), undef)
9391 SDValue Op0 = N->getOperand(0);
9392 SDValue Op1 = N->getOperand(1);
9393 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9394 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9395 Op0.getNumOperands() != 2 ||
9396 Op1.getNumOperands() != 2)
9398 SDValue Concat0Op1 = Op0.getOperand(1);
9399 SDValue Concat1Op1 = Op1.getOperand(1);
9400 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9401 Concat1Op1.getOpcode() != ISD::UNDEF)
9403 // Skip the transformation if any of the types are illegal.
9404 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9405 EVT VT = N->getValueType(0);
9406 if (!TLI.isTypeLegal(VT) ||
9407 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9408 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9411 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9412 Op0.getOperand(0), Op1.getOperand(0));
9413 // Translate the shuffle mask.
9414 SmallVector<int, 16> NewMask;
9415 unsigned NumElts = VT.getVectorNumElements();
9416 unsigned HalfElts = NumElts/2;
9417 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9418 for (unsigned n = 0; n < NumElts; ++n) {
9419 int MaskElt = SVN->getMaskElt(n);
9421 if (MaskElt < (int)HalfElts)
9423 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9424 NewElt = HalfElts + MaskElt - NumElts;
9425 NewMask.push_back(NewElt);
9427 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9428 DAG.getUNDEF(VT), NewMask.data());
9431 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9432 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9433 /// base address updates.
9434 /// For generic load/stores, the memory type is assumed to be a vector.
9435 /// The caller is assumed to have checked legality.
9436 static SDValue CombineBaseUpdate(SDNode *N,
9437 TargetLowering::DAGCombinerInfo &DCI) {
9438 SelectionDAG &DAG = DCI.DAG;
9439 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9440 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9441 const bool isStore = N->getOpcode() == ISD::STORE;
9442 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9443 SDValue Addr = N->getOperand(AddrOpIdx);
9444 MemSDNode *MemN = cast<MemSDNode>(N);
9447 // Search for a use of the address operand that is an increment.
9448 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9449 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9451 if (User->getOpcode() != ISD::ADD ||
9452 UI.getUse().getResNo() != Addr.getResNo())
9455 // Check that the add is independent of the load/store. Otherwise, folding
9456 // it would create a cycle.
9457 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9460 // Find the new opcode for the updating load/store.
9461 bool isLoadOp = true;
9462 bool isLaneOp = false;
9463 unsigned NewOpc = 0;
9464 unsigned NumVecs = 0;
9466 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9468 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9469 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9471 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9473 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9475 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9477 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9478 NumVecs = 2; isLaneOp = true; break;
9479 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9480 NumVecs = 3; isLaneOp = true; break;
9481 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9482 NumVecs = 4; isLaneOp = true; break;
9483 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9484 NumVecs = 1; isLoadOp = false; break;
9485 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9486 NumVecs = 2; isLoadOp = false; break;
9487 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9488 NumVecs = 3; isLoadOp = false; break;
9489 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9490 NumVecs = 4; isLoadOp = false; break;
9491 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9492 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9493 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9494 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9495 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9496 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9500 switch (N->getOpcode()) {
9501 default: llvm_unreachable("unexpected opcode for Neon base update");
9502 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9503 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9504 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9505 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9506 NumVecs = 1; isLaneOp = false; break;
9507 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9508 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9512 // Find the size of memory referenced by the load/store.
9515 VecTy = N->getValueType(0);
9516 } else if (isIntrinsic) {
9517 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9519 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9520 VecTy = N->getOperand(1).getValueType();
9523 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9525 NumBytes /= VecTy.getVectorNumElements();
9527 // If the increment is a constant, it must match the memory ref size.
9528 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9529 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9530 uint64_t IncVal = CInc->getZExtValue();
9531 if (IncVal != NumBytes)
9533 } else if (NumBytes >= 3 * 16) {
9534 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9535 // separate instructions that make it harder to use a non-constant update.
9539 // OK, we found an ADD we can fold into the base update.
9540 // Now, create a _UPD node, taking care of not breaking alignment.
9542 EVT AlignedVecTy = VecTy;
9543 unsigned Alignment = MemN->getAlignment();
9545 // If this is a less-than-standard-aligned load/store, change the type to
9546 // match the standard alignment.
9547 // The alignment is overlooked when selecting _UPD variants; and it's
9548 // easier to introduce bitcasts here than fix that.
9549 // There are 3 ways to get to this base-update combine:
9550 // - intrinsics: they are assumed to be properly aligned (to the standard
9551 // alignment of the memory type), so we don't need to do anything.
9552 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9553 // intrinsics, so, likewise, there's nothing to do.
9554 // - generic load/store instructions: the alignment is specified as an
9555 // explicit operand, rather than implicitly as the standard alignment
9556 // of the memory type (like the intrisics). We need to change the
9557 // memory type to match the explicit alignment. That way, we don't
9558 // generate non-standard-aligned ARMISD::VLDx nodes.
9559 if (isa<LSBaseSDNode>(N)) {
9562 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9563 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9564 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9565 assert(!isLaneOp && "Unexpected generic load/store lane.");
9566 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9567 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9569 // Don't set an explicit alignment on regular load/stores that we want
9570 // to transform to VLD/VST 1_UPD nodes.
9571 // This matches the behavior of regular load/stores, which only get an
9572 // explicit alignment if the MMO alignment is larger than the standard
9573 // alignment of the memory type.
9574 // Intrinsics, however, always get an explicit alignment, set to the
9575 // alignment of the MMO.
9579 // Create the new updating load/store node.
9580 // First, create an SDVTList for the new updating node's results.
9582 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9584 for (n = 0; n < NumResultVecs; ++n)
9585 Tys[n] = AlignedVecTy;
9586 Tys[n++] = MVT::i32;
9587 Tys[n] = MVT::Other;
9588 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9590 // Then, gather the new node's operands.
9591 SmallVector<SDValue, 8> Ops;
9592 Ops.push_back(N->getOperand(0)); // incoming chain
9593 Ops.push_back(N->getOperand(AddrOpIdx));
9596 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9597 // Try to match the intrinsic's signature
9598 Ops.push_back(StN->getValue());
9600 // Loads (and of course intrinsics) match the intrinsics' signature,
9601 // so just add all but the alignment operand.
9602 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9603 Ops.push_back(N->getOperand(i));
9606 // For all node types, the alignment operand is always the last one.
9607 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9609 // If this is a non-standard-aligned STORE, the penultimate operand is the
9610 // stored value. Bitcast it to the aligned type.
9611 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9612 SDValue &StVal = Ops[Ops.size()-2];
9613 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9616 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9618 MemN->getMemOperand());
9621 SmallVector<SDValue, 5> NewResults;
9622 for (unsigned i = 0; i < NumResultVecs; ++i)
9623 NewResults.push_back(SDValue(UpdN.getNode(), i));
9625 // If this is an non-standard-aligned LOAD, the first result is the loaded
9626 // value. Bitcast it to the expected result type.
9627 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9628 SDValue &LdVal = NewResults[0];
9629 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9632 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9633 DCI.CombineTo(N, NewResults);
9634 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9641 static SDValue PerformVLDCombine(SDNode *N,
9642 TargetLowering::DAGCombinerInfo &DCI) {
9643 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9646 return CombineBaseUpdate(N, DCI);
9649 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9650 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9651 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9653 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9654 SelectionDAG &DAG = DCI.DAG;
9655 EVT VT = N->getValueType(0);
9656 // vldN-dup instructions only support 64-bit vectors for N > 1.
9657 if (!VT.is64BitVector())
9660 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9661 SDNode *VLD = N->getOperand(0).getNode();
9662 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9664 unsigned NumVecs = 0;
9665 unsigned NewOpc = 0;
9666 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9667 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9669 NewOpc = ARMISD::VLD2DUP;
9670 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9672 NewOpc = ARMISD::VLD3DUP;
9673 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9675 NewOpc = ARMISD::VLD4DUP;
9680 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9681 // numbers match the load.
9682 unsigned VLDLaneNo =
9683 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9684 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9686 // Ignore uses of the chain result.
9687 if (UI.getUse().getResNo() == NumVecs)
9690 if (User->getOpcode() != ARMISD::VDUPLANE ||
9691 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9695 // Create the vldN-dup node.
9698 for (n = 0; n < NumVecs; ++n)
9700 Tys[n] = MVT::Other;
9701 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9702 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9703 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9704 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9705 Ops, VLDMemInt->getMemoryVT(),
9706 VLDMemInt->getMemOperand());
9709 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9711 unsigned ResNo = UI.getUse().getResNo();
9712 // Ignore uses of the chain result.
9713 if (ResNo == NumVecs)
9716 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9719 // Now the vldN-lane intrinsic is dead except for its chain result.
9720 // Update uses of the chain.
9721 std::vector<SDValue> VLDDupResults;
9722 for (unsigned n = 0; n < NumVecs; ++n)
9723 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9724 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9725 DCI.CombineTo(VLD, VLDDupResults);
9730 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9731 /// ARMISD::VDUPLANE.
9732 static SDValue PerformVDUPLANECombine(SDNode *N,
9733 TargetLowering::DAGCombinerInfo &DCI) {
9734 SDValue Op = N->getOperand(0);
9736 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9737 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9738 if (CombineVLDDUP(N, DCI))
9739 return SDValue(N, 0);
9741 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9742 // redundant. Ignore bit_converts for now; element sizes are checked below.
9743 while (Op.getOpcode() == ISD::BITCAST)
9744 Op = Op.getOperand(0);
9745 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9748 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9749 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9750 // The canonical VMOV for a zero vector uses a 32-bit element size.
9751 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9753 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9755 EVT VT = N->getValueType(0);
9756 if (EltSize > VT.getVectorElementType().getSizeInBits())
9759 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9762 static SDValue PerformLOADCombine(SDNode *N,
9763 TargetLowering::DAGCombinerInfo &DCI) {
9764 EVT VT = N->getValueType(0);
9766 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9767 if (ISD::isNormalLoad(N) && VT.isVector() &&
9768 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9769 return CombineBaseUpdate(N, DCI);
9774 /// PerformSTORECombine - Target-specific dag combine xforms for
9776 static SDValue PerformSTORECombine(SDNode *N,
9777 TargetLowering::DAGCombinerInfo &DCI) {
9778 StoreSDNode *St = cast<StoreSDNode>(N);
9779 if (St->isVolatile())
9782 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9783 // pack all of the elements in one place. Next, store to memory in fewer
9785 SDValue StVal = St->getValue();
9786 EVT VT = StVal.getValueType();
9787 if (St->isTruncatingStore() && VT.isVector()) {
9788 SelectionDAG &DAG = DCI.DAG;
9789 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9790 EVT StVT = St->getMemoryVT();
9791 unsigned NumElems = VT.getVectorNumElements();
9792 assert(StVT != VT && "Cannot truncate to the same type");
9793 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9794 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9796 // From, To sizes and ElemCount must be pow of two
9797 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9799 // We are going to use the original vector elt for storing.
9800 // Accumulated smaller vector elements must be a multiple of the store size.
9801 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9803 unsigned SizeRatio = FromEltSz / ToEltSz;
9804 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9806 // Create a type on which we perform the shuffle.
9807 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9808 NumElems*SizeRatio);
9809 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9812 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9813 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9814 for (unsigned i = 0; i < NumElems; ++i)
9815 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9816 ? (i + 1) * SizeRatio - 1
9819 // Can't shuffle using an illegal type.
9820 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9822 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9823 DAG.getUNDEF(WideVec.getValueType()),
9825 // At this point all of the data is stored at the bottom of the
9826 // register. We now need to save it to mem.
9828 // Find the largest store unit
9829 MVT StoreType = MVT::i8;
9830 for (MVT Tp : MVT::integer_valuetypes()) {
9831 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9834 // Didn't find a legal store type.
9835 if (!TLI.isTypeLegal(StoreType))
9838 // Bitcast the original vector into a vector of store-size units
9839 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9840 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9841 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9842 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9843 SmallVector<SDValue, 8> Chains;
9844 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9845 TLI.getPointerTy(DAG.getDataLayout()));
9846 SDValue BasePtr = St->getBasePtr();
9848 // Perform one or more big stores into memory.
9849 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9850 for (unsigned I = 0; I < E; I++) {
9851 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9852 StoreType, ShuffWide,
9853 DAG.getIntPtrConstant(I, DL));
9854 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9855 St->getPointerInfo(), St->isVolatile(),
9856 St->isNonTemporal(), St->getAlignment());
9857 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9859 Chains.push_back(Ch);
9861 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9864 if (!ISD::isNormalStore(St))
9867 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9868 // ARM stores of arguments in the same cache line.
9869 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9870 StVal.getNode()->hasOneUse()) {
9871 SelectionDAG &DAG = DCI.DAG;
9872 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9874 SDValue BasePtr = St->getBasePtr();
9875 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9876 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9877 BasePtr, St->getPointerInfo(), St->isVolatile(),
9878 St->isNonTemporal(), St->getAlignment());
9880 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9881 DAG.getConstant(4, DL, MVT::i32));
9882 return DAG.getStore(NewST1.getValue(0), DL,
9883 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9884 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9885 St->isNonTemporal(),
9886 std::min(4U, St->getAlignment() / 2));
9889 if (StVal.getValueType() == MVT::i64 &&
9890 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9892 // Bitcast an i64 store extracted from a vector to f64.
9893 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9894 SelectionDAG &DAG = DCI.DAG;
9896 SDValue IntVec = StVal.getOperand(0);
9897 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9898 IntVec.getValueType().getVectorNumElements());
9899 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9900 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9901 Vec, StVal.getOperand(1));
9903 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9904 // Make the DAGCombiner fold the bitcasts.
9905 DCI.AddToWorklist(Vec.getNode());
9906 DCI.AddToWorklist(ExtElt.getNode());
9907 DCI.AddToWorklist(V.getNode());
9908 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9909 St->getPointerInfo(), St->isVolatile(),
9910 St->isNonTemporal(), St->getAlignment(),
9914 // If this is a legal vector store, try to combine it into a VST1_UPD.
9915 if (ISD::isNormalStore(N) && VT.isVector() &&
9916 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9917 return CombineBaseUpdate(N, DCI);
9922 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9923 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9924 /// when the VMUL has a constant operand that is a power of 2.
9926 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9927 /// vmul.f32 d16, d17, d16
9928 /// vcvt.s32.f32 d16, d16
9930 /// vcvt.s32.f32 d16, d16, #3
9931 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
9932 const ARMSubtarget *Subtarget) {
9933 if (!Subtarget->hasNEON())
9936 SDValue Op = N->getOperand(0);
9937 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
9940 SDValue ConstVec = Op->getOperand(1);
9941 if (!isa<BuildVectorSDNode>(ConstVec))
9944 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9945 uint32_t FloatBits = FloatTy.getSizeInBits();
9946 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9947 uint32_t IntBits = IntTy.getSizeInBits();
9948 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9949 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9950 // These instructions only exist converting from f32 to i32. We can handle
9951 // smaller integers by generating an extra truncate, but larger ones would
9952 // be lossy. We also can't handle more then 4 lanes, since these intructions
9953 // only support v2i32/v4i32 types.
9957 BitVector UndefElements;
9958 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9959 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9960 if (C == -1 || C == 0 || C > 32)
9964 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9965 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9966 Intrinsic::arm_neon_vcvtfp2fxu;
9967 SDValue FixConv = DAG.getNode(
9968 ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9969 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
9970 DAG.getConstant(C, dl, MVT::i32));
9972 if (IntBits < FloatBits)
9973 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9978 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9979 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9980 /// when the VDIV has a constant operand that is a power of 2.
9982 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9983 /// vcvt.f32.s32 d16, d16
9984 /// vdiv.f32 d16, d17, d16
9986 /// vcvt.f32.s32 d16, d16, #3
9987 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
9988 const ARMSubtarget *Subtarget) {
9989 if (!Subtarget->hasNEON())
9992 SDValue Op = N->getOperand(0);
9993 unsigned OpOpcode = Op.getNode()->getOpcode();
9994 if (!N->getValueType(0).isVector() ||
9995 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9998 SDValue ConstVec = N->getOperand(1);
9999 if (!isa<BuildVectorSDNode>(ConstVec))
10002 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10003 uint32_t FloatBits = FloatTy.getSizeInBits();
10004 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10005 uint32_t IntBits = IntTy.getSizeInBits();
10006 unsigned NumLanes = Op.getValueType().getVectorNumElements();
10007 if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10008 // These instructions only exist converting from i32 to f32. We can handle
10009 // smaller integers by generating an extra extend, but larger ones would
10010 // be lossy. We also can't handle more then 4 lanes, since these intructions
10011 // only support v2i32/v4i32 types.
10015 BitVector UndefElements;
10016 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10017 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10018 if (C == -1 || C == 0 || C > 32)
10022 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10023 SDValue ConvInput = Op.getOperand(0);
10024 if (IntBits < FloatBits)
10025 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10026 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10029 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10030 Intrinsic::arm_neon_vcvtfxu2fp;
10031 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10033 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10034 ConvInput, DAG.getConstant(C, dl, MVT::i32));
10037 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10038 /// operand of a vector shift operation, where all the elements of the
10039 /// build_vector must have the same constant integer value.
10040 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10041 // Ignore bit_converts.
10042 while (Op.getOpcode() == ISD::BITCAST)
10043 Op = Op.getOperand(0);
10044 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10045 APInt SplatBits, SplatUndef;
10046 unsigned SplatBitSize;
10048 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10049 HasAnyUndefs, ElementBits) ||
10050 SplatBitSize > ElementBits)
10052 Cnt = SplatBits.getSExtValue();
10056 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10057 /// operand of a vector shift left operation. That value must be in the range:
10058 /// 0 <= Value < ElementBits for a left shift; or
10059 /// 0 <= Value <= ElementBits for a long left shift.
10060 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10061 assert(VT.isVector() && "vector shift count is not a vector type");
10062 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10063 if (! getVShiftImm(Op, ElementBits, Cnt))
10065 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10068 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10069 /// operand of a vector shift right operation. For a shift opcode, the value
10070 /// is positive, but for an intrinsic the value count must be negative. The
10071 /// absolute value must be in the range:
10072 /// 1 <= |Value| <= ElementBits for a right shift; or
10073 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
10074 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10076 assert(VT.isVector() && "vector shift count is not a vector type");
10077 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10078 if (! getVShiftImm(Op, ElementBits, Cnt))
10081 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10082 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10089 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10090 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10091 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10094 // Don't do anything for most intrinsics.
10097 case Intrinsic::arm_neon_vabds:
10098 if (!N->getValueType(0).isInteger())
10100 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
10101 N->getOperand(1), N->getOperand(2));
10102 case Intrinsic::arm_neon_vabdu:
10103 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
10104 N->getOperand(1), N->getOperand(2));
10106 // Vector shifts: check for immediate versions and lower them.
10107 // Note: This is done during DAG combining instead of DAG legalizing because
10108 // the build_vectors for 64-bit vector element shift counts are generally
10109 // not legal, and it is hard to see their values after they get legalized to
10110 // loads from a constant pool.
10111 case Intrinsic::arm_neon_vshifts:
10112 case Intrinsic::arm_neon_vshiftu:
10113 case Intrinsic::arm_neon_vrshifts:
10114 case Intrinsic::arm_neon_vrshiftu:
10115 case Intrinsic::arm_neon_vrshiftn:
10116 case Intrinsic::arm_neon_vqshifts:
10117 case Intrinsic::arm_neon_vqshiftu:
10118 case Intrinsic::arm_neon_vqshiftsu:
10119 case Intrinsic::arm_neon_vqshiftns:
10120 case Intrinsic::arm_neon_vqshiftnu:
10121 case Intrinsic::arm_neon_vqshiftnsu:
10122 case Intrinsic::arm_neon_vqrshiftns:
10123 case Intrinsic::arm_neon_vqrshiftnu:
10124 case Intrinsic::arm_neon_vqrshiftnsu: {
10125 EVT VT = N->getOperand(1).getValueType();
10127 unsigned VShiftOpc = 0;
10130 case Intrinsic::arm_neon_vshifts:
10131 case Intrinsic::arm_neon_vshiftu:
10132 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10133 VShiftOpc = ARMISD::VSHL;
10136 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10137 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10138 ARMISD::VSHRs : ARMISD::VSHRu);
10143 case Intrinsic::arm_neon_vrshifts:
10144 case Intrinsic::arm_neon_vrshiftu:
10145 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10149 case Intrinsic::arm_neon_vqshifts:
10150 case Intrinsic::arm_neon_vqshiftu:
10151 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10155 case Intrinsic::arm_neon_vqshiftsu:
10156 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10158 llvm_unreachable("invalid shift count for vqshlu intrinsic");
10160 case Intrinsic::arm_neon_vrshiftn:
10161 case Intrinsic::arm_neon_vqshiftns:
10162 case Intrinsic::arm_neon_vqshiftnu:
10163 case Intrinsic::arm_neon_vqshiftnsu:
10164 case Intrinsic::arm_neon_vqrshiftns:
10165 case Intrinsic::arm_neon_vqrshiftnu:
10166 case Intrinsic::arm_neon_vqrshiftnsu:
10167 // Narrowing shifts require an immediate right shift.
10168 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10170 llvm_unreachable("invalid shift count for narrowing vector shift "
10174 llvm_unreachable("unhandled vector shift");
10178 case Intrinsic::arm_neon_vshifts:
10179 case Intrinsic::arm_neon_vshiftu:
10180 // Opcode already set above.
10182 case Intrinsic::arm_neon_vrshifts:
10183 VShiftOpc = ARMISD::VRSHRs; break;
10184 case Intrinsic::arm_neon_vrshiftu:
10185 VShiftOpc = ARMISD::VRSHRu; break;
10186 case Intrinsic::arm_neon_vrshiftn:
10187 VShiftOpc = ARMISD::VRSHRN; break;
10188 case Intrinsic::arm_neon_vqshifts:
10189 VShiftOpc = ARMISD::VQSHLs; break;
10190 case Intrinsic::arm_neon_vqshiftu:
10191 VShiftOpc = ARMISD::VQSHLu; break;
10192 case Intrinsic::arm_neon_vqshiftsu:
10193 VShiftOpc = ARMISD::VQSHLsu; break;
10194 case Intrinsic::arm_neon_vqshiftns:
10195 VShiftOpc = ARMISD::VQSHRNs; break;
10196 case Intrinsic::arm_neon_vqshiftnu:
10197 VShiftOpc = ARMISD::VQSHRNu; break;
10198 case Intrinsic::arm_neon_vqshiftnsu:
10199 VShiftOpc = ARMISD::VQSHRNsu; break;
10200 case Intrinsic::arm_neon_vqrshiftns:
10201 VShiftOpc = ARMISD::VQRSHRNs; break;
10202 case Intrinsic::arm_neon_vqrshiftnu:
10203 VShiftOpc = ARMISD::VQRSHRNu; break;
10204 case Intrinsic::arm_neon_vqrshiftnsu:
10205 VShiftOpc = ARMISD::VQRSHRNsu; break;
10209 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10210 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10213 case Intrinsic::arm_neon_vshiftins: {
10214 EVT VT = N->getOperand(1).getValueType();
10216 unsigned VShiftOpc = 0;
10218 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10219 VShiftOpc = ARMISD::VSLI;
10220 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10221 VShiftOpc = ARMISD::VSRI;
10223 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10227 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10228 N->getOperand(1), N->getOperand(2),
10229 DAG.getConstant(Cnt, dl, MVT::i32));
10232 case Intrinsic::arm_neon_vqrshifts:
10233 case Intrinsic::arm_neon_vqrshiftu:
10234 // No immediate versions of these to check for.
10241 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10242 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10243 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10244 /// vector element shift counts are generally not legal, and it is hard to see
10245 /// their values after they get legalized to loads from a constant pool.
10246 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10247 const ARMSubtarget *ST) {
10248 EVT VT = N->getValueType(0);
10249 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10250 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10251 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10252 SDValue N1 = N->getOperand(1);
10253 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10254 SDValue N0 = N->getOperand(0);
10255 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10256 DAG.MaskedValueIsZero(N0.getOperand(0),
10257 APInt::getHighBitsSet(32, 16)))
10258 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10262 // Nothing to be done for scalar shifts.
10263 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10264 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10267 assert(ST->hasNEON() && "unexpected vector shift");
10270 switch (N->getOpcode()) {
10271 default: llvm_unreachable("unexpected shift opcode");
10274 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10276 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10277 DAG.getConstant(Cnt, dl, MVT::i32));
10283 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10284 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10285 ARMISD::VSHRs : ARMISD::VSHRu);
10287 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10288 DAG.getConstant(Cnt, dl, MVT::i32));
10294 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10295 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10296 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10297 const ARMSubtarget *ST) {
10298 SDValue N0 = N->getOperand(0);
10300 // Check for sign- and zero-extensions of vector extract operations of 8-
10301 // and 16-bit vector elements. NEON supports these directly. They are
10302 // handled during DAG combining because type legalization will promote them
10303 // to 32-bit types and it is messy to recognize the operations after that.
10304 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10305 SDValue Vec = N0.getOperand(0);
10306 SDValue Lane = N0.getOperand(1);
10307 EVT VT = N->getValueType(0);
10308 EVT EltVT = N0.getValueType();
10309 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10311 if (VT == MVT::i32 &&
10312 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10313 TLI.isTypeLegal(Vec.getValueType()) &&
10314 isa<ConstantSDNode>(Lane)) {
10317 switch (N->getOpcode()) {
10318 default: llvm_unreachable("unexpected opcode");
10319 case ISD::SIGN_EXTEND:
10320 Opc = ARMISD::VGETLANEs;
10322 case ISD::ZERO_EXTEND:
10323 case ISD::ANY_EXTEND:
10324 Opc = ARMISD::VGETLANEu;
10327 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10334 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10336 if (Op.getOpcode() == ARMISD::BFI) {
10337 // Conservatively, we can recurse down the first operand
10338 // and just mask out all affected bits.
10339 computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10341 // The operand to BFI is already a mask suitable for removing the bits it
10343 ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10344 APInt Mask = CI->getAPIntValue();
10349 if (Op.getOpcode() == ARMISD::CMOV) {
10350 APInt KZ2(KnownZero.getBitWidth(), 0);
10351 APInt KO2(KnownOne.getBitWidth(), 0);
10352 computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10353 computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10359 return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10362 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10363 // If we have a CMOV, OR and AND combination such as:
10368 // * CN is a single bit;
10369 // * All bits covered by CM are known zero in y
10371 // Then we can convert this into a sequence of BFI instructions. This will
10372 // always be a win if CM is a single bit, will always be no worse than the
10373 // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10374 // three bits (due to the extra IT instruction).
10376 SDValue Op0 = CMOV->getOperand(0);
10377 SDValue Op1 = CMOV->getOperand(1);
10378 auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
10379 auto CC = CCNode->getAPIntValue().getLimitedValue();
10380 SDValue CmpZ = CMOV->getOperand(4);
10382 // The compare must be against zero.
10383 if (!isNullConstant(CmpZ->getOperand(1)))
10386 assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10387 SDValue And = CmpZ->getOperand(0);
10388 if (And->getOpcode() != ISD::AND)
10390 ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10391 if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10393 SDValue X = And->getOperand(0);
10395 if (CC == ARMCC::EQ) {
10396 // We're performing an "equal to zero" compare. Swap the operands so we
10397 // canonicalize on a "not equal to zero" compare.
10398 std::swap(Op0, Op1);
10400 assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
10403 if (Op1->getOpcode() != ISD::OR)
10406 ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
10409 SDValue Y = Op1->getOperand(0);
10414 // Now, is it profitable to continue?
10415 APInt OrCI = OrC->getAPIntValue();
10416 unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10417 if (OrCI.countPopulation() > Heuristic)
10420 // Lastly, can we determine that the bits defined by OrCI
10422 APInt KnownZero, KnownOne;
10423 computeKnownBits(DAG, Y, KnownZero, KnownOne);
10424 if ((OrCI & KnownZero) != OrCI)
10427 // OK, we can do the combine.
10430 EVT VT = X.getValueType();
10431 unsigned BitInX = AndC->getAPIntValue().logBase2();
10434 // We must shift X first.
10435 X = DAG.getNode(ISD::SRL, dl, VT, X,
10436 DAG.getConstant(BitInX, dl, VT));
10439 for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10440 BitInY < NumActiveBits; ++BitInY) {
10441 if (OrCI[BitInY] == 0)
10443 APInt Mask(VT.getSizeInBits(), 0);
10444 Mask.setBit(BitInY);
10445 V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10446 // Confusingly, the operand is an *inverted* mask.
10447 DAG.getConstant(~Mask, dl, VT));
10453 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10455 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10456 SDValue Cmp = N->getOperand(4);
10457 if (Cmp.getOpcode() != ARMISD::CMPZ)
10458 // Only looking at EQ and NE cases.
10461 EVT VT = N->getValueType(0);
10463 SDValue LHS = Cmp.getOperand(0);
10464 SDValue RHS = Cmp.getOperand(1);
10465 SDValue FalseVal = N->getOperand(0);
10466 SDValue TrueVal = N->getOperand(1);
10467 SDValue ARMcc = N->getOperand(2);
10468 ARMCC::CondCodes CC =
10469 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10471 // BFI is only available on V6T2+.
10472 if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10473 SDValue R = PerformCMOVToBFICombine(N, DAG);
10494 /// FIXME: Turn this into a target neutral optimization?
10496 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10497 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10498 N->getOperand(3), Cmp);
10499 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10501 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10502 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10503 N->getOperand(3), NewCmp);
10506 if (Res.getNode()) {
10507 APInt KnownZero, KnownOne;
10508 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10509 // Capture demanded bits information that would be otherwise lost.
10510 if (KnownZero == 0xfffffffe)
10511 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10512 DAG.getValueType(MVT::i1));
10513 else if (KnownZero == 0xffffff00)
10514 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10515 DAG.getValueType(MVT::i8));
10516 else if (KnownZero == 0xffff0000)
10517 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10518 DAG.getValueType(MVT::i16));
10524 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10525 DAGCombinerInfo &DCI) const {
10526 switch (N->getOpcode()) {
10528 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10529 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10530 case ISD::SUB: return PerformSUBCombine(N, DCI);
10531 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10532 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10533 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10534 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10535 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10536 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10537 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10538 case ISD::STORE: return PerformSTORECombine(N, DCI);
10539 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10540 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10541 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10542 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10543 case ISD::FP_TO_SINT:
10544 case ISD::FP_TO_UINT:
10545 return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10547 return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10548 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10551 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10552 case ISD::SIGN_EXTEND:
10553 case ISD::ZERO_EXTEND:
10554 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10555 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10556 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10557 case ARMISD::VLD2DUP:
10558 case ARMISD::VLD3DUP:
10559 case ARMISD::VLD4DUP:
10560 return PerformVLDCombine(N, DCI);
10561 case ARMISD::BUILD_VECTOR:
10562 return PerformARMBUILD_VECTORCombine(N, DCI);
10563 case ISD::INTRINSIC_VOID:
10564 case ISD::INTRINSIC_W_CHAIN:
10565 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10566 case Intrinsic::arm_neon_vld1:
10567 case Intrinsic::arm_neon_vld2:
10568 case Intrinsic::arm_neon_vld3:
10569 case Intrinsic::arm_neon_vld4:
10570 case Intrinsic::arm_neon_vld2lane:
10571 case Intrinsic::arm_neon_vld3lane:
10572 case Intrinsic::arm_neon_vld4lane:
10573 case Intrinsic::arm_neon_vst1:
10574 case Intrinsic::arm_neon_vst2:
10575 case Intrinsic::arm_neon_vst3:
10576 case Intrinsic::arm_neon_vst4:
10577 case Intrinsic::arm_neon_vst2lane:
10578 case Intrinsic::arm_neon_vst3lane:
10579 case Intrinsic::arm_neon_vst4lane:
10580 return PerformVLDCombine(N, DCI);
10588 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10590 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10593 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10596 bool *Fast) const {
10597 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10598 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10600 switch (VT.getSimpleVT().SimpleTy) {
10606 // Unaligned access can use (for example) LRDB, LRDH, LDR
10607 if (AllowsUnaligned) {
10609 *Fast = Subtarget->hasV7Ops();
10616 // For any little-endian targets with neon, we can support unaligned ld/st
10617 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10618 // A big-endian target may also explicitly support unaligned accesses
10619 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10629 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10630 unsigned AlignCheck) {
10631 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10632 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10635 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10636 unsigned DstAlign, unsigned SrcAlign,
10637 bool IsMemset, bool ZeroMemset,
10639 MachineFunction &MF) const {
10640 const Function *F = MF.getFunction();
10642 // See if we can use NEON instructions for this...
10643 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10644 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10647 (memOpAlign(SrcAlign, DstAlign, 16) ||
10648 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10650 } else if (Size >= 8 &&
10651 (memOpAlign(SrcAlign, DstAlign, 8) ||
10652 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10658 // Lowering to i32/i16 if the size permits.
10661 else if (Size >= 2)
10664 // Let the target-independent logic figure it out.
10668 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10669 if (Val.getOpcode() != ISD::LOAD)
10672 EVT VT1 = Val.getValueType();
10673 if (!VT1.isSimple() || !VT1.isInteger() ||
10674 !VT2.isSimple() || !VT2.isInteger())
10677 switch (VT1.getSimpleVT().SimpleTy) {
10682 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10689 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10690 EVT VT = ExtVal.getValueType();
10692 if (!isTypeLegal(VT))
10695 // Don't create a loadext if we can fold the extension into a wide/long
10697 // If there's more than one user instruction, the loadext is desirable no
10698 // matter what. There can be two uses by the same instruction.
10699 if (ExtVal->use_empty() ||
10700 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10703 SDNode *U = *ExtVal->use_begin();
10704 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10705 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10711 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10712 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10715 if (!isTypeLegal(EVT::getEVT(Ty1)))
10718 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10720 // Assuming the caller doesn't have a zeroext or signext return parameter,
10721 // truncation all the way down to i1 is valid.
10726 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10730 unsigned Scale = 1;
10731 switch (VT.getSimpleVT().SimpleTy) {
10732 default: return false;
10747 if ((V & (Scale - 1)) != 0)
10750 return V == (V & ((1LL << 5) - 1));
10753 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10754 const ARMSubtarget *Subtarget) {
10755 bool isNeg = false;
10761 switch (VT.getSimpleVT().SimpleTy) {
10762 default: return false;
10767 // + imm12 or - imm8
10769 return V == (V & ((1LL << 8) - 1));
10770 return V == (V & ((1LL << 12) - 1));
10773 // Same as ARM mode. FIXME: NEON?
10774 if (!Subtarget->hasVFP2())
10779 return V == (V & ((1LL << 8) - 1));
10783 /// isLegalAddressImmediate - Return true if the integer value can be used
10784 /// as the offset of the target addressing mode for load / store of the
10786 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10787 const ARMSubtarget *Subtarget) {
10791 if (!VT.isSimple())
10794 if (Subtarget->isThumb1Only())
10795 return isLegalT1AddressImmediate(V, VT);
10796 else if (Subtarget->isThumb2())
10797 return isLegalT2AddressImmediate(V, VT, Subtarget);
10802 switch (VT.getSimpleVT().SimpleTy) {
10803 default: return false;
10808 return V == (V & ((1LL << 12) - 1));
10811 return V == (V & ((1LL << 8) - 1));
10814 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10819 return V == (V & ((1LL << 8) - 1));
10823 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10825 int Scale = AM.Scale;
10829 switch (VT.getSimpleVT().SimpleTy) {
10830 default: return false;
10838 Scale = Scale & ~1;
10839 return Scale == 2 || Scale == 4 || Scale == 8;
10842 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10846 // Note, we allow "void" uses (basically, uses that aren't loads or
10847 // stores), because arm allows folding a scale into many arithmetic
10848 // operations. This should be made more precise and revisited later.
10850 // Allow r << imm, but the imm has to be a multiple of two.
10851 if (Scale & 1) return false;
10852 return isPowerOf2_32(Scale);
10856 /// isLegalAddressingMode - Return true if the addressing mode represented
10857 /// by AM is legal for this target, for a load/store of the specified type.
10858 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10859 const AddrMode &AM, Type *Ty,
10860 unsigned AS) const {
10861 EVT VT = getValueType(DL, Ty, true);
10862 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10865 // Can never fold addr of global into load/store.
10869 switch (AM.Scale) {
10870 case 0: // no scale reg, must be "r+i" or "r", or "i".
10873 if (Subtarget->isThumb1Only())
10877 // ARM doesn't support any R+R*scale+imm addr modes.
10881 if (!VT.isSimple())
10884 if (Subtarget->isThumb2())
10885 return isLegalT2ScaledAddressingMode(AM, VT);
10887 int Scale = AM.Scale;
10888 switch (VT.getSimpleVT().SimpleTy) {
10889 default: return false;
10893 if (Scale < 0) Scale = -Scale;
10897 return isPowerOf2_32(Scale & ~1);
10901 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10906 // Note, we allow "void" uses (basically, uses that aren't loads or
10907 // stores), because arm allows folding a scale into many arithmetic
10908 // operations. This should be made more precise and revisited later.
10910 // Allow r << imm, but the imm has to be a multiple of two.
10911 if (Scale & 1) return false;
10912 return isPowerOf2_32(Scale);
10918 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10919 /// icmp immediate, that is the target has icmp instructions which can compare
10920 /// a register against the immediate without having to materialize the
10921 /// immediate into a register.
10922 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10923 // Thumb2 and ARM modes can use cmn for negative immediates.
10924 if (!Subtarget->isThumb())
10925 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10926 if (Subtarget->isThumb2())
10927 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10928 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10929 return Imm >= 0 && Imm <= 255;
10932 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10933 /// *or sub* immediate, that is the target has add or sub instructions which can
10934 /// add a register with the immediate without having to materialize the
10935 /// immediate into a register.
10936 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10937 // Same encoding for add/sub, just flip the sign.
10938 int64_t AbsImm = std::abs(Imm);
10939 if (!Subtarget->isThumb())
10940 return ARM_AM::getSOImmVal(AbsImm) != -1;
10941 if (Subtarget->isThumb2())
10942 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10943 // Thumb1 only has 8-bit unsigned immediate.
10944 return AbsImm >= 0 && AbsImm <= 255;
10947 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10948 bool isSEXTLoad, SDValue &Base,
10949 SDValue &Offset, bool &isInc,
10950 SelectionDAG &DAG) {
10951 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10954 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10955 // AddressingMode 3
10956 Base = Ptr->getOperand(0);
10957 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10958 int RHSC = (int)RHS->getZExtValue();
10959 if (RHSC < 0 && RHSC > -256) {
10960 assert(Ptr->getOpcode() == ISD::ADD);
10962 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10966 isInc = (Ptr->getOpcode() == ISD::ADD);
10967 Offset = Ptr->getOperand(1);
10969 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10970 // AddressingMode 2
10971 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10972 int RHSC = (int)RHS->getZExtValue();
10973 if (RHSC < 0 && RHSC > -0x1000) {
10974 assert(Ptr->getOpcode() == ISD::ADD);
10976 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10977 Base = Ptr->getOperand(0);
10982 if (Ptr->getOpcode() == ISD::ADD) {
10984 ARM_AM::ShiftOpc ShOpcVal=
10985 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10986 if (ShOpcVal != ARM_AM::no_shift) {
10987 Base = Ptr->getOperand(1);
10988 Offset = Ptr->getOperand(0);
10990 Base = Ptr->getOperand(0);
10991 Offset = Ptr->getOperand(1);
10996 isInc = (Ptr->getOpcode() == ISD::ADD);
10997 Base = Ptr->getOperand(0);
10998 Offset = Ptr->getOperand(1);
11002 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11006 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11007 bool isSEXTLoad, SDValue &Base,
11008 SDValue &Offset, bool &isInc,
11009 SelectionDAG &DAG) {
11010 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11013 Base = Ptr->getOperand(0);
11014 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11015 int RHSC = (int)RHS->getZExtValue();
11016 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11017 assert(Ptr->getOpcode() == ISD::ADD);
11019 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11021 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11022 isInc = Ptr->getOpcode() == ISD::ADD;
11023 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11031 /// getPreIndexedAddressParts - returns true by value, base pointer and
11032 /// offset pointer and addressing mode by reference if the node's address
11033 /// can be legally represented as pre-indexed load / store address.
11035 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11037 ISD::MemIndexedMode &AM,
11038 SelectionDAG &DAG) const {
11039 if (Subtarget->isThumb1Only())
11044 bool isSEXTLoad = false;
11045 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11046 Ptr = LD->getBasePtr();
11047 VT = LD->getMemoryVT();
11048 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11049 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11050 Ptr = ST->getBasePtr();
11051 VT = ST->getMemoryVT();
11056 bool isLegal = false;
11057 if (Subtarget->isThumb2())
11058 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11059 Offset, isInc, DAG);
11061 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11062 Offset, isInc, DAG);
11066 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11070 /// getPostIndexedAddressParts - returns true by value, base pointer and
11071 /// offset pointer and addressing mode by reference if this node can be
11072 /// combined with a load / store to form a post-indexed load / store.
11073 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11076 ISD::MemIndexedMode &AM,
11077 SelectionDAG &DAG) const {
11078 if (Subtarget->isThumb1Only())
11083 bool isSEXTLoad = false;
11084 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11085 VT = LD->getMemoryVT();
11086 Ptr = LD->getBasePtr();
11087 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11088 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11089 VT = ST->getMemoryVT();
11090 Ptr = ST->getBasePtr();
11095 bool isLegal = false;
11096 if (Subtarget->isThumb2())
11097 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11100 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11106 // Swap base ptr and offset to catch more post-index load / store when
11107 // it's legal. In Thumb2 mode, offset must be an immediate.
11108 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11109 !Subtarget->isThumb2())
11110 std::swap(Base, Offset);
11112 // Post-indexed load / store update the base pointer.
11117 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11121 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11124 const SelectionDAG &DAG,
11125 unsigned Depth) const {
11126 unsigned BitWidth = KnownOne.getBitWidth();
11127 KnownZero = KnownOne = APInt(BitWidth, 0);
11128 switch (Op.getOpcode()) {
11134 // These nodes' second result is a boolean
11135 if (Op.getResNo() == 0)
11137 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11139 case ARMISD::CMOV: {
11140 // Bits are known zero/one if known on the LHS and RHS.
11141 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11142 if (KnownZero == 0 && KnownOne == 0) return;
11144 APInt KnownZeroRHS, KnownOneRHS;
11145 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11146 KnownZero &= KnownZeroRHS;
11147 KnownOne &= KnownOneRHS;
11150 case ISD::INTRINSIC_W_CHAIN: {
11151 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11152 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11155 case Intrinsic::arm_ldaex:
11156 case Intrinsic::arm_ldrex: {
11157 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11158 unsigned MemBits = VT.getScalarType().getSizeInBits();
11159 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11167 //===----------------------------------------------------------------------===//
11168 // ARM Inline Assembly Support
11169 //===----------------------------------------------------------------------===//
11171 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11172 // Looking for "rev" which is V6+.
11173 if (!Subtarget->hasV6Ops())
11176 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11177 std::string AsmStr = IA->getAsmString();
11178 SmallVector<StringRef, 4> AsmPieces;
11179 SplitString(AsmStr, AsmPieces, ";\n");
11181 switch (AsmPieces.size()) {
11182 default: return false;
11184 AsmStr = AsmPieces[0];
11186 SplitString(AsmStr, AsmPieces, " \t,");
11189 if (AsmPieces.size() == 3 &&
11190 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11191 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11192 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11193 if (Ty && Ty->getBitWidth() == 32)
11194 return IntrinsicLowering::LowerToByteSwap(CI);
11202 /// getConstraintType - Given a constraint letter, return the type of
11203 /// constraint it is for this target.
11204 ARMTargetLowering::ConstraintType
11205 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11206 if (Constraint.size() == 1) {
11207 switch (Constraint[0]) {
11209 case 'l': return C_RegisterClass;
11210 case 'w': return C_RegisterClass;
11211 case 'h': return C_RegisterClass;
11212 case 'x': return C_RegisterClass;
11213 case 't': return C_RegisterClass;
11214 case 'j': return C_Other; // Constant for movw.
11215 // An address with a single base register. Due to the way we
11216 // currently handle addresses it is the same as an 'r' memory constraint.
11217 case 'Q': return C_Memory;
11219 } else if (Constraint.size() == 2) {
11220 switch (Constraint[0]) {
11222 // All 'U+' constraints are addresses.
11223 case 'U': return C_Memory;
11226 return TargetLowering::getConstraintType(Constraint);
11229 /// Examine constraint type and operand type and determine a weight value.
11230 /// This object must already have been set up with the operand type
11231 /// and the current alternative constraint selected.
11232 TargetLowering::ConstraintWeight
11233 ARMTargetLowering::getSingleConstraintMatchWeight(
11234 AsmOperandInfo &info, const char *constraint) const {
11235 ConstraintWeight weight = CW_Invalid;
11236 Value *CallOperandVal = info.CallOperandVal;
11237 // If we don't have a value, we can't do a match,
11238 // but allow it at the lowest weight.
11239 if (!CallOperandVal)
11241 Type *type = CallOperandVal->getType();
11242 // Look at the constraint type.
11243 switch (*constraint) {
11245 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11248 if (type->isIntegerTy()) {
11249 if (Subtarget->isThumb())
11250 weight = CW_SpecificReg;
11252 weight = CW_Register;
11256 if (type->isFloatingPointTy())
11257 weight = CW_Register;
11263 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11264 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11265 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11266 if (Constraint.size() == 1) {
11267 // GCC ARM Constraint Letters
11268 switch (Constraint[0]) {
11269 case 'l': // Low regs or general regs.
11270 if (Subtarget->isThumb())
11271 return RCPair(0U, &ARM::tGPRRegClass);
11272 return RCPair(0U, &ARM::GPRRegClass);
11273 case 'h': // High regs or no regs.
11274 if (Subtarget->isThumb())
11275 return RCPair(0U, &ARM::hGPRRegClass);
11278 if (Subtarget->isThumb1Only())
11279 return RCPair(0U, &ARM::tGPRRegClass);
11280 return RCPair(0U, &ARM::GPRRegClass);
11282 if (VT == MVT::Other)
11284 if (VT == MVT::f32)
11285 return RCPair(0U, &ARM::SPRRegClass);
11286 if (VT.getSizeInBits() == 64)
11287 return RCPair(0U, &ARM::DPRRegClass);
11288 if (VT.getSizeInBits() == 128)
11289 return RCPair(0U, &ARM::QPRRegClass);
11292 if (VT == MVT::Other)
11294 if (VT == MVT::f32)
11295 return RCPair(0U, &ARM::SPR_8RegClass);
11296 if (VT.getSizeInBits() == 64)
11297 return RCPair(0U, &ARM::DPR_8RegClass);
11298 if (VT.getSizeInBits() == 128)
11299 return RCPair(0U, &ARM::QPR_8RegClass);
11302 if (VT == MVT::f32)
11303 return RCPair(0U, &ARM::SPRRegClass);
11307 if (StringRef("{cc}").equals_lower(Constraint))
11308 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11310 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11313 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11314 /// vector. If it is invalid, don't add anything to Ops.
11315 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11316 std::string &Constraint,
11317 std::vector<SDValue>&Ops,
11318 SelectionDAG &DAG) const {
11321 // Currently only support length 1 constraints.
11322 if (Constraint.length() != 1) return;
11324 char ConstraintLetter = Constraint[0];
11325 switch (ConstraintLetter) {
11328 case 'I': case 'J': case 'K': case 'L':
11329 case 'M': case 'N': case 'O':
11330 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11334 int64_t CVal64 = C->getSExtValue();
11335 int CVal = (int) CVal64;
11336 // None of these constraints allow values larger than 32 bits. Check
11337 // that the value fits in an int.
11338 if (CVal != CVal64)
11341 switch (ConstraintLetter) {
11343 // Constant suitable for movw, must be between 0 and
11345 if (Subtarget->hasV6T2Ops())
11346 if (CVal >= 0 && CVal <= 65535)
11350 if (Subtarget->isThumb1Only()) {
11351 // This must be a constant between 0 and 255, for ADD
11353 if (CVal >= 0 && CVal <= 255)
11355 } else if (Subtarget->isThumb2()) {
11356 // A constant that can be used as an immediate value in a
11357 // data-processing instruction.
11358 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11361 // A constant that can be used as an immediate value in a
11362 // data-processing instruction.
11363 if (ARM_AM::getSOImmVal(CVal) != -1)
11369 if (Subtarget->isThumb()) { // FIXME thumb2
11370 // This must be a constant between -255 and -1, for negated ADD
11371 // immediates. This can be used in GCC with an "n" modifier that
11372 // prints the negated value, for use with SUB instructions. It is
11373 // not useful otherwise but is implemented for compatibility.
11374 if (CVal >= -255 && CVal <= -1)
11377 // This must be a constant between -4095 and 4095. It is not clear
11378 // what this constraint is intended for. Implemented for
11379 // compatibility with GCC.
11380 if (CVal >= -4095 && CVal <= 4095)
11386 if (Subtarget->isThumb1Only()) {
11387 // A 32-bit value where only one byte has a nonzero value. Exclude
11388 // zero to match GCC. This constraint is used by GCC internally for
11389 // constants that can be loaded with a move/shift combination.
11390 // It is not useful otherwise but is implemented for compatibility.
11391 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11393 } else if (Subtarget->isThumb2()) {
11394 // A constant whose bitwise inverse can be used as an immediate
11395 // value in a data-processing instruction. This can be used in GCC
11396 // with a "B" modifier that prints the inverted value, for use with
11397 // BIC and MVN instructions. It is not useful otherwise but is
11398 // implemented for compatibility.
11399 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11402 // A constant whose bitwise inverse can be used as an immediate
11403 // value in a data-processing instruction. This can be used in GCC
11404 // with a "B" modifier that prints the inverted value, for use with
11405 // BIC and MVN instructions. It is not useful otherwise but is
11406 // implemented for compatibility.
11407 if (ARM_AM::getSOImmVal(~CVal) != -1)
11413 if (Subtarget->isThumb1Only()) {
11414 // This must be a constant between -7 and 7,
11415 // for 3-operand ADD/SUB immediate instructions.
11416 if (CVal >= -7 && CVal < 7)
11418 } else if (Subtarget->isThumb2()) {
11419 // A constant whose negation can be used as an immediate value in a
11420 // data-processing instruction. This can be used in GCC with an "n"
11421 // modifier that prints the negated value, for use with SUB
11422 // instructions. It is not useful otherwise but is implemented for
11424 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11427 // A constant whose negation can be used as an immediate value in a
11428 // data-processing instruction. This can be used in GCC with an "n"
11429 // modifier that prints the negated value, for use with SUB
11430 // instructions. It is not useful otherwise but is implemented for
11432 if (ARM_AM::getSOImmVal(-CVal) != -1)
11438 if (Subtarget->isThumb()) { // FIXME thumb2
11439 // This must be a multiple of 4 between 0 and 1020, for
11440 // ADD sp + immediate.
11441 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11444 // A power of two or a constant between 0 and 32. This is used in
11445 // GCC for the shift amount on shifted register operands, but it is
11446 // useful in general for any shift amounts.
11447 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11453 if (Subtarget->isThumb()) { // FIXME thumb2
11454 // This must be a constant between 0 and 31, for shift amounts.
11455 if (CVal >= 0 && CVal <= 31)
11461 if (Subtarget->isThumb()) { // FIXME thumb2
11462 // This must be a multiple of 4 between -508 and 508, for
11463 // ADD/SUB sp = sp + immediate.
11464 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11469 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11473 if (Result.getNode()) {
11474 Ops.push_back(Result);
11477 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11480 static RTLIB::Libcall getDivRemLibcall(
11481 const SDNode *N, MVT::SimpleValueType SVT) {
11482 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11483 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11484 "Unhandled Opcode in getDivRemLibcall");
11485 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11486 N->getOpcode() == ISD::SREM;
11489 default: llvm_unreachable("Unexpected request for libcall!");
11490 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11491 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11492 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11493 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11498 static TargetLowering::ArgListTy getDivRemArgList(
11499 const SDNode *N, LLVMContext *Context) {
11500 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11501 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11502 "Unhandled Opcode in getDivRemArgList");
11503 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11504 N->getOpcode() == ISD::SREM;
11505 TargetLowering::ArgListTy Args;
11506 TargetLowering::ArgListEntry Entry;
11507 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11508 EVT ArgVT = N->getOperand(i).getValueType();
11509 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11510 Entry.Node = N->getOperand(i);
11512 Entry.isSExt = isSigned;
11513 Entry.isZExt = !isSigned;
11514 Args.push_back(Entry);
11519 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11520 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11521 "Register-based DivRem lowering only");
11522 unsigned Opcode = Op->getOpcode();
11523 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11524 "Invalid opcode for Div/Rem lowering");
11525 bool isSigned = (Opcode == ISD::SDIVREM);
11526 EVT VT = Op->getValueType(0);
11527 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11529 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11530 VT.getSimpleVT().SimpleTy);
11531 SDValue InChain = DAG.getEntryNode();
11533 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11536 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11537 getPointerTy(DAG.getDataLayout()));
11539 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11542 TargetLowering::CallLoweringInfo CLI(DAG);
11543 CLI.setDebugLoc(dl).setChain(InChain)
11544 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11545 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11547 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11548 return CallInfo.first;
11551 // Lowers REM using divmod helpers
11552 // see RTABI section 4.2/4.3
11553 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11554 // Build return types (div and rem)
11555 std::vector<Type*> RetTyParams;
11556 Type *RetTyElement;
11558 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11559 default: llvm_unreachable("Unexpected request for libcall!");
11560 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
11561 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11562 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11563 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11566 RetTyParams.push_back(RetTyElement);
11567 RetTyParams.push_back(RetTyElement);
11568 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11569 Type *RetTy = StructType::get(*DAG.getContext(), ret);
11571 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11573 SDValue InChain = DAG.getEntryNode();
11574 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11575 bool isSigned = N->getOpcode() == ISD::SREM;
11576 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11577 getPointerTy(DAG.getDataLayout()));
11580 CallLoweringInfo CLI(DAG);
11581 CLI.setChain(InChain)
11582 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11583 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11584 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11586 // Return second (rem) result operand (first contains div)
11587 SDNode *ResNode = CallResult.first.getNode();
11588 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11589 return ResNode->getOperand(1);
11593 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11594 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11598 SDValue Chain = Op.getOperand(0);
11599 SDValue Size = Op.getOperand(1);
11601 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11602 DAG.getConstant(2, DL, MVT::i32));
11605 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11606 Flag = Chain.getValue(1);
11608 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11609 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11611 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11612 Chain = NewSP.getValue(1);
11614 SDValue Ops[2] = { NewSP, Chain };
11615 return DAG.getMergeValues(Ops, DL);
11618 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11619 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11620 "Unexpected type for custom-lowering FP_EXTEND");
11623 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11625 SDValue SrcVal = Op.getOperand(0);
11626 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11630 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11631 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11632 Subtarget->isFPOnlySP() &&
11633 "Unexpected type for custom-lowering FP_ROUND");
11636 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11638 SDValue SrcVal = Op.getOperand(0);
11639 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11644 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11645 // The ARM target isn't yet aware of offsets.
11649 bool ARM::isBitFieldInvertedMask(unsigned v) {
11650 if (v == 0xffffffff)
11653 // there can be 1's on either or both "outsides", all the "inside"
11654 // bits must be 0's
11655 return isShiftedMask_32(~v);
11658 /// isFPImmLegal - Returns true if the target can instruction select the
11659 /// specified FP immediate natively. If false, the legalizer will
11660 /// materialize the FP immediate as a load from a constant pool.
11661 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11662 if (!Subtarget->hasVFP3())
11664 if (VT == MVT::f32)
11665 return ARM_AM::getFP32Imm(Imm) != -1;
11666 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11667 return ARM_AM::getFP64Imm(Imm) != -1;
11671 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11672 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11673 /// specified in the intrinsic calls.
11674 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11676 unsigned Intrinsic) const {
11677 switch (Intrinsic) {
11678 case Intrinsic::arm_neon_vld1:
11679 case Intrinsic::arm_neon_vld2:
11680 case Intrinsic::arm_neon_vld3:
11681 case Intrinsic::arm_neon_vld4:
11682 case Intrinsic::arm_neon_vld2lane:
11683 case Intrinsic::arm_neon_vld3lane:
11684 case Intrinsic::arm_neon_vld4lane: {
11685 Info.opc = ISD::INTRINSIC_W_CHAIN;
11686 // Conservatively set memVT to the entire set of vectors loaded.
11687 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11688 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11689 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11690 Info.ptrVal = I.getArgOperand(0);
11692 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11693 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11694 Info.vol = false; // volatile loads with NEON intrinsics not supported
11695 Info.readMem = true;
11696 Info.writeMem = false;
11699 case Intrinsic::arm_neon_vst1:
11700 case Intrinsic::arm_neon_vst2:
11701 case Intrinsic::arm_neon_vst3:
11702 case Intrinsic::arm_neon_vst4:
11703 case Intrinsic::arm_neon_vst2lane:
11704 case Intrinsic::arm_neon_vst3lane:
11705 case Intrinsic::arm_neon_vst4lane: {
11706 Info.opc = ISD::INTRINSIC_VOID;
11707 // Conservatively set memVT to the entire set of vectors stored.
11708 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11709 unsigned NumElts = 0;
11710 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11711 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11712 if (!ArgTy->isVectorTy())
11714 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11716 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11717 Info.ptrVal = I.getArgOperand(0);
11719 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11720 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11721 Info.vol = false; // volatile stores with NEON intrinsics not supported
11722 Info.readMem = false;
11723 Info.writeMem = true;
11726 case Intrinsic::arm_ldaex:
11727 case Intrinsic::arm_ldrex: {
11728 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11729 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11730 Info.opc = ISD::INTRINSIC_W_CHAIN;
11731 Info.memVT = MVT::getVT(PtrTy->getElementType());
11732 Info.ptrVal = I.getArgOperand(0);
11734 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11736 Info.readMem = true;
11737 Info.writeMem = false;
11740 case Intrinsic::arm_stlex:
11741 case Intrinsic::arm_strex: {
11742 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11743 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11744 Info.opc = ISD::INTRINSIC_W_CHAIN;
11745 Info.memVT = MVT::getVT(PtrTy->getElementType());
11746 Info.ptrVal = I.getArgOperand(1);
11748 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11750 Info.readMem = false;
11751 Info.writeMem = true;
11754 case Intrinsic::arm_stlexd:
11755 case Intrinsic::arm_strexd: {
11756 Info.opc = ISD::INTRINSIC_W_CHAIN;
11757 Info.memVT = MVT::i64;
11758 Info.ptrVal = I.getArgOperand(2);
11762 Info.readMem = false;
11763 Info.writeMem = true;
11766 case Intrinsic::arm_ldaexd:
11767 case Intrinsic::arm_ldrexd: {
11768 Info.opc = ISD::INTRINSIC_W_CHAIN;
11769 Info.memVT = MVT::i64;
11770 Info.ptrVal = I.getArgOperand(0);
11774 Info.readMem = true;
11775 Info.writeMem = false;
11785 /// \brief Returns true if it is beneficial to convert a load of a constant
11786 /// to just the constant itself.
11787 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11789 assert(Ty->isIntegerTy());
11791 unsigned Bits = Ty->getPrimitiveSizeInBits();
11792 if (Bits == 0 || Bits > 32)
11797 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11798 ARM_MB::MemBOpt Domain) const {
11799 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11801 // First, if the target has no DMB, see what fallback we can use.
11802 if (!Subtarget->hasDataBarrier()) {
11803 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11804 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11806 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11807 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11808 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11809 Builder.getInt32(0), Builder.getInt32(7),
11810 Builder.getInt32(10), Builder.getInt32(5)};
11811 return Builder.CreateCall(MCR, args);
11813 // Instead of using barriers, atomic accesses on these subtargets use
11815 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11818 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11819 // Only a full system barrier exists in the M-class architectures.
11820 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11821 Constant *CDomain = Builder.getInt32(Domain);
11822 return Builder.CreateCall(DMB, CDomain);
11826 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11827 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11828 AtomicOrdering Ord, bool IsStore,
11829 bool IsLoad) const {
11830 if (!getInsertFencesForAtomic())
11836 llvm_unreachable("Invalid fence: unordered/non-atomic");
11839 return nullptr; // Nothing to do
11840 case SequentiallyConsistent:
11842 return nullptr; // Nothing to do
11845 case AcquireRelease:
11846 if (Subtarget->isSwift())
11847 return makeDMB(Builder, ARM_MB::ISHST);
11848 // FIXME: add a comment with a link to documentation justifying this.
11850 return makeDMB(Builder, ARM_MB::ISH);
11852 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11855 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11856 AtomicOrdering Ord, bool IsStore,
11857 bool IsLoad) const {
11858 if (!getInsertFencesForAtomic())
11864 llvm_unreachable("Invalid fence: unordered/not-atomic");
11867 return nullptr; // Nothing to do
11869 case AcquireRelease:
11870 case SequentiallyConsistent:
11871 return makeDMB(Builder, ARM_MB::ISH);
11873 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11876 // Loads and stores less than 64-bits are already atomic; ones above that
11877 // are doomed anyway, so defer to the default libcall and blame the OS when
11878 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11879 // anything for those.
11880 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11881 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11882 return (Size == 64) && !Subtarget->isMClass();
11885 // Loads and stores less than 64-bits are already atomic; ones above that
11886 // are doomed anyway, so defer to the default libcall and blame the OS when
11887 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11888 // anything for those.
11889 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11890 // guarantee, see DDI0406C ARM architecture reference manual,
11891 // sections A8.8.72-74 LDRD)
11892 TargetLowering::AtomicExpansionKind
11893 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11894 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11895 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11896 : AtomicExpansionKind::None;
11899 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11900 // and up to 64 bits on the non-M profiles
11901 TargetLowering::AtomicExpansionKind
11902 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11903 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11904 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11905 ? AtomicExpansionKind::LLSC
11906 : AtomicExpansionKind::None;
11909 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11910 AtomicCmpXchgInst *AI) const {
11914 // This has so far only been implemented for MachO.
11915 bool ARMTargetLowering::useLoadStackGuardNode() const {
11916 return Subtarget->isTargetMachO();
11919 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11920 unsigned &Cost) const {
11921 // If we do not have NEON, vector types are not natively supported.
11922 if (!Subtarget->hasNEON())
11925 // Floating point values and vector values map to the same register file.
11926 // Therefore, although we could do a store extract of a vector type, this is
11927 // better to leave at float as we have more freedom in the addressing mode for
11929 if (VectorTy->isFPOrFPVectorTy())
11932 // If the index is unknown at compile time, this is very expensive to lower
11933 // and it is not possible to combine the store with the extract.
11934 if (!isa<ConstantInt>(Idx))
11937 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11938 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11939 // We can do a store + vector extract on any vector that fits perfectly in a D
11941 if (BitWidth == 64 || BitWidth == 128) {
11948 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
11949 return Subtarget->hasV6T2Ops();
11952 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
11953 return Subtarget->hasV6T2Ops();
11956 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11957 AtomicOrdering Ord) const {
11958 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11959 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11960 bool IsAcquire = isAtLeastAcquire(Ord);
11962 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11963 // intrinsic must return {i32, i32} and we have to recombine them into a
11964 // single i64 here.
11965 if (ValTy->getPrimitiveSizeInBits() == 64) {
11966 Intrinsic::ID Int =
11967 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11968 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11970 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11971 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11973 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11974 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11975 if (!Subtarget->isLittle())
11976 std::swap (Lo, Hi);
11977 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11978 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11979 return Builder.CreateOr(
11980 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11983 Type *Tys[] = { Addr->getType() };
11984 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11985 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11987 return Builder.CreateTruncOrBitCast(
11988 Builder.CreateCall(Ldrex, Addr),
11989 cast<PointerType>(Addr->getType())->getElementType());
11992 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11993 IRBuilder<> &Builder) const {
11994 if (!Subtarget->hasV7Ops())
11996 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11997 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12000 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12002 AtomicOrdering Ord) const {
12003 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12004 bool IsRelease = isAtLeastRelease(Ord);
12006 // Since the intrinsics must have legal type, the i64 intrinsics take two
12007 // parameters: "i32, i32". We must marshal Val into the appropriate form
12008 // before the call.
12009 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12010 Intrinsic::ID Int =
12011 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12012 Function *Strex = Intrinsic::getDeclaration(M, Int);
12013 Type *Int32Ty = Type::getInt32Ty(M->getContext());
12015 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
12016 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
12017 if (!Subtarget->isLittle())
12018 std::swap (Lo, Hi);
12019 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12020 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
12023 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
12024 Type *Tys[] = { Addr->getType() };
12025 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
12027 return Builder.CreateCall(
12028 Strex, {Builder.CreateZExtOrBitCast(
12029 Val, Strex->getFunctionType()->getParamType(0)),
12033 /// \brief Lower an interleaved load into a vldN intrinsic.
12035 /// E.g. Lower an interleaved load (Factor = 2):
12036 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
12037 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
12038 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
12041 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
12042 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
12043 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
12044 bool ARMTargetLowering::lowerInterleavedLoad(
12045 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12046 ArrayRef<unsigned> Indices, unsigned Factor) const {
12047 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12048 "Invalid interleave factor");
12049 assert(!Shuffles.empty() && "Empty shufflevector input");
12050 assert(Shuffles.size() == Indices.size() &&
12051 "Unmatched number of shufflevectors and indices");
12053 VectorType *VecTy = Shuffles[0]->getType();
12054 Type *EltTy = VecTy->getVectorElementType();
12056 const DataLayout &DL = LI->getModule()->getDataLayout();
12057 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
12058 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
12060 // Skip if we do not have NEON and skip illegal vector types and vector types
12061 // with i64/f64 elements (vldN doesn't support i64/f64 elements).
12062 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
12065 // A pointer vector can not be the return type of the ldN intrinsics. Need to
12066 // load integer vectors first and then convert to pointer vectors.
12067 if (EltTy->isPointerTy())
12069 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
12071 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
12072 Intrinsic::arm_neon_vld3,
12073 Intrinsic::arm_neon_vld4};
12075 IRBuilder<> Builder(LI);
12076 SmallVector<Value *, 2> Ops;
12078 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
12079 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
12080 Ops.push_back(Builder.getInt32(LI->getAlignment()));
12082 Type *Tys[] = { VecTy, Int8Ptr };
12083 Function *VldnFunc =
12084 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12085 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
12087 // Replace uses of each shufflevector with the corresponding vector loaded
12089 for (unsigned i = 0; i < Shuffles.size(); i++) {
12090 ShuffleVectorInst *SV = Shuffles[i];
12091 unsigned Index = Indices[i];
12093 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
12095 // Convert the integer vector to pointer vector if the element is pointer.
12096 if (EltTy->isPointerTy())
12097 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
12099 SV->replaceAllUsesWith(SubVec);
12105 /// \brief Get a mask consisting of sequential integers starting from \p Start.
12107 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
12108 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
12109 unsigned NumElts) {
12110 SmallVector<Constant *, 16> Mask;
12111 for (unsigned i = 0; i < NumElts; i++)
12112 Mask.push_back(Builder.getInt32(Start + i));
12114 return ConstantVector::get(Mask);
12117 /// \brief Lower an interleaved store into a vstN intrinsic.
12119 /// E.g. Lower an interleaved store (Factor = 3):
12120 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12121 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12122 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12125 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12126 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12127 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12128 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12130 /// Note that the new shufflevectors will be removed and we'll only generate one
12131 /// vst3 instruction in CodeGen.
12132 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12133 ShuffleVectorInst *SVI,
12134 unsigned Factor) const {
12135 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12136 "Invalid interleave factor");
12138 VectorType *VecTy = SVI->getType();
12139 assert(VecTy->getVectorNumElements() % Factor == 0 &&
12140 "Invalid interleaved store");
12142 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12143 Type *EltTy = VecTy->getVectorElementType();
12144 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12146 const DataLayout &DL = SI->getModule()->getDataLayout();
12147 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
12148 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
12150 // Skip if we do not have NEON and skip illegal vector types and vector types
12151 // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12152 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12156 Value *Op0 = SVI->getOperand(0);
12157 Value *Op1 = SVI->getOperand(1);
12158 IRBuilder<> Builder(SI);
12160 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12161 // vectors to integer vectors.
12162 if (EltTy->isPointerTy()) {
12163 Type *IntTy = DL.getIntPtrType(EltTy);
12165 // Convert to the corresponding integer vector.
12167 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12168 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12169 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12171 SubVecTy = VectorType::get(IntTy, NumSubElts);
12174 static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12175 Intrinsic::arm_neon_vst3,
12176 Intrinsic::arm_neon_vst4};
12177 SmallVector<Value *, 6> Ops;
12179 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12180 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12182 Type *Tys[] = { Int8Ptr, SubVecTy };
12183 Function *VstNFunc = Intrinsic::getDeclaration(
12184 SI->getModule(), StoreInts[Factor - 2], Tys);
12186 // Split the shufflevector operands into sub vectors for the new vstN call.
12187 for (unsigned i = 0; i < Factor; i++)
12188 Ops.push_back(Builder.CreateShuffleVector(
12189 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12191 Ops.push_back(Builder.getInt32(SI->getAlignment()));
12192 Builder.CreateCall(VstNFunc, Ops);
12204 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12205 uint64_t &Members) {
12206 if (auto *ST = dyn_cast<StructType>(Ty)) {
12207 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12208 uint64_t SubMembers = 0;
12209 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12211 Members += SubMembers;
12213 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12214 uint64_t SubMembers = 0;
12215 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12217 Members += SubMembers * AT->getNumElements();
12218 } else if (Ty->isFloatTy()) {
12219 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12223 } else if (Ty->isDoubleTy()) {
12224 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12228 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12235 return VT->getBitWidth() == 64;
12237 return VT->getBitWidth() == 128;
12239 switch (VT->getBitWidth()) {
12252 return (Members > 0 && Members <= 4);
12255 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12256 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12257 /// passing according to AAPCS rules.
12258 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12259 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12260 if (getEffectiveCallingConv(CallConv, isVarArg) !=
12261 CallingConv::ARM_AAPCS_VFP)
12264 HABaseType Base = HA_UNKNOWN;
12265 uint64_t Members = 0;
12266 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12267 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12269 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12270 return IsHA || IsIntArray;
12273 unsigned ARMTargetLowering::getExceptionPointerRegister(
12274 const Constant *PersonalityFn) const {
12275 // Platforms which do not use SjLj EH may return values in these registers
12276 // via the personality function.
12277 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12280 unsigned ARMTargetLowering::getExceptionSelectorRegister(
12281 const Constant *PersonalityFn) const {
12282 // Platforms which do not use SjLj EH may return values in these registers
12283 // via the personality function.
12284 return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;