1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "arm-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
64 ARMInterworking("arm-interworking", cl::Hidden,
65 cl::desc("Enable / disable ARM interworking (for debugging only)"),
69 class ARMCCState : public CCState {
71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
74 : CCState(CC, isVarArg, MF, locs, C) {
75 assert(((PC == Call) || (PC == Prologue)) &&
76 "ARMCCState users must specify whether their context is call"
77 "or prologue generation.");
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85 ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89 MVT PromotedBitwiseVT) {
90 if (VT != PromotedLdStVT) {
91 setOperationAction(ISD::LOAD, VT, Promote);
92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94 setOperationAction(ISD::STORE, VT, Promote);
95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98 MVT ElemTy = VT.getVectorElementType();
99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100 setOperationAction(ISD::SETCC, VT, Custom);
101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103 if (ElemTy == MVT::i32) {
104 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118 setOperationAction(ISD::SELECT, VT, Expand);
119 setOperationAction(ISD::SELECT_CC, VT, Expand);
120 setOperationAction(ISD::VSELECT, VT, Expand);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122 if (VT.isInteger()) {
123 setOperationAction(ISD::SHL, VT, Custom);
124 setOperationAction(ISD::SRA, VT, Custom);
125 setOperationAction(ISD::SRL, VT, Custom);
128 // Promote all bit-wise operations.
129 if (VT.isInteger() && VT != PromotedBitwiseVT) {
130 setOperationAction(ISD::AND, VT, Promote);
131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132 setOperationAction(ISD::OR, VT, Promote);
133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::XOR, VT, Promote);
135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138 // Neon does not support vector divide/remainder operations.
139 setOperationAction(ISD::SDIV, VT, Expand);
140 setOperationAction(ISD::UDIV, VT, Expand);
141 setOperationAction(ISD::FDIV, VT, Expand);
142 setOperationAction(ISD::SREM, VT, Expand);
143 setOperationAction(ISD::UREM, VT, Expand);
144 setOperationAction(ISD::FREM, VT, Expand);
146 if (VT.isInteger()) {
147 setOperationAction(ISD::SABSDIFF, VT, Legal);
148 setOperationAction(ISD::UABSDIFF, VT, Legal);
150 if (!VT.isFloatingPoint() &&
151 VT != MVT::v2i64 && VT != MVT::v1i64)
152 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
153 setOperationAction(Opcode, VT, Legal);
157 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::DPRRegClass);
159 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
162 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
163 addRegisterClass(VT, &ARM::DPairRegClass);
164 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
168 const ARMSubtarget &STI)
169 : TargetLowering(TM), Subtarget(&STI) {
170 RegInfo = Subtarget->getRegisterInfo();
171 Itins = Subtarget->getInstrItineraryData();
173 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
175 if (Subtarget->isTargetMachO()) {
176 // Uses VFP for Thumb libfuncs if available.
177 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
179 static const struct {
180 const RTLIB::Libcall Op;
181 const char * const Name;
182 const ISD::CondCode Cond;
184 // Single-precision floating-point arithmetic.
185 { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
186 { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
187 { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
188 { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
190 // Double-precision floating-point arithmetic.
191 { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
192 { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
193 { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
194 { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
196 // Single-precision comparisons.
197 { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
198 { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
199 { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
200 { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
201 { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
202 { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
203 { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
204 { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
206 // Double-precision comparisons.
207 { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
208 { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
209 { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
210 { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
211 { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
212 { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
213 { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
214 { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
216 // Floating-point to integer conversions.
217 // i64 conversions are done via library routines even when generating VFP
218 // instructions, so use the same ones.
219 { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
220 { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
221 { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
222 { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
224 // Conversions between floating types.
225 { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
226 { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
228 // Integer to floating-point conversions.
229 // i64 conversions are done via library routines even when generating VFP
230 // instructions, so use the same ones.
231 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
232 // e.g., __floatunsidf vs. __floatunssidfvfp.
233 { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
234 { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
235 { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
236 { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
239 for (const auto &LC : LibraryCalls) {
240 setLibcallName(LC.Op, LC.Name);
241 if (LC.Cond != ISD::SETCC_INVALID)
242 setCmpLibcallCC(LC.Op, LC.Cond);
247 // These libcalls are not available in 32-bit.
248 setLibcallName(RTLIB::SHL_I128, nullptr);
249 setLibcallName(RTLIB::SRL_I128, nullptr);
250 setLibcallName(RTLIB::SRA_I128, nullptr);
252 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
253 !Subtarget->isTargetWindows()) {
254 static const struct {
255 const RTLIB::Libcall Op;
256 const char * const Name;
257 const CallingConv::ID CC;
258 const ISD::CondCode Cond;
260 // Double-precision floating-point arithmetic helper functions
261 // RTABI chapter 4.1.2, Table 2
262 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267 // Double-precision floating-point comparison helper functions
268 // RTABI chapter 4.1.2, Table 3
269 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
270 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
271 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
272 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
273 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
274 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
276 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
278 // Single-precision floating-point arithmetic helper functions
279 // RTABI chapter 4.1.2, Table 4
280 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285 // Single-precision floating-point comparison helper functions
286 // RTABI chapter 4.1.2, Table 5
287 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
288 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
289 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
290 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
291 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
292 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
294 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
296 // Floating-point to integer conversions.
297 // RTABI chapter 4.1.2, Table 6
298 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 // Conversions between floating types.
308 // RTABI chapter 4.1.2, Table 7
309 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 // Integer to floating-point conversions.
314 // RTABI chapter 4.1.2, Table 8
315 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 // Long long helper functions
325 // RTABI chapter 4.2, Table 9
326 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 // Integer division functions
332 // RTABI chapter 4.3.1
333 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 // RTABI chapter 4.3.4
344 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 for (const auto &LC : LibraryCalls) {
350 setLibcallName(LC.Op, LC.Name);
351 setLibcallCallingConv(LC.Op, LC.CC);
352 if (LC.Cond != ISD::SETCC_INVALID)
353 setCmpLibcallCC(LC.Op, LC.Cond);
357 if (Subtarget->isTargetWindows()) {
358 static const struct {
359 const RTLIB::Libcall Op;
360 const char * const Name;
361 const CallingConv::ID CC;
363 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
364 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
366 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
373 for (const auto &LC : LibraryCalls) {
374 setLibcallName(LC.Op, LC.Name);
375 setLibcallCallingConv(LC.Op, LC.CC);
379 // Use divmod compiler-rt calls for iOS 5.0 and later.
380 if (Subtarget->getTargetTriple().isiOS() &&
381 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
386 // The half <-> float conversion functions are always soft-float, but are
387 // needed for some targets which use a hard-float calling convention by
389 if (Subtarget->isAAPCS_ABI()) {
390 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
399 if (Subtarget->isThumb1Only())
400 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
402 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
403 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
404 !Subtarget->isThumb1Only()) {
405 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
406 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
409 for (MVT VT : MVT::vector_valuetypes()) {
410 for (MVT InnerVT : MVT::vector_valuetypes()) {
411 setTruncStoreAction(VT, InnerVT, Expand);
412 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
413 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
414 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
417 setOperationAction(ISD::MULHS, VT, Expand);
418 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419 setOperationAction(ISD::MULHU, VT, Expand);
420 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
422 setOperationAction(ISD::BSWAP, VT, Expand);
425 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
428 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
429 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
431 if (Subtarget->hasNEON()) {
432 addDRTypeForNEON(MVT::v2f32);
433 addDRTypeForNEON(MVT::v8i8);
434 addDRTypeForNEON(MVT::v4i16);
435 addDRTypeForNEON(MVT::v2i32);
436 addDRTypeForNEON(MVT::v1i64);
438 addQRTypeForNEON(MVT::v4f32);
439 addQRTypeForNEON(MVT::v2f64);
440 addQRTypeForNEON(MVT::v16i8);
441 addQRTypeForNEON(MVT::v8i16);
442 addQRTypeForNEON(MVT::v4i32);
443 addQRTypeForNEON(MVT::v2i64);
445 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
446 // neither Neon nor VFP support any arithmetic operations on it.
447 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
448 // supported for v4f32.
449 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
450 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
451 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
452 // FIXME: Code duplication: FDIV and FREM are expanded always, see
453 // ARMTargetLowering::addTypeForNEON method for details.
454 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
455 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
456 // FIXME: Create unittest.
457 // In another words, find a way when "copysign" appears in DAG with vector
459 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
460 // FIXME: Code duplication: SETCC has custom operation action, see
461 // ARMTargetLowering::addTypeForNEON method for details.
462 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
463 // FIXME: Create unittest for FNEG and for FABS.
464 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
465 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
466 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
467 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
468 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
469 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
470 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
471 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
472 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
473 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
474 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
475 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
476 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
477 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
478 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
479 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
480 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
481 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
482 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
484 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
485 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
486 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
487 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
488 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
489 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
490 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
491 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
492 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
493 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
494 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
495 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
496 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
497 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
498 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
500 // Mark v2f32 intrinsics.
501 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
502 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
503 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
504 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
505 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
506 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
507 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
508 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
509 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
510 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
511 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
512 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
513 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
514 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
515 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
517 // Neon does not support some operations on v1i64 and v2i64 types.
518 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
519 // Custom handling for some quad-vector types to detect VMULL.
520 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
522 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
523 // Custom handling for some vector types to avoid expensive expansions
524 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
525 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
526 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
527 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
528 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
529 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
530 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
531 // a destination type that is wider than the source, and nor does
532 // it have a FP_TO_[SU]INT instruction with a narrower destination than
534 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
535 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
536 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
537 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
539 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
540 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
542 // NEON does not have single instruction CTPOP for vectors with element
543 // types wider than 8-bits. However, custom lowering can leverage the
544 // v8i8/v16i8 vcnt instruction.
545 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
546 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
547 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
548 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
550 // NEON does not have single instruction CTTZ for vectors.
551 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
552 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
553 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
554 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
556 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
557 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
558 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
559 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
561 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
563 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
564 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
566 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
567 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
568 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
569 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
571 // NEON only has FMA instructions as of VFP4.
572 if (!Subtarget->hasVFP4()) {
573 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
574 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
577 setTargetDAGCombine(ISD::INTRINSIC_VOID);
578 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
579 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
580 setTargetDAGCombine(ISD::SHL);
581 setTargetDAGCombine(ISD::SRL);
582 setTargetDAGCombine(ISD::SRA);
583 setTargetDAGCombine(ISD::SIGN_EXTEND);
584 setTargetDAGCombine(ISD::ZERO_EXTEND);
585 setTargetDAGCombine(ISD::ANY_EXTEND);
586 setTargetDAGCombine(ISD::BUILD_VECTOR);
587 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
588 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
589 setTargetDAGCombine(ISD::STORE);
590 setTargetDAGCombine(ISD::FP_TO_SINT);
591 setTargetDAGCombine(ISD::FP_TO_UINT);
592 setTargetDAGCombine(ISD::FDIV);
593 setTargetDAGCombine(ISD::LOAD);
595 // It is legal to extload from v4i8 to v4i16 or v4i32.
596 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
598 for (MVT VT : MVT::integer_vector_valuetypes()) {
599 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
600 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
601 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
606 // ARM and Thumb2 support UMLAL/SMLAL.
607 if (!Subtarget->isThumb1Only())
608 setTargetDAGCombine(ISD::ADDC);
610 if (Subtarget->isFPOnlySP()) {
611 // When targeting a floating-point unit with only single-precision
612 // operations, f64 is legal for the few double-precision instructions which
613 // are present However, no double-precision operations other than moves,
614 // loads and stores are provided by the hardware.
615 setOperationAction(ISD::FADD, MVT::f64, Expand);
616 setOperationAction(ISD::FSUB, MVT::f64, Expand);
617 setOperationAction(ISD::FMUL, MVT::f64, Expand);
618 setOperationAction(ISD::FMA, MVT::f64, Expand);
619 setOperationAction(ISD::FDIV, MVT::f64, Expand);
620 setOperationAction(ISD::FREM, MVT::f64, Expand);
621 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
622 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
623 setOperationAction(ISD::FNEG, MVT::f64, Expand);
624 setOperationAction(ISD::FABS, MVT::f64, Expand);
625 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
626 setOperationAction(ISD::FSIN, MVT::f64, Expand);
627 setOperationAction(ISD::FCOS, MVT::f64, Expand);
628 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
629 setOperationAction(ISD::FPOW, MVT::f64, Expand);
630 setOperationAction(ISD::FLOG, MVT::f64, Expand);
631 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
632 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
633 setOperationAction(ISD::FEXP, MVT::f64, Expand);
634 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
635 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
636 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
637 setOperationAction(ISD::FRINT, MVT::f64, Expand);
638 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
639 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
640 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
641 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
642 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
643 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
644 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
645 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
646 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
647 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
650 computeRegisterProperties(Subtarget->getRegisterInfo());
652 // ARM does not have floating-point extending loads.
653 for (MVT VT : MVT::fp_valuetypes()) {
654 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
655 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
658 // ... or truncating stores
659 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
660 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
661 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
663 // ARM does not have i1 sign extending load.
664 for (MVT VT : MVT::integer_valuetypes())
665 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
667 // ARM supports all 4 flavors of integer indexed load / store.
668 if (!Subtarget->isThumb1Only()) {
669 for (unsigned im = (unsigned)ISD::PRE_INC;
670 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
671 setIndexedLoadAction(im, MVT::i1, Legal);
672 setIndexedLoadAction(im, MVT::i8, Legal);
673 setIndexedLoadAction(im, MVT::i16, Legal);
674 setIndexedLoadAction(im, MVT::i32, Legal);
675 setIndexedStoreAction(im, MVT::i1, Legal);
676 setIndexedStoreAction(im, MVT::i8, Legal);
677 setIndexedStoreAction(im, MVT::i16, Legal);
678 setIndexedStoreAction(im, MVT::i32, Legal);
682 setOperationAction(ISD::SADDO, MVT::i32, Custom);
683 setOperationAction(ISD::UADDO, MVT::i32, Custom);
684 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
685 setOperationAction(ISD::USUBO, MVT::i32, Custom);
687 // i64 operation support.
688 setOperationAction(ISD::MUL, MVT::i64, Expand);
689 setOperationAction(ISD::MULHU, MVT::i32, Expand);
690 if (Subtarget->isThumb1Only()) {
691 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
692 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
694 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
695 || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
696 setOperationAction(ISD::MULHS, MVT::i32, Expand);
698 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
699 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
700 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
701 setOperationAction(ISD::SRL, MVT::i64, Custom);
702 setOperationAction(ISD::SRA, MVT::i64, Custom);
704 if (!Subtarget->isThumb1Only()) {
705 // FIXME: We should do this for Thumb1 as well.
706 setOperationAction(ISD::ADDC, MVT::i32, Custom);
707 setOperationAction(ISD::ADDE, MVT::i32, Custom);
708 setOperationAction(ISD::SUBC, MVT::i32, Custom);
709 setOperationAction(ISD::SUBE, MVT::i32, Custom);
712 // ARM does not have ROTL.
713 setOperationAction(ISD::ROTL, MVT::i32, Expand);
714 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
715 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
716 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
717 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
719 // These just redirect to CTTZ and CTLZ on ARM.
720 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
721 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
723 // @llvm.readcyclecounter requires the Performance Monitors extension.
724 // Default to the 0 expansion on unsupported platforms.
725 // FIXME: Technically there are older ARM CPUs that have
726 // implementation-specific ways of obtaining this information.
727 if (Subtarget->hasPerfMon())
728 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
730 // Only ARMv6 has BSWAP.
731 if (!Subtarget->hasV6Ops())
732 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
734 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
735 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
736 // These are expanded into libcalls if the cpu doesn't have HW divider.
737 setOperationAction(ISD::SDIV, MVT::i32, Expand);
738 setOperationAction(ISD::UDIV, MVT::i32, Expand);
741 if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
742 setOperationAction(ISD::SDIV, MVT::i32, Custom);
743 setOperationAction(ISD::UDIV, MVT::i32, Custom);
745 setOperationAction(ISD::SDIV, MVT::i64, Custom);
746 setOperationAction(ISD::UDIV, MVT::i64, Custom);
749 setOperationAction(ISD::SREM, MVT::i32, Expand);
750 setOperationAction(ISD::UREM, MVT::i32, Expand);
751 // Register based DivRem for AEABI (RTABI 4.2)
752 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
753 setOperationAction(ISD::SREM, MVT::i64, Custom);
754 setOperationAction(ISD::UREM, MVT::i64, Custom);
756 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
757 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
758 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
759 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
760 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
761 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
762 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
763 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
765 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
766 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
767 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
768 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
769 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
770 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
771 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
772 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
774 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
775 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
777 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
778 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
781 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
782 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
783 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
784 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
785 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
787 setOperationAction(ISD::TRAP, MVT::Other, Legal);
789 // Use the default implementation.
790 setOperationAction(ISD::VASTART, MVT::Other, Custom);
791 setOperationAction(ISD::VAARG, MVT::Other, Expand);
792 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
793 setOperationAction(ISD::VAEND, MVT::Other, Expand);
794 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
795 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
797 if (!Subtarget->isTargetMachO()) {
798 // Non-MachO platforms may return values in these registers via the
799 // personality function.
800 setExceptionPointerRegister(ARM::R0);
801 setExceptionSelectorRegister(ARM::R1);
804 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
805 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
807 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
809 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
810 // the default expansion. If we are targeting a single threaded system,
811 // then set them all for expand so we can lower them later into their
813 if (TM.Options.ThreadModel == ThreadModel::Single)
814 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
815 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
816 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
817 // to ldrex/strex loops already.
818 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
820 // On v8, we have particularly efficient implementations of atomic fences
821 // if they can be combined with nearby atomic loads and stores.
822 if (!Subtarget->hasV8Ops()) {
823 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
824 setInsertFencesForAtomic(true);
827 // If there's anything we can use as a barrier, go through custom lowering
829 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
830 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
832 // Set them all for expansion, which will force libcalls.
833 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
834 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
835 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
836 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
837 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
838 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
839 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
840 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
841 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
842 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
843 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
844 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
845 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
846 // Unordered/Monotonic case.
847 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
848 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
851 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
853 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
854 if (!Subtarget->hasV6Ops()) {
855 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
856 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
858 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
860 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
861 !Subtarget->isThumb1Only()) {
862 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
863 // iff target supports vfp2.
864 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
865 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
868 // We want to custom lower some of our intrinsics.
869 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
870 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
871 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
872 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
873 if (Subtarget->isTargetDarwin())
874 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
876 setOperationAction(ISD::SETCC, MVT::i32, Expand);
877 setOperationAction(ISD::SETCC, MVT::f32, Expand);
878 setOperationAction(ISD::SETCC, MVT::f64, Expand);
879 setOperationAction(ISD::SELECT, MVT::i32, Custom);
880 setOperationAction(ISD::SELECT, MVT::f32, Custom);
881 setOperationAction(ISD::SELECT, MVT::f64, Custom);
882 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
883 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
884 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
886 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
887 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
888 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
889 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
890 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
892 // We don't support sin/cos/fmod/copysign/pow
893 setOperationAction(ISD::FSIN, MVT::f64, Expand);
894 setOperationAction(ISD::FSIN, MVT::f32, Expand);
895 setOperationAction(ISD::FCOS, MVT::f32, Expand);
896 setOperationAction(ISD::FCOS, MVT::f64, Expand);
897 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
898 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
899 setOperationAction(ISD::FREM, MVT::f64, Expand);
900 setOperationAction(ISD::FREM, MVT::f32, Expand);
901 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
902 !Subtarget->isThumb1Only()) {
903 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
904 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
906 setOperationAction(ISD::FPOW, MVT::f64, Expand);
907 setOperationAction(ISD::FPOW, MVT::f32, Expand);
909 if (!Subtarget->hasVFP4()) {
910 setOperationAction(ISD::FMA, MVT::f64, Expand);
911 setOperationAction(ISD::FMA, MVT::f32, Expand);
914 // Various VFP goodness
915 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
916 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
917 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
918 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
919 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
922 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
923 if (!Subtarget->hasFP16()) {
924 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
925 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
929 // Combine sin / cos into one node or libcall if possible.
930 if (Subtarget->hasSinCos()) {
931 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
932 setLibcallName(RTLIB::SINCOS_F64, "sincos");
933 if (Subtarget->getTargetTriple().isiOS()) {
934 // For iOS, we don't want to the normal expansion of a libcall to
935 // sincos. We want to issue a libcall to __sincos_stret.
936 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
937 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
941 // FP-ARMv8 implements a lot of rounding-like FP operations.
942 if (Subtarget->hasFPARMv8()) {
943 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
944 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
945 setOperationAction(ISD::FROUND, MVT::f32, Legal);
946 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
947 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
948 setOperationAction(ISD::FRINT, MVT::f32, Legal);
949 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
950 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
951 setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
952 setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
953 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
954 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
956 if (!Subtarget->isFPOnlySP()) {
957 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
958 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
959 setOperationAction(ISD::FROUND, MVT::f64, Legal);
960 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
961 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
962 setOperationAction(ISD::FRINT, MVT::f64, Legal);
963 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
964 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
968 if (Subtarget->hasNEON()) {
969 // vmin and vmax aren't available in a scalar form, so we use
970 // a NEON instruction with an undef lane instead.
971 setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
972 setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
973 setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
974 setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
975 setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
976 setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
979 // We have target-specific dag combine patterns for the following nodes:
980 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
981 setTargetDAGCombine(ISD::ADD);
982 setTargetDAGCombine(ISD::SUB);
983 setTargetDAGCombine(ISD::MUL);
984 setTargetDAGCombine(ISD::AND);
985 setTargetDAGCombine(ISD::OR);
986 setTargetDAGCombine(ISD::XOR);
988 if (Subtarget->hasV6Ops())
989 setTargetDAGCombine(ISD::SRL);
991 setStackPointerRegisterToSaveRestore(ARM::SP);
993 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
994 !Subtarget->hasVFP2())
995 setSchedulingPreference(Sched::RegPressure);
997 setSchedulingPreference(Sched::Hybrid);
999 //// temporary - rewrite interface to use type
1000 MaxStoresPerMemset = 8;
1001 MaxStoresPerMemsetOptSize = 4;
1002 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1003 MaxStoresPerMemcpyOptSize = 2;
1004 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1005 MaxStoresPerMemmoveOptSize = 2;
1007 // On ARM arguments smaller than 4 bytes are extended, so all arguments
1008 // are at least 4 bytes aligned.
1009 setMinStackArgumentAlignment(4);
1011 // Prefer likely predicted branches to selects on out-of-order cores.
1012 PredictableSelectIsExpensive = Subtarget->isLikeA9();
1014 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1017 bool ARMTargetLowering::useSoftFloat() const {
1018 return Subtarget->useSoftFloat();
1021 // FIXME: It might make sense to define the representative register class as the
1022 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1023 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1024 // SPR's representative would be DPR_VFP2. This should work well if register
1025 // pressure tracking were modified such that a register use would increment the
1026 // pressure of the register class's representative and all of it's super
1027 // classes' representatives transitively. We have not implemented this because
1028 // of the difficulty prior to coalescing of modeling operand register classes
1029 // due to the common occurrence of cross class copies and subregister insertions
1031 std::pair<const TargetRegisterClass *, uint8_t>
1032 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1034 const TargetRegisterClass *RRC = nullptr;
1036 switch (VT.SimpleTy) {
1038 return TargetLowering::findRepresentativeClass(TRI, VT);
1039 // Use DPR as representative register class for all floating point
1040 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1041 // the cost is 1 for both f32 and f64.
1042 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1043 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1044 RRC = &ARM::DPRRegClass;
1045 // When NEON is used for SP, only half of the register file is available
1046 // because operations that define both SP and DP results will be constrained
1047 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1048 // coalescing by double-counting the SP regs. See the FIXME above.
1049 if (Subtarget->useNEONForSinglePrecisionFP())
1052 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1053 case MVT::v4f32: case MVT::v2f64:
1054 RRC = &ARM::DPRRegClass;
1058 RRC = &ARM::DPRRegClass;
1062 RRC = &ARM::DPRRegClass;
1066 return std::make_pair(RRC, Cost);
1069 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1070 switch ((ARMISD::NodeType)Opcode) {
1071 case ARMISD::FIRST_NUMBER: break;
1072 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1073 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1074 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1075 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1076 case ARMISD::CALL: return "ARMISD::CALL";
1077 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1078 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1079 case ARMISD::tCALL: return "ARMISD::tCALL";
1080 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1081 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1082 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1083 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1084 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1085 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1086 case ARMISD::CMP: return "ARMISD::CMP";
1087 case ARMISD::CMN: return "ARMISD::CMN";
1088 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1089 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1090 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1091 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1092 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1094 case ARMISD::CMOV: return "ARMISD::CMOV";
1096 case ARMISD::RBIT: return "ARMISD::RBIT";
1098 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1099 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1100 case ARMISD::RRX: return "ARMISD::RRX";
1102 case ARMISD::ADDC: return "ARMISD::ADDC";
1103 case ARMISD::ADDE: return "ARMISD::ADDE";
1104 case ARMISD::SUBC: return "ARMISD::SUBC";
1105 case ARMISD::SUBE: return "ARMISD::SUBE";
1107 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1108 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1110 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1111 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1112 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1114 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1116 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1118 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1120 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1122 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1124 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1125 case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1127 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1128 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1129 case ARMISD::VCGE: return "ARMISD::VCGE";
1130 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1131 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1132 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1133 case ARMISD::VCGT: return "ARMISD::VCGT";
1134 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1135 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1136 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1137 case ARMISD::VTST: return "ARMISD::VTST";
1139 case ARMISD::VSHL: return "ARMISD::VSHL";
1140 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1141 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1142 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1143 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1144 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1145 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1146 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1147 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1148 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1149 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1150 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1151 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1152 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1153 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1154 case ARMISD::VSLI: return "ARMISD::VSLI";
1155 case ARMISD::VSRI: return "ARMISD::VSRI";
1156 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1157 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1158 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1159 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1160 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1161 case ARMISD::VDUP: return "ARMISD::VDUP";
1162 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1163 case ARMISD::VEXT: return "ARMISD::VEXT";
1164 case ARMISD::VREV64: return "ARMISD::VREV64";
1165 case ARMISD::VREV32: return "ARMISD::VREV32";
1166 case ARMISD::VREV16: return "ARMISD::VREV16";
1167 case ARMISD::VZIP: return "ARMISD::VZIP";
1168 case ARMISD::VUZP: return "ARMISD::VUZP";
1169 case ARMISD::VTRN: return "ARMISD::VTRN";
1170 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1171 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1172 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1173 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1174 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1175 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1176 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1177 case ARMISD::BFI: return "ARMISD::BFI";
1178 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1179 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1180 case ARMISD::VBSL: return "ARMISD::VBSL";
1181 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1182 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1183 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1184 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1185 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1186 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1187 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1188 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1189 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1190 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1191 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1192 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1193 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1194 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1195 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1196 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1197 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1198 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1199 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1200 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1205 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1208 return getPointerTy(DL);
1209 return VT.changeVectorElementTypeToInteger();
1212 /// getRegClassFor - Return the register class that should be used for the
1213 /// specified value type.
1214 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1215 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1216 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1217 // load / store 4 to 8 consecutive D registers.
1218 if (Subtarget->hasNEON()) {
1219 if (VT == MVT::v4i64)
1220 return &ARM::QQPRRegClass;
1221 if (VT == MVT::v8i64)
1222 return &ARM::QQQQPRRegClass;
1224 return TargetLowering::getRegClassFor(VT);
1227 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1228 // source/dest is aligned and the copy size is large enough. We therefore want
1229 // to align such objects passed to memory intrinsics.
1230 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1231 unsigned &PrefAlign) const {
1232 if (!isa<MemIntrinsic>(CI))
1235 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1236 // cycle faster than 4-byte aligned LDM.
1237 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1241 // Create a fast isel object.
1243 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1244 const TargetLibraryInfo *libInfo) const {
1245 return ARM::createFastISel(funcInfo, libInfo);
1248 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1249 unsigned NumVals = N->getNumValues();
1251 return Sched::RegPressure;
1253 for (unsigned i = 0; i != NumVals; ++i) {
1254 EVT VT = N->getValueType(i);
1255 if (VT == MVT::Glue || VT == MVT::Other)
1257 if (VT.isFloatingPoint() || VT.isVector())
1261 if (!N->isMachineOpcode())
1262 return Sched::RegPressure;
1264 // Load are scheduled for latency even if there instruction itinerary
1265 // is not available.
1266 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1267 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1269 if (MCID.getNumDefs() == 0)
1270 return Sched::RegPressure;
1271 if (!Itins->isEmpty() &&
1272 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1275 return Sched::RegPressure;
1278 //===----------------------------------------------------------------------===//
1280 //===----------------------------------------------------------------------===//
1282 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1283 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1285 default: llvm_unreachable("Unknown condition code!");
1286 case ISD::SETNE: return ARMCC::NE;
1287 case ISD::SETEQ: return ARMCC::EQ;
1288 case ISD::SETGT: return ARMCC::GT;
1289 case ISD::SETGE: return ARMCC::GE;
1290 case ISD::SETLT: return ARMCC::LT;
1291 case ISD::SETLE: return ARMCC::LE;
1292 case ISD::SETUGT: return ARMCC::HI;
1293 case ISD::SETUGE: return ARMCC::HS;
1294 case ISD::SETULT: return ARMCC::LO;
1295 case ISD::SETULE: return ARMCC::LS;
1299 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1300 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1301 ARMCC::CondCodes &CondCode2) {
1302 CondCode2 = ARMCC::AL;
1304 default: llvm_unreachable("Unknown FP condition!");
1306 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1308 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1310 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1311 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1312 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1313 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1314 case ISD::SETO: CondCode = ARMCC::VC; break;
1315 case ISD::SETUO: CondCode = ARMCC::VS; break;
1316 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1317 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1318 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1320 case ISD::SETULT: CondCode = ARMCC::LT; break;
1322 case ISD::SETULE: CondCode = ARMCC::LE; break;
1324 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1328 //===----------------------------------------------------------------------===//
1329 // Calling Convention Implementation
1330 //===----------------------------------------------------------------------===//
1332 #include "ARMGenCallingConv.inc"
1334 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1335 /// account presence of floating point hardware and calling convention
1336 /// limitations, such as support for variadic functions.
1338 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1339 bool isVarArg) const {
1342 llvm_unreachable("Unsupported calling convention");
1343 case CallingConv::ARM_AAPCS:
1344 case CallingConv::ARM_APCS:
1345 case CallingConv::GHC:
1347 case CallingConv::ARM_AAPCS_VFP:
1348 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1349 case CallingConv::C:
1350 if (!Subtarget->isAAPCS_ABI())
1351 return CallingConv::ARM_APCS;
1352 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1353 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1355 return CallingConv::ARM_AAPCS_VFP;
1357 return CallingConv::ARM_AAPCS;
1358 case CallingConv::Fast:
1359 if (!Subtarget->isAAPCS_ABI()) {
1360 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1361 return CallingConv::Fast;
1362 return CallingConv::ARM_APCS;
1363 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1364 return CallingConv::ARM_AAPCS_VFP;
1366 return CallingConv::ARM_AAPCS;
1370 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1371 /// CallingConvention.
1372 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1374 bool isVarArg) const {
1375 switch (getEffectiveCallingConv(CC, isVarArg)) {
1377 llvm_unreachable("Unsupported calling convention");
1378 case CallingConv::ARM_APCS:
1379 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1380 case CallingConv::ARM_AAPCS:
1381 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1382 case CallingConv::ARM_AAPCS_VFP:
1383 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1384 case CallingConv::Fast:
1385 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1386 case CallingConv::GHC:
1387 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1391 /// LowerCallResult - Lower the result values of a call into the
1392 /// appropriate copies out of appropriate physical registers.
1394 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1395 CallingConv::ID CallConv, bool isVarArg,
1396 const SmallVectorImpl<ISD::InputArg> &Ins,
1397 SDLoc dl, SelectionDAG &DAG,
1398 SmallVectorImpl<SDValue> &InVals,
1399 bool isThisReturn, SDValue ThisVal) const {
1401 // Assign locations to each value returned by this call.
1402 SmallVector<CCValAssign, 16> RVLocs;
1403 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1404 *DAG.getContext(), Call);
1405 CCInfo.AnalyzeCallResult(Ins,
1406 CCAssignFnForNode(CallConv, /* Return*/ true,
1409 // Copy all of the result registers out of their specified physreg.
1410 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1411 CCValAssign VA = RVLocs[i];
1413 // Pass 'this' value directly from the argument to return value, to avoid
1414 // reg unit interference
1415 if (i == 0 && isThisReturn) {
1416 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1417 "unexpected return calling convention register assignment");
1418 InVals.push_back(ThisVal);
1423 if (VA.needsCustom()) {
1424 // Handle f64 or half of a v2f64.
1425 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1427 Chain = Lo.getValue(1);
1428 InFlag = Lo.getValue(2);
1429 VA = RVLocs[++i]; // skip ahead to next loc
1430 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1432 Chain = Hi.getValue(1);
1433 InFlag = Hi.getValue(2);
1434 if (!Subtarget->isLittle())
1436 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1438 if (VA.getLocVT() == MVT::v2f64) {
1439 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1440 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1441 DAG.getConstant(0, dl, MVT::i32));
1443 VA = RVLocs[++i]; // skip ahead to next loc
1444 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1445 Chain = Lo.getValue(1);
1446 InFlag = Lo.getValue(2);
1447 VA = RVLocs[++i]; // skip ahead to next loc
1448 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1449 Chain = Hi.getValue(1);
1450 InFlag = Hi.getValue(2);
1451 if (!Subtarget->isLittle())
1453 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1454 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1455 DAG.getConstant(1, dl, MVT::i32));
1458 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1460 Chain = Val.getValue(1);
1461 InFlag = Val.getValue(2);
1464 switch (VA.getLocInfo()) {
1465 default: llvm_unreachable("Unknown loc info!");
1466 case CCValAssign::Full: break;
1467 case CCValAssign::BCvt:
1468 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1472 InVals.push_back(Val);
1478 /// LowerMemOpCallTo - Store the argument to the stack.
1480 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1481 SDValue StackPtr, SDValue Arg,
1482 SDLoc dl, SelectionDAG &DAG,
1483 const CCValAssign &VA,
1484 ISD::ArgFlagsTy Flags) const {
1485 unsigned LocMemOffset = VA.getLocMemOffset();
1486 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1487 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1489 return DAG.getStore(
1490 Chain, dl, Arg, PtrOff,
1491 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1495 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1496 SDValue Chain, SDValue &Arg,
1497 RegsToPassVector &RegsToPass,
1498 CCValAssign &VA, CCValAssign &NextVA,
1500 SmallVectorImpl<SDValue> &MemOpChains,
1501 ISD::ArgFlagsTy Flags) const {
1503 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1504 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1505 unsigned id = Subtarget->isLittle() ? 0 : 1;
1506 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1508 if (NextVA.isRegLoc())
1509 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1511 assert(NextVA.isMemLoc());
1512 if (!StackPtr.getNode())
1513 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1514 getPointerTy(DAG.getDataLayout()));
1516 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1522 /// LowerCall - Lowering a call into a callseq_start <-
1523 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1526 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1527 SmallVectorImpl<SDValue> &InVals) const {
1528 SelectionDAG &DAG = CLI.DAG;
1530 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1531 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1532 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1533 SDValue Chain = CLI.Chain;
1534 SDValue Callee = CLI.Callee;
1535 bool &isTailCall = CLI.IsTailCall;
1536 CallingConv::ID CallConv = CLI.CallConv;
1537 bool doesNotRet = CLI.DoesNotReturn;
1538 bool isVarArg = CLI.IsVarArg;
1540 MachineFunction &MF = DAG.getMachineFunction();
1541 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1542 bool isThisReturn = false;
1543 bool isSibCall = false;
1544 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1546 // Disable tail calls if they're not supported.
1547 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1551 // Check if it's really possible to do a tail call.
1552 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1553 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1554 Outs, OutVals, Ins, DAG);
1555 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1556 report_fatal_error("failed to perform tail call elimination on a call "
1557 "site marked musttail");
1558 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1559 // detected sibcalls.
1566 // Analyze operands of the call, assigning locations to each operand.
1567 SmallVector<CCValAssign, 16> ArgLocs;
1568 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1569 *DAG.getContext(), Call);
1570 CCInfo.AnalyzeCallOperands(Outs,
1571 CCAssignFnForNode(CallConv, /* Return*/ false,
1574 // Get a count of how many bytes are to be pushed on the stack.
1575 unsigned NumBytes = CCInfo.getNextStackOffset();
1577 // For tail calls, memory operands are available in our caller's stack.
1581 // Adjust the stack pointer for the new arguments...
1582 // These operations are automatically eliminated by the prolog/epilog pass
1584 Chain = DAG.getCALLSEQ_START(Chain,
1585 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1588 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1590 RegsToPassVector RegsToPass;
1591 SmallVector<SDValue, 8> MemOpChains;
1593 // Walk the register/memloc assignments, inserting copies/loads. In the case
1594 // of tail call optimization, arguments are handled later.
1595 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1597 ++i, ++realArgIdx) {
1598 CCValAssign &VA = ArgLocs[i];
1599 SDValue Arg = OutVals[realArgIdx];
1600 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1601 bool isByVal = Flags.isByVal();
1603 // Promote the value if needed.
1604 switch (VA.getLocInfo()) {
1605 default: llvm_unreachable("Unknown loc info!");
1606 case CCValAssign::Full: break;
1607 case CCValAssign::SExt:
1608 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1610 case CCValAssign::ZExt:
1611 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1613 case CCValAssign::AExt:
1614 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1616 case CCValAssign::BCvt:
1617 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1621 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1622 if (VA.needsCustom()) {
1623 if (VA.getLocVT() == MVT::v2f64) {
1624 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1625 DAG.getConstant(0, dl, MVT::i32));
1626 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1627 DAG.getConstant(1, dl, MVT::i32));
1629 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1630 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1632 VA = ArgLocs[++i]; // skip ahead to next loc
1633 if (VA.isRegLoc()) {
1634 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1635 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1637 assert(VA.isMemLoc());
1639 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1640 dl, DAG, VA, Flags));
1643 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1644 StackPtr, MemOpChains, Flags);
1646 } else if (VA.isRegLoc()) {
1647 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1648 assert(VA.getLocVT() == MVT::i32 &&
1649 "unexpected calling convention register assignment");
1650 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1651 "unexpected use of 'returned'");
1652 isThisReturn = true;
1654 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1655 } else if (isByVal) {
1656 assert(VA.isMemLoc());
1657 unsigned offset = 0;
1659 // True if this byval aggregate will be split between registers
1661 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1662 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1664 if (CurByValIdx < ByValArgsCount) {
1666 unsigned RegBegin, RegEnd;
1667 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1670 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1672 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1673 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1674 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1675 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1676 MachinePointerInfo(),
1677 false, false, false,
1678 DAG.InferPtrAlignment(AddArg));
1679 MemOpChains.push_back(Load.getValue(1));
1680 RegsToPass.push_back(std::make_pair(j, Load));
1683 // If parameter size outsides register area, "offset" value
1684 // helps us to calculate stack slot for remained part properly.
1685 offset = RegEnd - RegBegin;
1687 CCInfo.nextInRegsParam();
1690 if (Flags.getByValSize() > 4*offset) {
1691 auto PtrVT = getPointerTy(DAG.getDataLayout());
1692 unsigned LocMemOffset = VA.getLocMemOffset();
1693 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1694 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1695 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1696 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1697 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1699 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1702 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1703 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1704 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1707 } else if (!isSibCall) {
1708 assert(VA.isMemLoc());
1710 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1711 dl, DAG, VA, Flags));
1715 if (!MemOpChains.empty())
1716 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1718 // Build a sequence of copy-to-reg nodes chained together with token chain
1719 // and flag operands which copy the outgoing args into the appropriate regs.
1721 // Tail call byval lowering might overwrite argument registers so in case of
1722 // tail call optimization the copies to registers are lowered later.
1724 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1725 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1726 RegsToPass[i].second, InFlag);
1727 InFlag = Chain.getValue(1);
1730 // For tail calls lower the arguments to the 'real' stack slot.
1732 // Force all the incoming stack arguments to be loaded from the stack
1733 // before any new outgoing arguments are stored to the stack, because the
1734 // outgoing stack slots may alias the incoming argument stack slots, and
1735 // the alias isn't otherwise explicit. This is slightly more conservative
1736 // than necessary, because it means that each store effectively depends
1737 // on every argument instead of just those arguments it would clobber.
1739 // Do not flag preceding copytoreg stuff together with the following stuff.
1741 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1742 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1743 RegsToPass[i].second, InFlag);
1744 InFlag = Chain.getValue(1);
1749 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1750 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1751 // node so that legalize doesn't hack it.
1752 bool isDirect = false;
1753 bool isARMFunc = false;
1754 bool isLocalARMFunc = false;
1755 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1756 auto PtrVt = getPointerTy(DAG.getDataLayout());
1758 if (Subtarget->genLongCalls()) {
1759 assert((Subtarget->isTargetWindows() ||
1760 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1761 "long-calls with non-static relocation model!");
1762 // Handle a global address or an external symbol. If it's not one of
1763 // those, the target's already in a register, so we don't need to do
1765 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1766 const GlobalValue *GV = G->getGlobal();
1767 // Create a constant pool entry for the callee address
1768 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1769 ARMConstantPoolValue *CPV =
1770 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1772 // Get the address of the callee into a register
1773 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1774 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1775 Callee = DAG.getLoad(
1776 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1777 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1779 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1780 const char *Sym = S->getSymbol();
1782 // Create a constant pool entry for the callee address
1783 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1784 ARMConstantPoolValue *CPV =
1785 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1786 ARMPCLabelIndex, 0);
1787 // Get the address of the callee into a register
1788 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1789 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1790 Callee = DAG.getLoad(
1791 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1792 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1795 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1796 const GlobalValue *GV = G->getGlobal();
1798 bool isDef = GV->isStrongDefinitionForLinker();
1799 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1800 getTargetMachine().getRelocationModel() != Reloc::Static;
1801 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1802 // ARM call to a local ARM function is predicable.
1803 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1804 // tBX takes a register source operand.
1805 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1806 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1807 Callee = DAG.getNode(
1808 ARMISD::WrapperPIC, dl, PtrVt,
1809 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1810 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1811 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1812 false, false, true, 0);
1813 } else if (Subtarget->isTargetCOFF()) {
1814 assert(Subtarget->isTargetWindows() &&
1815 "Windows is the only supported COFF target");
1816 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1817 ? ARMII::MO_DLLIMPORT
1818 : ARMII::MO_NO_FLAG;
1820 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1821 if (GV->hasDLLImportStorageClass())
1823 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1824 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1825 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1826 false, false, false, 0);
1828 // On ELF targets for PIC code, direct calls should go through the PLT
1829 unsigned OpFlags = 0;
1830 if (Subtarget->isTargetELF() &&
1831 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1832 OpFlags = ARMII::MO_PLT;
1833 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1835 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1837 bool isStub = Subtarget->isTargetMachO() &&
1838 getTargetMachine().getRelocationModel() != Reloc::Static;
1839 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1840 // tBX takes a register source operand.
1841 const char *Sym = S->getSymbol();
1842 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1843 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1844 ARMConstantPoolValue *CPV =
1845 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1846 ARMPCLabelIndex, 4);
1847 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1848 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1849 Callee = DAG.getLoad(
1850 PtrVt, dl, DAG.getEntryNode(), CPAddr,
1851 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1853 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1854 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1856 unsigned OpFlags = 0;
1857 // On ELF targets for PIC code, direct calls should go through the PLT
1858 if (Subtarget->isTargetELF() &&
1859 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1860 OpFlags = ARMII::MO_PLT;
1861 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1865 // FIXME: handle tail calls differently.
1867 if (Subtarget->isThumb()) {
1868 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1869 CallOpc = ARMISD::CALL_NOLINK;
1871 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1873 if (!isDirect && !Subtarget->hasV5TOps())
1874 CallOpc = ARMISD::CALL_NOLINK;
1875 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1876 // Emit regular call when code size is the priority
1877 !MF.getFunction()->optForMinSize())
1878 // "mov lr, pc; b _foo" to avoid confusing the RSP
1879 CallOpc = ARMISD::CALL_NOLINK;
1881 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1884 std::vector<SDValue> Ops;
1885 Ops.push_back(Chain);
1886 Ops.push_back(Callee);
1888 // Add argument registers to the end of the list so that they are known live
1890 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1891 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1892 RegsToPass[i].second.getValueType()));
1894 // Add a register mask operand representing the call-preserved registers.
1896 const uint32_t *Mask;
1897 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1899 // For 'this' returns, use the R0-preserving mask if applicable
1900 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1902 // Set isThisReturn to false if the calling convention is not one that
1903 // allows 'returned' to be modeled in this way, so LowerCallResult does
1904 // not try to pass 'this' straight through
1905 isThisReturn = false;
1906 Mask = ARI->getCallPreservedMask(MF, CallConv);
1909 Mask = ARI->getCallPreservedMask(MF, CallConv);
1911 assert(Mask && "Missing call preserved mask for calling convention");
1912 Ops.push_back(DAG.getRegisterMask(Mask));
1915 if (InFlag.getNode())
1916 Ops.push_back(InFlag);
1918 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1920 MF.getFrameInfo()->setHasTailCall();
1921 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1924 // Returns a chain and a flag for retval copy to use.
1925 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1926 InFlag = Chain.getValue(1);
1928 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1929 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1931 InFlag = Chain.getValue(1);
1933 // Handle result values, copying them out of physregs into vregs that we
1935 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1936 InVals, isThisReturn,
1937 isThisReturn ? OutVals[0] : SDValue());
1940 /// HandleByVal - Every parameter *after* a byval parameter is passed
1941 /// on the stack. Remember the next parameter register to allocate,
1942 /// and then confiscate the rest of the parameter registers to insure
1944 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1945 unsigned Align) const {
1946 assert((State->getCallOrPrologue() == Prologue ||
1947 State->getCallOrPrologue() == Call) &&
1948 "unhandled ParmContext");
1950 // Byval (as with any stack) slots are always at least 4 byte aligned.
1951 Align = std::max(Align, 4U);
1953 unsigned Reg = State->AllocateReg(GPRArgRegs);
1957 unsigned AlignInRegs = Align / 4;
1958 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1959 for (unsigned i = 0; i < Waste; ++i)
1960 Reg = State->AllocateReg(GPRArgRegs);
1965 unsigned Excess = 4 * (ARM::R4 - Reg);
1967 // Special case when NSAA != SP and parameter size greater than size of
1968 // all remained GPR regs. In that case we can't split parameter, we must
1969 // send it to stack. We also must set NCRN to R4, so waste all
1970 // remained registers.
1971 const unsigned NSAAOffset = State->getNextStackOffset();
1972 if (NSAAOffset != 0 && Size > Excess) {
1973 while (State->AllocateReg(GPRArgRegs))
1978 // First register for byval parameter is the first register that wasn't
1979 // allocated before this method call, so it would be "reg".
1980 // If parameter is small enough to be saved in range [reg, r4), then
1981 // the end (first after last) register would be reg + param-size-in-regs,
1982 // else parameter would be splitted between registers and stack,
1983 // end register would be r4 in this case.
1984 unsigned ByValRegBegin = Reg;
1985 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1986 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1987 // Note, first register is allocated in the beginning of function already,
1988 // allocate remained amount of registers we need.
1989 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1990 State->AllocateReg(GPRArgRegs);
1991 // A byval parameter that is split between registers and memory needs its
1992 // size truncated here.
1993 // In the case where the entire structure fits in registers, we set the
1994 // size in memory to zero.
1995 Size = std::max<int>(Size - Excess, 0);
1998 /// MatchingStackOffset - Return true if the given stack call argument is
1999 /// already available in the same position (relatively) of the caller's
2000 /// incoming argument stack.
2002 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2003 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2004 const TargetInstrInfo *TII) {
2005 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2007 if (Arg.getOpcode() == ISD::CopyFromReg) {
2008 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2009 if (!TargetRegisterInfo::isVirtualRegister(VR))
2011 MachineInstr *Def = MRI->getVRegDef(VR);
2014 if (!Flags.isByVal()) {
2015 if (!TII->isLoadFromStackSlot(Def, FI))
2020 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2021 if (Flags.isByVal())
2022 // ByVal argument is passed in as a pointer but it's now being
2023 // dereferenced. e.g.
2024 // define @foo(%struct.X* %A) {
2025 // tail call @bar(%struct.X* byval %A)
2028 SDValue Ptr = Ld->getBasePtr();
2029 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2032 FI = FINode->getIndex();
2036 assert(FI != INT_MAX);
2037 if (!MFI->isFixedObjectIndex(FI))
2039 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2042 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2043 /// for tail call optimization. Targets which want to do tail call
2044 /// optimization should implement this function.
2046 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2047 CallingConv::ID CalleeCC,
2049 bool isCalleeStructRet,
2050 bool isCallerStructRet,
2051 const SmallVectorImpl<ISD::OutputArg> &Outs,
2052 const SmallVectorImpl<SDValue> &OutVals,
2053 const SmallVectorImpl<ISD::InputArg> &Ins,
2054 SelectionDAG& DAG) const {
2055 const Function *CallerF = DAG.getMachineFunction().getFunction();
2056 CallingConv::ID CallerCC = CallerF->getCallingConv();
2057 bool CCMatch = CallerCC == CalleeCC;
2059 assert(Subtarget->supportsTailCall());
2061 // Look for obvious safe cases to perform tail call optimization that do not
2062 // require ABI changes. This is what gcc calls sibcall.
2064 // Do not sibcall optimize vararg calls unless the call site is not passing
2066 if (isVarArg && !Outs.empty())
2069 // Exception-handling functions need a special set of instructions to indicate
2070 // a return to the hardware. Tail-calling another function would probably
2072 if (CallerF->hasFnAttribute("interrupt"))
2075 // Also avoid sibcall optimization if either caller or callee uses struct
2076 // return semantics.
2077 if (isCalleeStructRet || isCallerStructRet)
2080 // Externally-defined functions with weak linkage should not be
2081 // tail-called on ARM when the OS does not support dynamic
2082 // pre-emption of symbols, as the AAELF spec requires normal calls
2083 // to undefined weak functions to be replaced with a NOP or jump to the
2084 // next instruction. The behaviour of branch instructions in this
2085 // situation (as used for tail calls) is implementation-defined, so we
2086 // cannot rely on the linker replacing the tail call with a return.
2087 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2088 const GlobalValue *GV = G->getGlobal();
2089 const Triple &TT = getTargetMachine().getTargetTriple();
2090 if (GV->hasExternalWeakLinkage() &&
2091 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2095 // If the calling conventions do not match, then we'd better make sure the
2096 // results are returned in the same way as what the caller expects.
2098 SmallVector<CCValAssign, 16> RVLocs1;
2099 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2100 *DAG.getContext(), Call);
2101 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2103 SmallVector<CCValAssign, 16> RVLocs2;
2104 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2105 *DAG.getContext(), Call);
2106 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2108 if (RVLocs1.size() != RVLocs2.size())
2110 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2111 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2113 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2115 if (RVLocs1[i].isRegLoc()) {
2116 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2119 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2125 // If Caller's vararg or byval argument has been split between registers and
2126 // stack, do not perform tail call, since part of the argument is in caller's
2128 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2129 getInfo<ARMFunctionInfo>();
2130 if (AFI_Caller->getArgRegsSaveSize())
2133 // If the callee takes no arguments then go on to check the results of the
2135 if (!Outs.empty()) {
2136 // Check if stack adjustment is needed. For now, do not do this if any
2137 // argument is passed on the stack.
2138 SmallVector<CCValAssign, 16> ArgLocs;
2139 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2140 *DAG.getContext(), Call);
2141 CCInfo.AnalyzeCallOperands(Outs,
2142 CCAssignFnForNode(CalleeCC, false, isVarArg));
2143 if (CCInfo.getNextStackOffset()) {
2144 MachineFunction &MF = DAG.getMachineFunction();
2146 // Check if the arguments are already laid out in the right way as
2147 // the caller's fixed stack objects.
2148 MachineFrameInfo *MFI = MF.getFrameInfo();
2149 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2150 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2151 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2153 ++i, ++realArgIdx) {
2154 CCValAssign &VA = ArgLocs[i];
2155 EVT RegVT = VA.getLocVT();
2156 SDValue Arg = OutVals[realArgIdx];
2157 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2158 if (VA.getLocInfo() == CCValAssign::Indirect)
2160 if (VA.needsCustom()) {
2161 // f64 and vector types are split into multiple registers or
2162 // register/stack-slot combinations. The types will not match
2163 // the registers; give up on memory f64 refs until we figure
2164 // out what to do about this.
2167 if (!ArgLocs[++i].isRegLoc())
2169 if (RegVT == MVT::v2f64) {
2170 if (!ArgLocs[++i].isRegLoc())
2172 if (!ArgLocs[++i].isRegLoc())
2175 } else if (!VA.isRegLoc()) {
2176 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2188 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2189 MachineFunction &MF, bool isVarArg,
2190 const SmallVectorImpl<ISD::OutputArg> &Outs,
2191 LLVMContext &Context) const {
2192 SmallVector<CCValAssign, 16> RVLocs;
2193 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2194 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2198 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2199 SDLoc DL, SelectionDAG &DAG) {
2200 const MachineFunction &MF = DAG.getMachineFunction();
2201 const Function *F = MF.getFunction();
2203 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2205 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2206 // version of the "preferred return address". These offsets affect the return
2207 // instruction if this is a return from PL1 without hypervisor extensions.
2208 // IRQ/FIQ: +4 "subs pc, lr, #4"
2209 // SWI: 0 "subs pc, lr, #0"
2210 // ABORT: +4 "subs pc, lr, #4"
2211 // UNDEF: +4/+2 "subs pc, lr, #0"
2212 // UNDEF varies depending on where the exception came from ARM or Thumb
2213 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2216 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2219 else if (IntKind == "SWI" || IntKind == "UNDEF")
2222 report_fatal_error("Unsupported interrupt attribute. If present, value "
2223 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2225 RetOps.insert(RetOps.begin() + 1,
2226 DAG.getConstant(LROffset, DL, MVT::i32, false));
2228 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2232 ARMTargetLowering::LowerReturn(SDValue Chain,
2233 CallingConv::ID CallConv, bool isVarArg,
2234 const SmallVectorImpl<ISD::OutputArg> &Outs,
2235 const SmallVectorImpl<SDValue> &OutVals,
2236 SDLoc dl, SelectionDAG &DAG) const {
2238 // CCValAssign - represent the assignment of the return value to a location.
2239 SmallVector<CCValAssign, 16> RVLocs;
2241 // CCState - Info about the registers and stack slots.
2242 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2243 *DAG.getContext(), Call);
2245 // Analyze outgoing return values.
2246 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2250 SmallVector<SDValue, 4> RetOps;
2251 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2252 bool isLittleEndian = Subtarget->isLittle();
2254 MachineFunction &MF = DAG.getMachineFunction();
2255 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2256 AFI->setReturnRegsCount(RVLocs.size());
2258 // Copy the result values into the output registers.
2259 for (unsigned i = 0, realRVLocIdx = 0;
2261 ++i, ++realRVLocIdx) {
2262 CCValAssign &VA = RVLocs[i];
2263 assert(VA.isRegLoc() && "Can only return in registers!");
2265 SDValue Arg = OutVals[realRVLocIdx];
2267 switch (VA.getLocInfo()) {
2268 default: llvm_unreachable("Unknown loc info!");
2269 case CCValAssign::Full: break;
2270 case CCValAssign::BCvt:
2271 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2275 if (VA.needsCustom()) {
2276 if (VA.getLocVT() == MVT::v2f64) {
2277 // Extract the first half and return it in two registers.
2278 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2279 DAG.getConstant(0, dl, MVT::i32));
2280 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2281 DAG.getVTList(MVT::i32, MVT::i32), Half);
2283 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2284 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2286 Flag = Chain.getValue(1);
2287 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2288 VA = RVLocs[++i]; // skip ahead to next loc
2289 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2290 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2292 Flag = Chain.getValue(1);
2293 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2294 VA = RVLocs[++i]; // skip ahead to next loc
2296 // Extract the 2nd half and fall through to handle it as an f64 value.
2297 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2298 DAG.getConstant(1, dl, MVT::i32));
2300 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2302 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2303 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2304 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2305 fmrrd.getValue(isLittleEndian ? 0 : 1),
2307 Flag = Chain.getValue(1);
2308 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2309 VA = RVLocs[++i]; // skip ahead to next loc
2310 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2311 fmrrd.getValue(isLittleEndian ? 1 : 0),
2314 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2316 // Guarantee that all emitted copies are
2317 // stuck together, avoiding something bad.
2318 Flag = Chain.getValue(1);
2319 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2322 // Update chain and glue.
2325 RetOps.push_back(Flag);
2327 // CPUs which aren't M-class use a special sequence to return from
2328 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2329 // though we use "subs pc, lr, #N").
2331 // M-class CPUs actually use a normal return sequence with a special
2332 // (hardware-provided) value in LR, so the normal code path works.
2333 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2334 !Subtarget->isMClass()) {
2335 if (Subtarget->isThumb1Only())
2336 report_fatal_error("interrupt attribute is not supported in Thumb1");
2337 return LowerInterruptReturn(RetOps, dl, DAG);
2340 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2343 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2344 if (N->getNumValues() != 1)
2346 if (!N->hasNUsesOfValue(1, 0))
2349 SDValue TCChain = Chain;
2350 SDNode *Copy = *N->use_begin();
2351 if (Copy->getOpcode() == ISD::CopyToReg) {
2352 // If the copy has a glue operand, we conservatively assume it isn't safe to
2353 // perform a tail call.
2354 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2356 TCChain = Copy->getOperand(0);
2357 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2358 SDNode *VMov = Copy;
2359 // f64 returned in a pair of GPRs.
2360 SmallPtrSet<SDNode*, 2> Copies;
2361 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2363 if (UI->getOpcode() != ISD::CopyToReg)
2367 if (Copies.size() > 2)
2370 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2372 SDValue UseChain = UI->getOperand(0);
2373 if (Copies.count(UseChain.getNode()))
2377 // We are at the top of this chain.
2378 // If the copy has a glue operand, we conservatively assume it
2379 // isn't safe to perform a tail call.
2380 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2386 } else if (Copy->getOpcode() == ISD::BITCAST) {
2387 // f32 returned in a single GPR.
2388 if (!Copy->hasOneUse())
2390 Copy = *Copy->use_begin();
2391 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2393 // If the copy has a glue operand, we conservatively assume it isn't safe to
2394 // perform a tail call.
2395 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2397 TCChain = Copy->getOperand(0);
2402 bool HasRet = false;
2403 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2405 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2406 UI->getOpcode() != ARMISD::INTRET_FLAG)
2418 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2419 if (!Subtarget->supportsTailCall())
2423 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2424 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2430 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2431 // and pass the lower and high parts through.
2432 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2434 SDValue WriteValue = Op->getOperand(2);
2436 // This function is only supposed to be called for i64 type argument.
2437 assert(WriteValue.getValueType() == MVT::i64
2438 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2440 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2441 DAG.getConstant(0, DL, MVT::i32));
2442 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2443 DAG.getConstant(1, DL, MVT::i32));
2444 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2445 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2448 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2449 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2450 // one of the above mentioned nodes. It has to be wrapped because otherwise
2451 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2452 // be used to form addressing mode. These wrapped nodes will be selected
2454 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2455 EVT PtrVT = Op.getValueType();
2456 // FIXME there is no actual debug info here
2458 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2460 if (CP->isMachineConstantPoolEntry())
2461 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2462 CP->getAlignment());
2464 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2465 CP->getAlignment());
2466 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2469 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2470 return MachineJumpTableInfo::EK_Inline;
2473 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2474 SelectionDAG &DAG) const {
2475 MachineFunction &MF = DAG.getMachineFunction();
2476 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2477 unsigned ARMPCLabelIndex = 0;
2479 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2480 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2481 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2483 if (RelocM == Reloc::Static) {
2484 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2486 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2487 ARMPCLabelIndex = AFI->createPICLabelUId();
2488 ARMConstantPoolValue *CPV =
2489 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2490 ARMCP::CPBlockAddress, PCAdj);
2491 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2493 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2495 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2496 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2497 false, false, false, 0);
2498 if (RelocM == Reloc::Static)
2500 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2501 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2504 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2506 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2507 SelectionDAG &DAG) const {
2509 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2510 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2511 MachineFunction &MF = DAG.getMachineFunction();
2512 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2513 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2514 ARMConstantPoolValue *CPV =
2515 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2516 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2517 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2518 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2520 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2521 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2522 false, false, false, 0);
2523 SDValue Chain = Argument.getValue(1);
2525 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2526 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2528 // call __tls_get_addr.
2531 Entry.Node = Argument;
2532 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2533 Args.push_back(Entry);
2535 // FIXME: is there useful debug info available here?
2536 TargetLowering::CallLoweringInfo CLI(DAG);
2537 CLI.setDebugLoc(dl).setChain(Chain)
2538 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2539 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2542 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2543 return CallResult.first;
2546 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2547 // "local exec" model.
2549 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2551 TLSModel::Model model) const {
2552 const GlobalValue *GV = GA->getGlobal();
2555 SDValue Chain = DAG.getEntryNode();
2556 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2557 // Get the Thread Pointer
2558 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2560 if (model == TLSModel::InitialExec) {
2561 MachineFunction &MF = DAG.getMachineFunction();
2562 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2563 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2564 // Initial exec model.
2565 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2566 ARMConstantPoolValue *CPV =
2567 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2568 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2570 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2571 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2572 Offset = DAG.getLoad(
2573 PtrVT, dl, Chain, Offset,
2574 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2576 Chain = Offset.getValue(1);
2578 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2579 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2581 Offset = DAG.getLoad(
2582 PtrVT, dl, Chain, Offset,
2583 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2587 assert(model == TLSModel::LocalExec);
2588 ARMConstantPoolValue *CPV =
2589 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2590 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2591 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2592 Offset = DAG.getLoad(
2593 PtrVT, dl, Chain, Offset,
2594 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2598 // The address of the thread local variable is the add of the thread
2599 // pointer with the offset of the variable.
2600 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2604 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2605 // TODO: implement the "local dynamic" model
2606 assert(Subtarget->isTargetELF() &&
2607 "TLS not implemented for non-ELF targets");
2608 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2609 if (DAG.getTarget().Options.EmulatedTLS)
2610 return LowerToTLSEmulatedModel(GA, DAG);
2612 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2615 case TLSModel::GeneralDynamic:
2616 case TLSModel::LocalDynamic:
2617 return LowerToTLSGeneralDynamicModel(GA, DAG);
2618 case TLSModel::InitialExec:
2619 case TLSModel::LocalExec:
2620 return LowerToTLSExecModels(GA, DAG, model);
2622 llvm_unreachable("bogus TLS model");
2625 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2626 SelectionDAG &DAG) const {
2627 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2629 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2630 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2631 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2632 ARMConstantPoolValue *CPV =
2633 ARMConstantPoolConstant::Create(GV,
2634 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2635 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2636 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2637 SDValue Result = DAG.getLoad(
2638 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2639 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2641 SDValue Chain = Result.getValue(1);
2642 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2643 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2645 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2646 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2647 false, false, false, 0);
2651 // If we have T2 ops, we can materialize the address directly via movt/movw
2652 // pair. This is always cheaper.
2653 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2655 // FIXME: Once remat is capable of dealing with instructions with register
2656 // operands, expand this into two nodes.
2657 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2658 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2660 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2661 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2663 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2664 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2669 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2670 SelectionDAG &DAG) const {
2671 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2673 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2674 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2676 if (Subtarget->useMovt(DAG.getMachineFunction()))
2679 // FIXME: Once remat is capable of dealing with instructions with register
2680 // operands, expand this into multiple nodes
2682 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2684 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2685 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2687 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2688 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2689 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2690 false, false, false, 0);
2694 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2695 SelectionDAG &DAG) const {
2696 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2697 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2698 "Windows on ARM expects to use movw/movt");
2700 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2701 const ARMII::TOF TargetFlags =
2702 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2703 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2709 // FIXME: Once remat is capable of dealing with instructions with register
2710 // operands, expand this into two nodes.
2711 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2712 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2714 if (GV->hasDLLImportStorageClass())
2715 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2716 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2717 false, false, false, 0);
2721 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2722 SelectionDAG &DAG) const {
2723 assert(Subtarget->isTargetELF() &&
2724 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2725 MachineFunction &MF = DAG.getMachineFunction();
2726 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2727 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2728 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2730 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2731 ARMConstantPoolValue *CPV =
2732 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2733 ARMPCLabelIndex, PCAdj);
2734 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2735 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2737 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2738 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2739 false, false, false, 0);
2740 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2741 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2745 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2747 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2748 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2749 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2750 Op.getOperand(1), Val);
2754 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2756 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2757 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2760 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2761 SelectionDAG &DAG) const {
2763 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2768 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2769 const ARMSubtarget *Subtarget) const {
2770 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2773 default: return SDValue(); // Don't custom lower most intrinsics.
2774 case Intrinsic::arm_rbit: {
2775 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2776 "RBIT intrinsic must have i32 type!");
2777 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2779 case Intrinsic::arm_thread_pointer: {
2780 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2781 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2783 case Intrinsic::eh_sjlj_lsda: {
2784 MachineFunction &MF = DAG.getMachineFunction();
2785 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2786 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2787 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2788 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2790 unsigned PCAdj = (RelocM != Reloc::PIC_)
2791 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2792 ARMConstantPoolValue *CPV =
2793 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2794 ARMCP::CPLSDA, PCAdj);
2795 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2796 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2797 SDValue Result = DAG.getLoad(
2798 PtrVT, dl, DAG.getEntryNode(), CPAddr,
2799 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2802 if (RelocM == Reloc::PIC_) {
2803 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2804 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2808 case Intrinsic::arm_neon_vmulls:
2809 case Intrinsic::arm_neon_vmullu: {
2810 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2811 ? ARMISD::VMULLs : ARMISD::VMULLu;
2812 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2813 Op.getOperand(1), Op.getOperand(2));
2815 case Intrinsic::arm_neon_vminnm:
2816 case Intrinsic::arm_neon_vmaxnm: {
2817 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2818 ? ISD::FMINNUM : ISD::FMAXNUM;
2819 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2820 Op.getOperand(1), Op.getOperand(2));
2822 case Intrinsic::arm_neon_vminu:
2823 case Intrinsic::arm_neon_vmaxu: {
2824 if (Op.getValueType().isFloatingPoint())
2826 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2827 ? ISD::UMIN : ISD::UMAX;
2828 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2829 Op.getOperand(1), Op.getOperand(2));
2831 case Intrinsic::arm_neon_vmins:
2832 case Intrinsic::arm_neon_vmaxs: {
2833 // v{min,max}s is overloaded between signed integers and floats.
2834 if (!Op.getValueType().isFloatingPoint()) {
2835 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2836 ? ISD::SMIN : ISD::SMAX;
2837 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2838 Op.getOperand(1), Op.getOperand(2));
2840 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2841 ? ISD::FMINNAN : ISD::FMAXNAN;
2842 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2843 Op.getOperand(1), Op.getOperand(2));
2848 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2849 const ARMSubtarget *Subtarget) {
2850 // FIXME: handle "fence singlethread" more efficiently.
2852 if (!Subtarget->hasDataBarrier()) {
2853 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2854 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2856 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2857 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2858 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2859 DAG.getConstant(0, dl, MVT::i32));
2862 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2863 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2864 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2865 if (Subtarget->isMClass()) {
2866 // Only a full system barrier exists in the M-class architectures.
2867 Domain = ARM_MB::SY;
2868 } else if (Subtarget->isSwift() && Ord == Release) {
2869 // Swift happens to implement ISHST barriers in a way that's compatible with
2870 // Release semantics but weaker than ISH so we'd be fools not to use
2871 // it. Beware: other processors probably don't!
2872 Domain = ARM_MB::ISHST;
2875 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2876 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2877 DAG.getConstant(Domain, dl, MVT::i32));
2880 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2881 const ARMSubtarget *Subtarget) {
2882 // ARM pre v5TE and Thumb1 does not have preload instructions.
2883 if (!(Subtarget->isThumb2() ||
2884 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2885 // Just preserve the chain.
2886 return Op.getOperand(0);
2889 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2891 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2892 // ARMv7 with MP extension has PLDW.
2893 return Op.getOperand(0);
2895 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2896 if (Subtarget->isThumb()) {
2898 isRead = ~isRead & 1;
2899 isData = ~isData & 1;
2902 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2903 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2904 DAG.getConstant(isData, dl, MVT::i32));
2907 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2908 MachineFunction &MF = DAG.getMachineFunction();
2909 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2911 // vastart just stores the address of the VarArgsFrameIndex slot into the
2912 // memory location argument.
2914 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2915 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2916 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2917 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2918 MachinePointerInfo(SV), false, false, 0);
2922 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2923 SDValue &Root, SelectionDAG &DAG,
2925 MachineFunction &MF = DAG.getMachineFunction();
2926 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2928 const TargetRegisterClass *RC;
2929 if (AFI->isThumb1OnlyFunction())
2930 RC = &ARM::tGPRRegClass;
2932 RC = &ARM::GPRRegClass;
2934 // Transform the arguments stored in physical registers into virtual ones.
2935 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2936 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2939 if (NextVA.isMemLoc()) {
2940 MachineFrameInfo *MFI = MF.getFrameInfo();
2941 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2943 // Create load node to retrieve arguments from the stack.
2944 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2945 ArgValue2 = DAG.getLoad(
2946 MVT::i32, dl, Root, FIN,
2947 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2950 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2951 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2953 if (!Subtarget->isLittle())
2954 std::swap (ArgValue, ArgValue2);
2955 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2958 // The remaining GPRs hold either the beginning of variable-argument
2959 // data, or the beginning of an aggregate passed by value (usually
2960 // byval). Either way, we allocate stack slots adjacent to the data
2961 // provided by our caller, and store the unallocated registers there.
2962 // If this is a variadic function, the va_list pointer will begin with
2963 // these values; otherwise, this reassembles a (byval) structure that
2964 // was split between registers and memory.
2965 // Return: The frame index registers were stored into.
2967 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2968 SDLoc dl, SDValue &Chain,
2969 const Value *OrigArg,
2970 unsigned InRegsParamRecordIdx,
2972 unsigned ArgSize) const {
2973 // Currently, two use-cases possible:
2974 // Case #1. Non-var-args function, and we meet first byval parameter.
2975 // Setup first unallocated register as first byval register;
2976 // eat all remained registers
2977 // (these two actions are performed by HandleByVal method).
2978 // Then, here, we initialize stack frame with
2979 // "store-reg" instructions.
2980 // Case #2. Var-args function, that doesn't contain byval parameters.
2981 // The same: eat all remained unallocated registers,
2982 // initialize stack frame.
2984 MachineFunction &MF = DAG.getMachineFunction();
2985 MachineFrameInfo *MFI = MF.getFrameInfo();
2986 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2987 unsigned RBegin, REnd;
2988 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2989 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2991 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2992 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2997 ArgOffset = -4 * (ARM::R4 - RBegin);
2999 auto PtrVT = getPointerTy(DAG.getDataLayout());
3000 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3001 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3003 SmallVector<SDValue, 4> MemOps;
3004 const TargetRegisterClass *RC =
3005 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3007 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3008 unsigned VReg = MF.addLiveIn(Reg, RC);
3009 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3011 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3012 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3013 MemOps.push_back(Store);
3014 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3017 if (!MemOps.empty())
3018 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3022 // Setup stack frame, the va_list pointer will start from.
3024 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3025 SDLoc dl, SDValue &Chain,
3027 unsigned TotalArgRegsSaveSize,
3028 bool ForceMutable) const {
3029 MachineFunction &MF = DAG.getMachineFunction();
3030 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3032 // Try to store any remaining integer argument regs
3033 // to their spots on the stack so that they may be loaded by deferencing
3034 // the result of va_next.
3035 // If there is no regs to be stored, just point address after last
3036 // argument passed via stack.
3037 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3038 CCInfo.getInRegsParamsCount(),
3039 CCInfo.getNextStackOffset(), 4);
3040 AFI->setVarArgsFrameIndex(FrameIndex);
3044 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3045 CallingConv::ID CallConv, bool isVarArg,
3046 const SmallVectorImpl<ISD::InputArg>
3048 SDLoc dl, SelectionDAG &DAG,
3049 SmallVectorImpl<SDValue> &InVals)
3051 MachineFunction &MF = DAG.getMachineFunction();
3052 MachineFrameInfo *MFI = MF.getFrameInfo();
3054 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3056 // Assign locations to all of the incoming arguments.
3057 SmallVector<CCValAssign, 16> ArgLocs;
3058 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3059 *DAG.getContext(), Prologue);
3060 CCInfo.AnalyzeFormalArguments(Ins,
3061 CCAssignFnForNode(CallConv, /* Return*/ false,
3064 SmallVector<SDValue, 16> ArgValues;
3066 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3067 unsigned CurArgIdx = 0;
3069 // Initially ArgRegsSaveSize is zero.
3070 // Then we increase this value each time we meet byval parameter.
3071 // We also increase this value in case of varargs function.
3072 AFI->setArgRegsSaveSize(0);
3074 // Calculate the amount of stack space that we need to allocate to store
3075 // byval and variadic arguments that are passed in registers.
3076 // We need to know this before we allocate the first byval or variadic
3077 // argument, as they will be allocated a stack slot below the CFA (Canonical
3078 // Frame Address, the stack pointer at entry to the function).
3079 unsigned ArgRegBegin = ARM::R4;
3080 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3081 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3084 CCValAssign &VA = ArgLocs[i];
3085 unsigned Index = VA.getValNo();
3086 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3087 if (!Flags.isByVal())
3090 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3091 unsigned RBegin, REnd;
3092 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3093 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3095 CCInfo.nextInRegsParam();
3097 CCInfo.rewindByValRegsInfo();
3099 int lastInsIndex = -1;
3100 if (isVarArg && MFI->hasVAStart()) {
3101 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3102 if (RegIdx != array_lengthof(GPRArgRegs))
3103 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3106 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3107 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3108 auto PtrVT = getPointerTy(DAG.getDataLayout());
3110 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3111 CCValAssign &VA = ArgLocs[i];
3112 if (Ins[VA.getValNo()].isOrigArg()) {
3113 std::advance(CurOrigArg,
3114 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3115 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3117 // Arguments stored in registers.
3118 if (VA.isRegLoc()) {
3119 EVT RegVT = VA.getLocVT();
3121 if (VA.needsCustom()) {
3122 // f64 and vector types are split up into multiple registers or
3123 // combinations of registers and stack slots.
3124 if (VA.getLocVT() == MVT::v2f64) {
3125 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3127 VA = ArgLocs[++i]; // skip ahead to next loc
3129 if (VA.isMemLoc()) {
3130 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3131 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3132 ArgValue2 = DAG.getLoad(
3133 MVT::f64, dl, Chain, FIN,
3134 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3135 false, false, false, 0);
3137 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3140 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3141 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3142 ArgValue, ArgValue1,
3143 DAG.getIntPtrConstant(0, dl));
3144 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3145 ArgValue, ArgValue2,
3146 DAG.getIntPtrConstant(1, dl));
3148 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3151 const TargetRegisterClass *RC;
3153 if (RegVT == MVT::f32)
3154 RC = &ARM::SPRRegClass;
3155 else if (RegVT == MVT::f64)
3156 RC = &ARM::DPRRegClass;
3157 else if (RegVT == MVT::v2f64)
3158 RC = &ARM::QPRRegClass;
3159 else if (RegVT == MVT::i32)
3160 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3161 : &ARM::GPRRegClass;
3163 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3165 // Transform the arguments in physical registers into virtual ones.
3166 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3167 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3170 // If this is an 8 or 16-bit value, it is really passed promoted
3171 // to 32 bits. Insert an assert[sz]ext to capture this, then
3172 // truncate to the right size.
3173 switch (VA.getLocInfo()) {
3174 default: llvm_unreachable("Unknown loc info!");
3175 case CCValAssign::Full: break;
3176 case CCValAssign::BCvt:
3177 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3179 case CCValAssign::SExt:
3180 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3181 DAG.getValueType(VA.getValVT()));
3182 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3184 case CCValAssign::ZExt:
3185 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3186 DAG.getValueType(VA.getValVT()));
3187 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3191 InVals.push_back(ArgValue);
3193 } else { // VA.isRegLoc()
3196 assert(VA.isMemLoc());
3197 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3199 int index = VA.getValNo();
3201 // Some Ins[] entries become multiple ArgLoc[] entries.
3202 // Process them only once.
3203 if (index != lastInsIndex)
3205 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3206 // FIXME: For now, all byval parameter objects are marked mutable.
3207 // This can be changed with more analysis.
3208 // In case of tail call optimization mark all arguments mutable.
3209 // Since they could be overwritten by lowering of arguments in case of
3211 if (Flags.isByVal()) {
3212 assert(Ins[index].isOrigArg() &&
3213 "Byval arguments cannot be implicit");
3214 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3216 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3217 CurByValIndex, VA.getLocMemOffset(),
3218 Flags.getByValSize());
3219 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3220 CCInfo.nextInRegsParam();
3222 unsigned FIOffset = VA.getLocMemOffset();
3223 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3226 // Create load nodes to retrieve arguments from the stack.
3227 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3228 InVals.push_back(DAG.getLoad(
3229 VA.getValVT(), dl, Chain, FIN,
3230 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3231 false, false, false, 0));
3233 lastInsIndex = index;
3239 if (isVarArg && MFI->hasVAStart())
3240 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3241 CCInfo.getNextStackOffset(),
3242 TotalArgRegsSaveSize);
3244 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3249 /// isFloatingPointZero - Return true if this is +0.0.
3250 static bool isFloatingPointZero(SDValue Op) {
3251 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3252 return CFP->getValueAPF().isPosZero();
3253 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3254 // Maybe this has already been legalized into the constant pool?
3255 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3256 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3257 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3258 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3259 return CFP->getValueAPF().isPosZero();
3261 } else if (Op->getOpcode() == ISD::BITCAST &&
3262 Op->getValueType(0) == MVT::f64) {
3263 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3264 // created by LowerConstantFP().
3265 SDValue BitcastOp = Op->getOperand(0);
3266 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3267 SDValue MoveOp = BitcastOp->getOperand(0);
3268 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3269 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3277 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3278 /// the given operands.
3280 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3281 SDValue &ARMcc, SelectionDAG &DAG,
3283 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3284 unsigned C = RHSC->getZExtValue();
3285 if (!isLegalICmpImmediate(C)) {
3286 // Constant does not fit, try adjusting it by one?
3291 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3292 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3293 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3298 if (C != 0 && isLegalICmpImmediate(C-1)) {
3299 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3300 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3305 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3306 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3307 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3312 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3313 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3314 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3321 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3322 ARMISD::NodeType CompareType;
3325 CompareType = ARMISD::CMP;
3330 CompareType = ARMISD::CMPZ;
3333 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3334 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3337 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3339 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3341 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3343 if (!isFloatingPointZero(RHS))
3344 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3346 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3347 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3350 /// duplicateCmp - Glue values can have only one use, so this function
3351 /// duplicates a comparison node.
3353 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3354 unsigned Opc = Cmp.getOpcode();
3356 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3357 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3359 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3360 Cmp = Cmp.getOperand(0);
3361 Opc = Cmp.getOpcode();
3362 if (Opc == ARMISD::CMPFP)
3363 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3365 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3366 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3368 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3371 std::pair<SDValue, SDValue>
3372 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3373 SDValue &ARMcc) const {
3374 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3376 SDValue Value, OverflowCmp;
3377 SDValue LHS = Op.getOperand(0);
3378 SDValue RHS = Op.getOperand(1);
3381 // FIXME: We are currently always generating CMPs because we don't support
3382 // generating CMN through the backend. This is not as good as the natural
3383 // CMP case because it causes a register dependency and cannot be folded
3386 switch (Op.getOpcode()) {
3388 llvm_unreachable("Unknown overflow instruction!");
3390 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3391 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3392 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3395 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3396 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3397 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3400 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3401 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3402 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3405 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3406 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3407 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3411 return std::make_pair(Value, OverflowCmp);
3416 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3417 // Let legalize expand this if it isn't a legal type yet.
3418 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3421 SDValue Value, OverflowCmp;
3423 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3424 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3426 // We use 0 and 1 as false and true values.
3427 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3428 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3429 EVT VT = Op.getValueType();
3431 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3432 ARMcc, CCR, OverflowCmp);
3434 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3435 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3439 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3440 SDValue Cond = Op.getOperand(0);
3441 SDValue SelectTrue = Op.getOperand(1);
3442 SDValue SelectFalse = Op.getOperand(2);
3444 unsigned Opc = Cond.getOpcode();
3446 if (Cond.getResNo() == 1 &&
3447 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3448 Opc == ISD::USUBO)) {
3449 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3452 SDValue Value, OverflowCmp;
3454 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3455 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3456 EVT VT = Op.getValueType();
3458 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3464 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3465 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3467 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3468 const ConstantSDNode *CMOVTrue =
3469 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3470 const ConstantSDNode *CMOVFalse =
3471 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3473 if (CMOVTrue && CMOVFalse) {
3474 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3475 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3479 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3481 False = SelectFalse;
3482 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3487 if (True.getNode() && False.getNode()) {
3488 EVT VT = Op.getValueType();
3489 SDValue ARMcc = Cond.getOperand(2);
3490 SDValue CCR = Cond.getOperand(3);
3491 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3492 assert(True.getValueType() == VT);
3493 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3498 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3499 // undefined bits before doing a full-word comparison with zero.
3500 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3501 DAG.getConstant(1, dl, Cond.getValueType()));
3503 return DAG.getSelectCC(dl, Cond,
3504 DAG.getConstant(0, dl, Cond.getValueType()),
3505 SelectTrue, SelectFalse, ISD::SETNE);
3508 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3509 bool &swpCmpOps, bool &swpVselOps) {
3510 // Start by selecting the GE condition code for opcodes that return true for
3512 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3514 CondCode = ARMCC::GE;
3516 // and GT for opcodes that return false for 'equality'.
3517 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3519 CondCode = ARMCC::GT;
3521 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3522 // to swap the compare operands.
3523 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3527 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3528 // If we have an unordered opcode, we need to swap the operands to the VSEL
3529 // instruction (effectively negating the condition).
3531 // This also has the effect of swapping which one of 'less' or 'greater'
3532 // returns true, so we also swap the compare operands. It also switches
3533 // whether we return true for 'equality', so we compensate by picking the
3534 // opposite condition code to our original choice.
3535 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3536 CC == ISD::SETUGT) {
3537 swpCmpOps = !swpCmpOps;
3538 swpVselOps = !swpVselOps;
3539 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3542 // 'ordered' is 'anything but unordered', so use the VS condition code and
3543 // swap the VSEL operands.
3544 if (CC == ISD::SETO) {
3545 CondCode = ARMCC::VS;
3549 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3550 // code and swap the VSEL operands.
3551 if (CC == ISD::SETUNE) {
3552 CondCode = ARMCC::EQ;
3557 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3558 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3559 SDValue Cmp, SelectionDAG &DAG) const {
3560 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3561 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3562 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3563 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3564 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3566 SDValue TrueLow = TrueVal.getValue(0);
3567 SDValue TrueHigh = TrueVal.getValue(1);
3568 SDValue FalseLow = FalseVal.getValue(0);
3569 SDValue FalseHigh = FalseVal.getValue(1);
3571 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3573 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3574 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3576 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3578 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3583 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3584 EVT VT = Op.getValueType();
3585 SDValue LHS = Op.getOperand(0);
3586 SDValue RHS = Op.getOperand(1);
3587 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3588 SDValue TrueVal = Op.getOperand(2);
3589 SDValue FalseVal = Op.getOperand(3);
3592 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3593 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3596 // If softenSetCCOperands only returned one value, we should compare it to
3598 if (!RHS.getNode()) {
3599 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3604 if (LHS.getValueType() == MVT::i32) {
3605 // Try to generate VSEL on ARMv8.
3606 // The VSEL instruction can't use all the usual ARM condition
3607 // codes: it only has two bits to select the condition code, so it's
3608 // constrained to use only GE, GT, VS and EQ.
3610 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3611 // swap the operands of the previous compare instruction (effectively
3612 // inverting the compare condition, swapping 'less' and 'greater') and
3613 // sometimes need to swap the operands to the VSEL (which inverts the
3614 // condition in the sense of firing whenever the previous condition didn't)
3615 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3616 TrueVal.getValueType() == MVT::f64)) {
3617 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3618 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3619 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3620 CC = ISD::getSetCCInverse(CC, true);
3621 std::swap(TrueVal, FalseVal);
3626 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3627 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3628 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3631 ARMCC::CondCodes CondCode, CondCode2;
3632 FPCCToARMCC(CC, CondCode, CondCode2);
3634 // Try to generate VMAXNM/VMINNM on ARMv8.
3635 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3636 TrueVal.getValueType() == MVT::f64)) {
3637 bool swpCmpOps = false;
3638 bool swpVselOps = false;
3639 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3641 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3642 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3644 std::swap(LHS, RHS);
3646 std::swap(TrueVal, FalseVal);
3650 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3651 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3652 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3653 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3654 if (CondCode2 != ARMCC::AL) {
3655 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3656 // FIXME: Needs another CMP because flag can have but one use.
3657 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3658 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3663 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3664 /// to morph to an integer compare sequence.
3665 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3666 const ARMSubtarget *Subtarget) {
3667 SDNode *N = Op.getNode();
3668 if (!N->hasOneUse())
3669 // Otherwise it requires moving the value from fp to integer registers.
3671 if (!N->getNumValues())
3673 EVT VT = Op.getValueType();
3674 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3675 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3676 // vmrs are very slow, e.g. cortex-a8.
3679 if (isFloatingPointZero(Op)) {
3683 return ISD::isNormalLoad(N);
3686 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3687 if (isFloatingPointZero(Op))
3688 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3690 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3691 return DAG.getLoad(MVT::i32, SDLoc(Op),
3692 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3693 Ld->isVolatile(), Ld->isNonTemporal(),
3694 Ld->isInvariant(), Ld->getAlignment());
3696 llvm_unreachable("Unknown VFP cmp argument!");
3699 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3700 SDValue &RetVal1, SDValue &RetVal2) {
3703 if (isFloatingPointZero(Op)) {
3704 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3705 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3709 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3710 SDValue Ptr = Ld->getBasePtr();
3711 RetVal1 = DAG.getLoad(MVT::i32, dl,
3712 Ld->getChain(), Ptr,
3713 Ld->getPointerInfo(),
3714 Ld->isVolatile(), Ld->isNonTemporal(),
3715 Ld->isInvariant(), Ld->getAlignment());
3717 EVT PtrType = Ptr.getValueType();
3718 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3719 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3720 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3721 RetVal2 = DAG.getLoad(MVT::i32, dl,
3722 Ld->getChain(), NewPtr,
3723 Ld->getPointerInfo().getWithOffset(4),
3724 Ld->isVolatile(), Ld->isNonTemporal(),
3725 Ld->isInvariant(), NewAlign);
3729 llvm_unreachable("Unknown VFP cmp argument!");
3732 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3733 /// f32 and even f64 comparisons to integer ones.
3735 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3736 SDValue Chain = Op.getOperand(0);
3737 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3738 SDValue LHS = Op.getOperand(2);
3739 SDValue RHS = Op.getOperand(3);
3740 SDValue Dest = Op.getOperand(4);
3743 bool LHSSeenZero = false;
3744 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3745 bool RHSSeenZero = false;
3746 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3747 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3748 // If unsafe fp math optimization is enabled and there are no other uses of
3749 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3750 // to an integer comparison.
3751 if (CC == ISD::SETOEQ)
3753 else if (CC == ISD::SETUNE)
3756 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3758 if (LHS.getValueType() == MVT::f32) {
3759 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3760 bitcastf32Toi32(LHS, DAG), Mask);
3761 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3762 bitcastf32Toi32(RHS, DAG), Mask);
3763 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3764 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3765 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3766 Chain, Dest, ARMcc, CCR, Cmp);
3771 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3772 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3773 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3774 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3775 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3776 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3777 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3778 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3779 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3785 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3786 SDValue Chain = Op.getOperand(0);
3787 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3788 SDValue LHS = Op.getOperand(2);
3789 SDValue RHS = Op.getOperand(3);
3790 SDValue Dest = Op.getOperand(4);
3793 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3794 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3797 // If softenSetCCOperands only returned one value, we should compare it to
3799 if (!RHS.getNode()) {
3800 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3805 if (LHS.getValueType() == MVT::i32) {
3807 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3808 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3809 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3810 Chain, Dest, ARMcc, CCR, Cmp);
3813 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3815 if (getTargetMachine().Options.UnsafeFPMath &&
3816 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3817 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3818 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3819 if (Result.getNode())
3823 ARMCC::CondCodes CondCode, CondCode2;
3824 FPCCToARMCC(CC, CondCode, CondCode2);
3826 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3827 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3828 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3829 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3830 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3831 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3832 if (CondCode2 != ARMCC::AL) {
3833 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3834 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3835 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3840 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3841 SDValue Chain = Op.getOperand(0);
3842 SDValue Table = Op.getOperand(1);
3843 SDValue Index = Op.getOperand(2);
3846 EVT PTy = getPointerTy(DAG.getDataLayout());
3847 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3848 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3849 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3850 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3851 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3852 if (Subtarget->isThumb2()) {
3853 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3854 // which does another jump to the destination. This also makes it easier
3855 // to translate it to TBB / TBH later.
3856 // FIXME: This might not work if the function is extremely large.
3857 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3858 Addr, Op.getOperand(2), JTI);
3860 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3862 DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3863 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3864 false, false, false, 0);
3865 Chain = Addr.getValue(1);
3866 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3867 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3870 DAG.getLoad(PTy, dl, Chain, Addr,
3871 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3872 false, false, false, 0);
3873 Chain = Addr.getValue(1);
3874 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3878 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3879 EVT VT = Op.getValueType();
3882 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3883 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3885 return DAG.UnrollVectorOp(Op.getNode());
3888 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3889 "Invalid type for custom lowering!");
3890 if (VT != MVT::v4i16)
3891 return DAG.UnrollVectorOp(Op.getNode());
3893 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3894 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3897 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3898 EVT VT = Op.getValueType();
3900 return LowerVectorFP_TO_INT(Op, DAG);
3901 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3903 if (Op.getOpcode() == ISD::FP_TO_SINT)
3904 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3907 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3909 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3910 /*isSigned*/ false, SDLoc(Op)).first;
3916 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3917 EVT VT = Op.getValueType();
3920 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3921 if (VT.getVectorElementType() == MVT::f32)
3923 return DAG.UnrollVectorOp(Op.getNode());
3926 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3927 "Invalid type for custom lowering!");
3928 if (VT != MVT::v4f32)
3929 return DAG.UnrollVectorOp(Op.getNode());
3933 switch (Op.getOpcode()) {
3934 default: llvm_unreachable("Invalid opcode!");
3935 case ISD::SINT_TO_FP:
3936 CastOpc = ISD::SIGN_EXTEND;
3937 Opc = ISD::SINT_TO_FP;
3939 case ISD::UINT_TO_FP:
3940 CastOpc = ISD::ZERO_EXTEND;
3941 Opc = ISD::UINT_TO_FP;
3945 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3946 return DAG.getNode(Opc, dl, VT, Op);
3949 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3950 EVT VT = Op.getValueType();
3952 return LowerVectorINT_TO_FP(Op, DAG);
3953 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3955 if (Op.getOpcode() == ISD::SINT_TO_FP)
3956 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3959 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3961 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3962 /*isSigned*/ false, SDLoc(Op)).first;
3968 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3969 // Implement fcopysign with a fabs and a conditional fneg.
3970 SDValue Tmp0 = Op.getOperand(0);
3971 SDValue Tmp1 = Op.getOperand(1);
3973 EVT VT = Op.getValueType();
3974 EVT SrcVT = Tmp1.getValueType();
3975 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3976 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3977 bool UseNEON = !InGPR && Subtarget->hasNEON();
3980 // Use VBSL to copy the sign bit.
3981 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3982 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3983 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3984 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3986 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3987 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3988 DAG.getConstant(32, dl, MVT::i32));
3989 else /*if (VT == MVT::f32)*/
3990 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3991 if (SrcVT == MVT::f32) {
3992 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3994 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3995 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3996 DAG.getConstant(32, dl, MVT::i32));
3997 } else if (VT == MVT::f32)
3998 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3999 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4000 DAG.getConstant(32, dl, MVT::i32));
4001 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4002 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4004 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4006 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4007 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4008 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4010 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4011 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4012 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4013 if (VT == MVT::f32) {
4014 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4015 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4016 DAG.getConstant(0, dl, MVT::i32));
4018 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4024 // Bitcast operand 1 to i32.
4025 if (SrcVT == MVT::f64)
4026 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4028 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4030 // Or in the signbit with integer operations.
4031 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4032 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4033 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4034 if (VT == MVT::f32) {
4035 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4036 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4037 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4038 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4041 // f64: Or the high part with signbit and then combine two parts.
4042 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4044 SDValue Lo = Tmp0.getValue(0);
4045 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4046 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4047 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4050 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4051 MachineFunction &MF = DAG.getMachineFunction();
4052 MachineFrameInfo *MFI = MF.getFrameInfo();
4053 MFI->setReturnAddressIsTaken(true);
4055 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4058 EVT VT = Op.getValueType();
4060 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4062 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4063 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4064 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4065 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4066 MachinePointerInfo(), false, false, false, 0);
4069 // Return LR, which contains the return address. Mark it an implicit live-in.
4070 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4071 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4074 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4075 const ARMBaseRegisterInfo &ARI =
4076 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4077 MachineFunction &MF = DAG.getMachineFunction();
4078 MachineFrameInfo *MFI = MF.getFrameInfo();
4079 MFI->setFrameAddressIsTaken(true);
4081 EVT VT = Op.getValueType();
4082 SDLoc dl(Op); // FIXME probably not meaningful
4083 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4084 unsigned FrameReg = ARI.getFrameRegister(MF);
4085 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4087 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4088 MachinePointerInfo(),
4089 false, false, false, 0);
4093 // FIXME? Maybe this could be a TableGen attribute on some registers and
4094 // this table could be generated automatically from RegInfo.
4095 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4096 SelectionDAG &DAG) const {
4097 unsigned Reg = StringSwitch<unsigned>(RegName)
4098 .Case("sp", ARM::SP)
4102 report_fatal_error(Twine("Invalid register name \""
4103 + StringRef(RegName) + "\"."));
4106 // Result is 64 bit value so split into two 32 bit values and return as a
4108 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4109 SelectionDAG &DAG) {
4112 // This function is only supposed to be called for i64 type destination.
4113 assert(N->getValueType(0) == MVT::i64
4114 && "ExpandREAD_REGISTER called for non-i64 type result.");
4116 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4117 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4121 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4123 Results.push_back(Read.getOperand(0));
4126 /// ExpandBITCAST - If the target supports VFP, this function is called to
4127 /// expand a bit convert where either the source or destination type is i64 to
4128 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4129 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4130 /// vectors), since the legalizer won't know what to do with that.
4131 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4132 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4134 SDValue Op = N->getOperand(0);
4136 // This function is only supposed to be called for i64 types, either as the
4137 // source or destination of the bit convert.
4138 EVT SrcVT = Op.getValueType();
4139 EVT DstVT = N->getValueType(0);
4140 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4141 "ExpandBITCAST called for non-i64 type");
4143 // Turn i64->f64 into VMOVDRR.
4144 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4145 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4146 DAG.getConstant(0, dl, MVT::i32));
4147 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4148 DAG.getConstant(1, dl, MVT::i32));
4149 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4150 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4153 // Turn f64->i64 into VMOVRRD.
4154 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4156 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4157 SrcVT.getVectorNumElements() > 1)
4158 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4159 DAG.getVTList(MVT::i32, MVT::i32),
4160 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4162 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4163 DAG.getVTList(MVT::i32, MVT::i32), Op);
4164 // Merge the pieces into a single i64 value.
4165 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4171 /// getZeroVector - Returns a vector of specified type with all zero elements.
4172 /// Zero vectors are used to represent vector negation and in those cases
4173 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4174 /// not support i64 elements, so sometimes the zero vectors will need to be
4175 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4177 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4178 assert(VT.isVector() && "Expected a vector type");
4179 // The canonical modified immediate encoding of a zero vector is....0!
4180 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4181 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4182 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4183 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4186 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4187 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4188 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4189 SelectionDAG &DAG) const {
4190 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4191 EVT VT = Op.getValueType();
4192 unsigned VTBits = VT.getSizeInBits();
4194 SDValue ShOpLo = Op.getOperand(0);
4195 SDValue ShOpHi = Op.getOperand(1);
4196 SDValue ShAmt = Op.getOperand(2);
4198 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4200 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4202 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4203 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4204 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4205 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4206 DAG.getConstant(VTBits, dl, MVT::i32));
4207 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4208 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4209 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4211 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4212 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4213 ISD::SETGE, ARMcc, DAG, dl);
4214 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4215 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4218 SDValue Ops[2] = { Lo, Hi };
4219 return DAG.getMergeValues(Ops, dl);
4222 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4223 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4224 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4225 SelectionDAG &DAG) const {
4226 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4227 EVT VT = Op.getValueType();
4228 unsigned VTBits = VT.getSizeInBits();
4230 SDValue ShOpLo = Op.getOperand(0);
4231 SDValue ShOpHi = Op.getOperand(1);
4232 SDValue ShAmt = Op.getOperand(2);
4235 assert(Op.getOpcode() == ISD::SHL_PARTS);
4236 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4237 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4238 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4239 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4240 DAG.getConstant(VTBits, dl, MVT::i32));
4241 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4242 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4244 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4245 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4246 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4247 ISD::SETGE, ARMcc, DAG, dl);
4248 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4249 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4252 SDValue Ops[2] = { Lo, Hi };
4253 return DAG.getMergeValues(Ops, dl);
4256 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4257 SelectionDAG &DAG) const {
4258 // The rounding mode is in bits 23:22 of the FPSCR.
4259 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4260 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4261 // so that the shift + and get folded into a bitfield extract.
4263 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4264 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4266 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4267 DAG.getConstant(1U << 22, dl, MVT::i32));
4268 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4269 DAG.getConstant(22, dl, MVT::i32));
4270 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4271 DAG.getConstant(3, dl, MVT::i32));
4274 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4275 const ARMSubtarget *ST) {
4277 EVT VT = N->getValueType(0);
4278 if (VT.isVector()) {
4279 assert(ST->hasNEON());
4281 // Compute the least significant set bit: LSB = X & -X
4282 SDValue X = N->getOperand(0);
4283 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4284 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4286 EVT ElemTy = VT.getVectorElementType();
4288 if (ElemTy == MVT::i8) {
4289 // Compute with: cttz(x) = ctpop(lsb - 1)
4290 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4291 DAG.getTargetConstant(1, dl, ElemTy));
4292 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4293 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4296 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4297 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4298 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4299 unsigned NumBits = ElemTy.getSizeInBits();
4300 SDValue WidthMinus1 =
4301 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4302 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4303 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4304 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4307 // Compute with: cttz(x) = ctpop(lsb - 1)
4309 // Since we can only compute the number of bits in a byte with vcnt.8, we
4310 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4315 if (ElemTy == MVT::i64) {
4316 // Load constant 0xffff'ffff'ffff'ffff to register.
4317 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4318 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4319 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4321 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4322 DAG.getTargetConstant(1, dl, ElemTy));
4323 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4326 // Count #bits with vcnt.8.
4327 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4328 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4329 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4331 // Gather the #bits with vpaddl (pairwise add.)
4332 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4333 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4334 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4336 if (ElemTy == MVT::i16)
4339 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4340 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4341 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4343 if (ElemTy == MVT::i32)
4346 assert(ElemTy == MVT::i64);
4347 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4348 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4353 if (!ST->hasV6T2Ops())
4356 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4357 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4360 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4361 /// for each 16-bit element from operand, repeated. The basic idea is to
4362 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4364 /// Trace for v4i16:
4365 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4366 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4367 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4368 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4369 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4370 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4371 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4372 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4373 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4374 EVT VT = N->getValueType(0);
4377 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4378 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4379 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4380 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4381 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4382 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4385 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4386 /// bit-count for each 16-bit element from the operand. We need slightly
4387 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4388 /// 64/128-bit registers.
4390 /// Trace for v4i16:
4391 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4392 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4393 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4394 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4395 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4396 EVT VT = N->getValueType(0);
4399 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4400 if (VT.is64BitVector()) {
4401 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4402 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4403 DAG.getIntPtrConstant(0, DL));
4405 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4406 BitCounts, DAG.getIntPtrConstant(0, DL));
4407 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4411 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4412 /// bit-count for each 32-bit element from the operand. The idea here is
4413 /// to split the vector into 16-bit elements, leverage the 16-bit count
4414 /// routine, and then combine the results.
4416 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4417 /// input = [v0 v1 ] (vi: 32-bit elements)
4418 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4419 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4420 /// vrev: N0 = [k1 k0 k3 k2 ]
4422 /// N1 =+[k1 k0 k3 k2 ]
4424 /// N2 =+[k1 k3 k0 k2 ]
4426 /// Extended =+[k1 k3 k0 k2 ]
4428 /// Extracted=+[k1 k3 ]
4430 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4431 EVT VT = N->getValueType(0);
4434 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4436 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4437 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4438 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4439 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4440 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4442 if (VT.is64BitVector()) {
4443 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4444 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4445 DAG.getIntPtrConstant(0, DL));
4447 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4448 DAG.getIntPtrConstant(0, DL));
4449 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4453 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4454 const ARMSubtarget *ST) {
4455 EVT VT = N->getValueType(0);
4457 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4458 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4459 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4460 "Unexpected type for custom ctpop lowering");
4462 if (VT.getVectorElementType() == MVT::i32)
4463 return lowerCTPOP32BitElements(N, DAG);
4465 return lowerCTPOP16BitElements(N, DAG);
4468 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4469 const ARMSubtarget *ST) {
4470 EVT VT = N->getValueType(0);
4476 // Lower vector shifts on NEON to use VSHL.
4477 assert(ST->hasNEON() && "unexpected vector shift");
4479 // Left shifts translate directly to the vshiftu intrinsic.
4480 if (N->getOpcode() == ISD::SHL)
4481 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4482 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4484 N->getOperand(0), N->getOperand(1));
4486 assert((N->getOpcode() == ISD::SRA ||
4487 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4489 // NEON uses the same intrinsics for both left and right shifts. For
4490 // right shifts, the shift amounts are negative, so negate the vector of
4492 EVT ShiftVT = N->getOperand(1).getValueType();
4493 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4494 getZeroVector(ShiftVT, DAG, dl),
4496 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4497 Intrinsic::arm_neon_vshifts :
4498 Intrinsic::arm_neon_vshiftu);
4499 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4500 DAG.getConstant(vshiftInt, dl, MVT::i32),
4501 N->getOperand(0), NegatedCount);
4504 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4505 const ARMSubtarget *ST) {
4506 EVT VT = N->getValueType(0);
4509 // We can get here for a node like i32 = ISD::SHL i32, i64
4513 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4514 "Unknown shift to lower!");
4516 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4517 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4518 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4521 // If we are in thumb mode, we don't have RRX.
4522 if (ST->isThumb1Only()) return SDValue();
4524 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4525 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4526 DAG.getConstant(0, dl, MVT::i32));
4527 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4528 DAG.getConstant(1, dl, MVT::i32));
4530 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4531 // captures the result into a carry flag.
4532 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4533 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4535 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4536 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4538 // Merge the pieces into a single i64 value.
4539 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4542 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4543 SDValue TmpOp0, TmpOp1;
4544 bool Invert = false;
4548 SDValue Op0 = Op.getOperand(0);
4549 SDValue Op1 = Op.getOperand(1);
4550 SDValue CC = Op.getOperand(2);
4551 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4552 EVT VT = Op.getValueType();
4553 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4556 if (CmpVT.getVectorElementType() == MVT::i64)
4557 // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4558 // but it's possible that our operands are 64-bit but our result is 32-bit.
4559 // Bail in this case.
4562 if (Op1.getValueType().isFloatingPoint()) {
4563 switch (SetCCOpcode) {
4564 default: llvm_unreachable("Illegal FP comparison");
4566 case ISD::SETNE: Invert = true; // Fallthrough
4568 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4570 case ISD::SETLT: Swap = true; // Fallthrough
4572 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4574 case ISD::SETLE: Swap = true; // Fallthrough
4576 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4577 case ISD::SETUGE: Swap = true; // Fallthrough
4578 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4579 case ISD::SETUGT: Swap = true; // Fallthrough
4580 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4581 case ISD::SETUEQ: Invert = true; // Fallthrough
4583 // Expand this to (OLT | OGT).
4587 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4588 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4590 case ISD::SETUO: Invert = true; // Fallthrough
4592 // Expand this to (OLT | OGE).
4596 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4597 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4601 // Integer comparisons.
4602 switch (SetCCOpcode) {
4603 default: llvm_unreachable("Illegal integer comparison");
4604 case ISD::SETNE: Invert = true;
4605 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4606 case ISD::SETLT: Swap = true;
4607 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4608 case ISD::SETLE: Swap = true;
4609 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4610 case ISD::SETULT: Swap = true;
4611 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4612 case ISD::SETULE: Swap = true;
4613 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4616 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4617 if (Opc == ARMISD::VCEQ) {
4620 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4622 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4625 // Ignore bitconvert.
4626 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4627 AndOp = AndOp.getOperand(0);
4629 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4631 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4632 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4639 std::swap(Op0, Op1);
4641 // If one of the operands is a constant vector zero, attempt to fold the
4642 // comparison to a specialized compare-against-zero form.
4644 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4646 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4647 if (Opc == ARMISD::VCGE)
4648 Opc = ARMISD::VCLEZ;
4649 else if (Opc == ARMISD::VCGT)
4650 Opc = ARMISD::VCLTZ;
4655 if (SingleOp.getNode()) {
4658 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4660 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4662 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4664 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4666 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4668 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4671 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4674 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4677 Result = DAG.getNOT(dl, Result, VT);
4682 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4683 /// valid vector constant for a NEON instruction with a "modified immediate"
4684 /// operand (e.g., VMOV). If so, return the encoded value.
4685 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4686 unsigned SplatBitSize, SelectionDAG &DAG,
4687 SDLoc dl, EVT &VT, bool is128Bits,
4688 NEONModImmType type) {
4689 unsigned OpCmode, Imm;
4691 // SplatBitSize is set to the smallest size that splats the vector, so a
4692 // zero vector will always have SplatBitSize == 8. However, NEON modified
4693 // immediate instructions others than VMOV do not support the 8-bit encoding
4694 // of a zero vector, and the default encoding of zero is supposed to be the
4699 switch (SplatBitSize) {
4701 if (type != VMOVModImm)
4703 // Any 1-byte value is OK. Op=0, Cmode=1110.
4704 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4707 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4711 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4712 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4713 if ((SplatBits & ~0xff) == 0) {
4714 // Value = 0x00nn: Op=x, Cmode=100x.
4719 if ((SplatBits & ~0xff00) == 0) {
4720 // Value = 0xnn00: Op=x, Cmode=101x.
4722 Imm = SplatBits >> 8;
4728 // NEON's 32-bit VMOV supports splat values where:
4729 // * only one byte is nonzero, or
4730 // * the least significant byte is 0xff and the second byte is nonzero, or
4731 // * the least significant 2 bytes are 0xff and the third is nonzero.
4732 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4733 if ((SplatBits & ~0xff) == 0) {
4734 // Value = 0x000000nn: Op=x, Cmode=000x.
4739 if ((SplatBits & ~0xff00) == 0) {
4740 // Value = 0x0000nn00: Op=x, Cmode=001x.
4742 Imm = SplatBits >> 8;
4745 if ((SplatBits & ~0xff0000) == 0) {
4746 // Value = 0x00nn0000: Op=x, Cmode=010x.
4748 Imm = SplatBits >> 16;
4751 if ((SplatBits & ~0xff000000) == 0) {
4752 // Value = 0xnn000000: Op=x, Cmode=011x.
4754 Imm = SplatBits >> 24;
4758 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4759 if (type == OtherModImm) return SDValue();
4761 if ((SplatBits & ~0xffff) == 0 &&
4762 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4763 // Value = 0x0000nnff: Op=x, Cmode=1100.
4765 Imm = SplatBits >> 8;
4769 if ((SplatBits & ~0xffffff) == 0 &&
4770 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4771 // Value = 0x00nnffff: Op=x, Cmode=1101.
4773 Imm = SplatBits >> 16;
4777 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4778 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4779 // VMOV.I32. A (very) minor optimization would be to replicate the value
4780 // and fall through here to test for a valid 64-bit splat. But, then the
4781 // caller would also need to check and handle the change in size.
4785 if (type != VMOVModImm)
4787 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4788 uint64_t BitMask = 0xff;
4790 unsigned ImmMask = 1;
4792 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4793 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4796 } else if ((SplatBits & BitMask) != 0) {
4803 if (DAG.getDataLayout().isBigEndian())
4804 // swap higher and lower 32 bit word
4805 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4807 // Op=1, Cmode=1110.
4809 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4814 llvm_unreachable("unexpected size for isNEONModifiedImm");
4817 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4818 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4821 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4822 const ARMSubtarget *ST) const {
4826 bool IsDouble = Op.getValueType() == MVT::f64;
4827 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4829 // Use the default (constant pool) lowering for double constants when we have
4831 if (IsDouble && Subtarget->isFPOnlySP())
4834 // Try splatting with a VMOV.f32...
4835 APFloat FPVal = CFP->getValueAPF();
4836 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4839 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4840 // We have code in place to select a valid ConstantFP already, no need to
4845 // It's a float and we are trying to use NEON operations where
4846 // possible. Lower it to a splat followed by an extract.
4848 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4849 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4851 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4852 DAG.getConstant(0, DL, MVT::i32));
4855 // The rest of our options are NEON only, make sure that's allowed before
4857 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4861 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4863 // It wouldn't really be worth bothering for doubles except for one very
4864 // important value, which does happen to match: 0.0. So make sure we don't do
4866 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4869 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4870 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4871 VMovVT, false, VMOVModImm);
4872 if (NewVal != SDValue()) {
4874 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4877 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4879 // It's a float: cast and extract a vector element.
4880 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4882 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4883 DAG.getConstant(0, DL, MVT::i32));
4886 // Finally, try a VMVN.i32
4887 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4889 if (NewVal != SDValue()) {
4891 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4894 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4896 // It's a float: cast and extract a vector element.
4897 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4899 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4900 DAG.getConstant(0, DL, MVT::i32));
4906 // check if an VEXT instruction can handle the shuffle mask when the
4907 // vector sources of the shuffle are the same.
4908 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4909 unsigned NumElts = VT.getVectorNumElements();
4911 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4917 // If this is a VEXT shuffle, the immediate value is the index of the first
4918 // element. The other shuffle indices must be the successive elements after
4920 unsigned ExpectedElt = Imm;
4921 for (unsigned i = 1; i < NumElts; ++i) {
4922 // Increment the expected index. If it wraps around, just follow it
4923 // back to index zero and keep going.
4925 if (ExpectedElt == NumElts)
4928 if (M[i] < 0) continue; // ignore UNDEF indices
4929 if (ExpectedElt != static_cast<unsigned>(M[i]))
4937 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4938 bool &ReverseVEXT, unsigned &Imm) {
4939 unsigned NumElts = VT.getVectorNumElements();
4940 ReverseVEXT = false;
4942 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4948 // If this is a VEXT shuffle, the immediate value is the index of the first
4949 // element. The other shuffle indices must be the successive elements after
4951 unsigned ExpectedElt = Imm;
4952 for (unsigned i = 1; i < NumElts; ++i) {
4953 // Increment the expected index. If it wraps around, it may still be
4954 // a VEXT but the source vectors must be swapped.
4956 if (ExpectedElt == NumElts * 2) {
4961 if (M[i] < 0) continue; // ignore UNDEF indices
4962 if (ExpectedElt != static_cast<unsigned>(M[i]))
4966 // Adjust the index value if the source operands will be swapped.
4973 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4974 /// instruction with the specified blocksize. (The order of the elements
4975 /// within each block of the vector is reversed.)
4976 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4977 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4978 "Only possible block sizes for VREV are: 16, 32, 64");
4980 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4984 unsigned NumElts = VT.getVectorNumElements();
4985 unsigned BlockElts = M[0] + 1;
4986 // If the first shuffle index is UNDEF, be optimistic.
4988 BlockElts = BlockSize / EltSz;
4990 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4993 for (unsigned i = 0; i < NumElts; ++i) {
4994 if (M[i] < 0) continue; // ignore UNDEF indices
4995 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5002 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5003 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5004 // range, then 0 is placed into the resulting vector. So pretty much any mask
5005 // of 8 elements can work here.
5006 return VT == MVT::v8i8 && M.size() == 8;
5009 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5010 // checking that pairs of elements in the shuffle mask represent the same index
5011 // in each vector, incrementing the expected index by 2 at each step.
5012 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5013 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5015 // WhichResult gives the offset for each element in the mask based on which
5016 // of the two results it belongs to.
5018 // The transpose can be represented either as:
5019 // result1 = shufflevector v1, v2, result1_shuffle_mask
5020 // result2 = shufflevector v1, v2, result2_shuffle_mask
5021 // where v1/v2 and the shuffle masks have the same number of elements
5022 // (here WhichResult (see below) indicates which result is being checked)
5025 // results = shufflevector v1, v2, shuffle_mask
5026 // where both results are returned in one vector and the shuffle mask has twice
5027 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5028 // want to check the low half and high half of the shuffle mask as if it were
5030 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5031 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5035 unsigned NumElts = VT.getVectorNumElements();
5036 if (M.size() != NumElts && M.size() != NumElts*2)
5039 // If the mask is twice as long as the input vector then we need to check the
5040 // upper and lower parts of the mask with a matching value for WhichResult
5041 // FIXME: A mask with only even values will be rejected in case the first
5042 // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5043 // M[0] is used to determine WhichResult
5044 for (unsigned i = 0; i < M.size(); i += NumElts) {
5045 if (M.size() == NumElts * 2)
5046 WhichResult = i / NumElts;
5048 WhichResult = M[i] == 0 ? 0 : 1;
5049 for (unsigned j = 0; j < NumElts; j += 2) {
5050 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5051 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5056 if (M.size() == NumElts*2)
5062 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5063 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5064 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5065 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5066 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5070 unsigned NumElts = VT.getVectorNumElements();
5071 if (M.size() != NumElts && M.size() != NumElts*2)
5074 for (unsigned i = 0; i < M.size(); i += NumElts) {
5075 if (M.size() == NumElts * 2)
5076 WhichResult = i / NumElts;
5078 WhichResult = M[i] == 0 ? 0 : 1;
5079 for (unsigned j = 0; j < NumElts; j += 2) {
5080 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5081 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5086 if (M.size() == NumElts*2)
5092 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5093 // that the mask elements are either all even and in steps of size 2 or all odd
5094 // and in steps of size 2.
5095 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5096 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5098 // Requires similar checks to that of isVTRNMask with
5099 // respect the how results are returned.
5100 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5101 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5105 unsigned NumElts = VT.getVectorNumElements();
5106 if (M.size() != NumElts && M.size() != NumElts*2)
5109 for (unsigned i = 0; i < M.size(); i += NumElts) {
5110 WhichResult = M[i] == 0 ? 0 : 1;
5111 for (unsigned j = 0; j < NumElts; ++j) {
5112 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5117 if (M.size() == NumElts*2)
5120 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5121 if (VT.is64BitVector() && EltSz == 32)
5127 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5128 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5129 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5130 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5131 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5135 unsigned NumElts = VT.getVectorNumElements();
5136 if (M.size() != NumElts && M.size() != NumElts*2)
5139 unsigned Half = NumElts / 2;
5140 for (unsigned i = 0; i < M.size(); i += NumElts) {
5141 WhichResult = M[i] == 0 ? 0 : 1;
5142 for (unsigned j = 0; j < NumElts; j += Half) {
5143 unsigned Idx = WhichResult;
5144 for (unsigned k = 0; k < Half; ++k) {
5145 int MIdx = M[i + j + k];
5146 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5153 if (M.size() == NumElts*2)
5156 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5157 if (VT.is64BitVector() && EltSz == 32)
5163 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5164 // that pairs of elements of the shufflemask represent the same index in each
5165 // vector incrementing sequentially through the vectors.
5166 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5167 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5169 // Requires similar checks to that of isVTRNMask with respect the how results
5171 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5172 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5176 unsigned NumElts = VT.getVectorNumElements();
5177 if (M.size() != NumElts && M.size() != NumElts*2)
5180 for (unsigned i = 0; i < M.size(); i += NumElts) {
5181 WhichResult = M[i] == 0 ? 0 : 1;
5182 unsigned Idx = WhichResult * NumElts / 2;
5183 for (unsigned j = 0; j < NumElts; j += 2) {
5184 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5185 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5191 if (M.size() == NumElts*2)
5194 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5195 if (VT.is64BitVector() && EltSz == 32)
5201 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5202 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5203 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5204 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5205 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5209 unsigned NumElts = VT.getVectorNumElements();
5210 if (M.size() != NumElts && M.size() != NumElts*2)
5213 for (unsigned i = 0; i < M.size(); i += NumElts) {
5214 WhichResult = M[i] == 0 ? 0 : 1;
5215 unsigned Idx = WhichResult * NumElts / 2;
5216 for (unsigned j = 0; j < NumElts; j += 2) {
5217 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5218 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5224 if (M.size() == NumElts*2)
5227 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5228 if (VT.is64BitVector() && EltSz == 32)
5234 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5235 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5236 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5237 unsigned &WhichResult,
5240 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5241 return ARMISD::VTRN;
5242 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5243 return ARMISD::VUZP;
5244 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5245 return ARMISD::VZIP;
5248 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5249 return ARMISD::VTRN;
5250 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5251 return ARMISD::VUZP;
5252 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5253 return ARMISD::VZIP;
5258 /// \return true if this is a reverse operation on an vector.
5259 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5260 unsigned NumElts = VT.getVectorNumElements();
5261 // Make sure the mask has the right size.
5262 if (NumElts != M.size())
5265 // Look for <15, ..., 3, -1, 1, 0>.
5266 for (unsigned i = 0; i != NumElts; ++i)
5267 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5273 // If N is an integer constant that can be moved into a register in one
5274 // instruction, return an SDValue of such a constant (will become a MOV
5275 // instruction). Otherwise return null.
5276 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5277 const ARMSubtarget *ST, SDLoc dl) {
5279 if (!isa<ConstantSDNode>(N))
5281 Val = cast<ConstantSDNode>(N)->getZExtValue();
5283 if (ST->isThumb1Only()) {
5284 if (Val <= 255 || ~Val <= 255)
5285 return DAG.getConstant(Val, dl, MVT::i32);
5287 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5288 return DAG.getConstant(Val, dl, MVT::i32);
5293 // If this is a case we can't handle, return null and let the default
5294 // expansion code take care of it.
5295 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5296 const ARMSubtarget *ST) const {
5297 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5299 EVT VT = Op.getValueType();
5301 APInt SplatBits, SplatUndef;
5302 unsigned SplatBitSize;
5304 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5305 if (SplatBitSize <= 64) {
5306 // Check if an immediate VMOV works.
5308 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5309 SplatUndef.getZExtValue(), SplatBitSize,
5310 DAG, dl, VmovVT, VT.is128BitVector(),
5312 if (Val.getNode()) {
5313 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5314 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5317 // Try an immediate VMVN.
5318 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5319 Val = isNEONModifiedImm(NegatedImm,
5320 SplatUndef.getZExtValue(), SplatBitSize,
5321 DAG, dl, VmovVT, VT.is128BitVector(),
5323 if (Val.getNode()) {
5324 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5325 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5328 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5329 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5330 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5332 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5333 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5339 // Scan through the operands to see if only one value is used.
5341 // As an optimisation, even if more than one value is used it may be more
5342 // profitable to splat with one value then change some lanes.
5344 // Heuristically we decide to do this if the vector has a "dominant" value,
5345 // defined as splatted to more than half of the lanes.
5346 unsigned NumElts = VT.getVectorNumElements();
5347 bool isOnlyLowElement = true;
5348 bool usesOnlyOneValue = true;
5349 bool hasDominantValue = false;
5350 bool isConstant = true;
5352 // Map of the number of times a particular SDValue appears in the
5354 DenseMap<SDValue, unsigned> ValueCounts;
5356 for (unsigned i = 0; i < NumElts; ++i) {
5357 SDValue V = Op.getOperand(i);
5358 if (V.getOpcode() == ISD::UNDEF)
5361 isOnlyLowElement = false;
5362 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5365 ValueCounts.insert(std::make_pair(V, 0));
5366 unsigned &Count = ValueCounts[V];
5368 // Is this value dominant? (takes up more than half of the lanes)
5369 if (++Count > (NumElts / 2)) {
5370 hasDominantValue = true;
5374 if (ValueCounts.size() != 1)
5375 usesOnlyOneValue = false;
5376 if (!Value.getNode() && ValueCounts.size() > 0)
5377 Value = ValueCounts.begin()->first;
5379 if (ValueCounts.size() == 0)
5380 return DAG.getUNDEF(VT);
5382 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5383 // Keep going if we are hitting this case.
5384 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5385 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5387 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5389 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5390 // i32 and try again.
5391 if (hasDominantValue && EltSize <= 32) {
5395 // If we are VDUPing a value that comes directly from a vector, that will
5396 // cause an unnecessary move to and from a GPR, where instead we could
5397 // just use VDUPLANE. We can only do this if the lane being extracted
5398 // is at a constant index, as the VDUP from lane instructions only have
5399 // constant-index forms.
5400 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5401 isa<ConstantSDNode>(Value->getOperand(1))) {
5402 // We need to create a new undef vector to use for the VDUPLANE if the
5403 // size of the vector from which we get the value is different than the
5404 // size of the vector that we need to create. We will insert the element
5405 // such that the register coalescer will remove unnecessary copies.
5406 if (VT != Value->getOperand(0).getValueType()) {
5407 ConstantSDNode *constIndex;
5408 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5409 assert(constIndex && "The index is not a constant!");
5410 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5411 VT.getVectorNumElements();
5412 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5413 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5414 Value, DAG.getConstant(index, dl, MVT::i32)),
5415 DAG.getConstant(index, dl, MVT::i32));
5417 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5418 Value->getOperand(0), Value->getOperand(1));
5420 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5422 if (!usesOnlyOneValue) {
5423 // The dominant value was splatted as 'N', but we now have to insert
5424 // all differing elements.
5425 for (unsigned I = 0; I < NumElts; ++I) {
5426 if (Op.getOperand(I) == Value)
5428 SmallVector<SDValue, 3> Ops;
5430 Ops.push_back(Op.getOperand(I));
5431 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5432 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5437 if (VT.getVectorElementType().isFloatingPoint()) {
5438 SmallVector<SDValue, 8> Ops;
5439 for (unsigned i = 0; i < NumElts; ++i)
5440 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5442 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5443 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5444 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5446 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5448 if (usesOnlyOneValue) {
5449 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5450 if (isConstant && Val.getNode())
5451 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5455 // If all elements are constants and the case above didn't get hit, fall back
5456 // to the default expansion, which will generate a load from the constant
5461 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5463 SDValue shuffle = ReconstructShuffle(Op, DAG);
5464 if (shuffle != SDValue())
5468 // Vectors with 32- or 64-bit elements can be built by directly assigning
5469 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5470 // will be legalized.
5471 if (EltSize >= 32) {
5472 // Do the expansion with floating-point types, since that is what the VFP
5473 // registers are defined to use, and since i64 is not legal.
5474 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5475 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5476 SmallVector<SDValue, 8> Ops;
5477 for (unsigned i = 0; i < NumElts; ++i)
5478 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5479 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5480 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5483 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5484 // know the default expansion would otherwise fall back on something even
5485 // worse. For a vector with one or two non-undef values, that's
5486 // scalar_to_vector for the elements followed by a shuffle (provided the
5487 // shuffle is valid for the target) and materialization element by element
5488 // on the stack followed by a load for everything else.
5489 if (!isConstant && !usesOnlyOneValue) {
5490 SDValue Vec = DAG.getUNDEF(VT);
5491 for (unsigned i = 0 ; i < NumElts; ++i) {
5492 SDValue V = Op.getOperand(i);
5493 if (V.getOpcode() == ISD::UNDEF)
5495 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5496 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5504 // Gather data to see if the operation can be modelled as a
5505 // shuffle in combination with VEXTs.
5506 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5507 SelectionDAG &DAG) const {
5508 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5510 EVT VT = Op.getValueType();
5511 unsigned NumElts = VT.getVectorNumElements();
5513 struct ShuffleSourceInfo {
5518 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5519 // be compatible with the shuffle we intend to construct. As a result
5520 // ShuffleVec will be some sliding window into the original Vec.
5523 // Code should guarantee that element i in Vec starts at element "WindowBase
5524 // + i * WindowScale in ShuffleVec".
5528 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5529 ShuffleSourceInfo(SDValue Vec)
5530 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5534 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5536 SmallVector<ShuffleSourceInfo, 2> Sources;
5537 for (unsigned i = 0; i < NumElts; ++i) {
5538 SDValue V = Op.getOperand(i);
5539 if (V.getOpcode() == ISD::UNDEF)
5541 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5542 // A shuffle can only come from building a vector from various
5543 // elements of other vectors.
5545 } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5546 // Furthermore, shuffles require a constant mask, whereas extractelts
5547 // accept variable indices.
5551 // Add this element source to the list if it's not already there.
5552 SDValue SourceVec = V.getOperand(0);
5553 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5554 if (Source == Sources.end())
5555 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5557 // Update the minimum and maximum lane number seen.
5558 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5559 Source->MinElt = std::min(Source->MinElt, EltNo);
5560 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5563 // Currently only do something sane when at most two source vectors
5565 if (Sources.size() > 2)
5568 // Find out the smallest element size among result and two sources, and use
5569 // it as element size to build the shuffle_vector.
5570 EVT SmallestEltTy = VT.getVectorElementType();
5571 for (auto &Source : Sources) {
5572 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5573 if (SrcEltTy.bitsLT(SmallestEltTy))
5574 SmallestEltTy = SrcEltTy;
5576 unsigned ResMultiplier =
5577 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5578 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5579 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5581 // If the source vector is too wide or too narrow, we may nevertheless be able
5582 // to construct a compatible shuffle either by concatenating it with UNDEF or
5583 // extracting a suitable range of elements.
5584 for (auto &Src : Sources) {
5585 EVT SrcVT = Src.ShuffleVec.getValueType();
5587 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5590 // This stage of the search produces a source with the same element type as
5591 // the original, but with a total width matching the BUILD_VECTOR output.
5592 EVT EltVT = SrcVT.getVectorElementType();
5593 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5594 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5596 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5597 if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5599 // We can pad out the smaller vector for free, so if it's part of a
5602 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5603 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5607 if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5610 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5611 // Span too large for a VEXT to cope
5615 if (Src.MinElt >= NumSrcElts) {
5616 // The extraction can just take the second half
5618 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5619 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5620 Src.WindowBase = -NumSrcElts;
5621 } else if (Src.MaxElt < NumSrcElts) {
5622 // The extraction can just take the first half
5624 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5625 DAG.getConstant(0, dl, MVT::i32));
5627 // An actual VEXT is needed
5629 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5630 DAG.getConstant(0, dl, MVT::i32));
5632 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5633 DAG.getConstant(NumSrcElts, dl, MVT::i32));
5635 Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5637 DAG.getConstant(Src.MinElt, dl, MVT::i32));
5638 Src.WindowBase = -Src.MinElt;
5642 // Another possible incompatibility occurs from the vector element types. We
5643 // can fix this by bitcasting the source vectors to the same type we intend
5645 for (auto &Src : Sources) {
5646 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5647 if (SrcEltTy == SmallestEltTy)
5649 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5650 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5651 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5652 Src.WindowBase *= Src.WindowScale;
5655 // Final sanity check before we try to actually produce a shuffle.
5657 for (auto Src : Sources)
5658 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5661 // The stars all align, our next step is to produce the mask for the shuffle.
5662 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5663 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5664 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5665 SDValue Entry = Op.getOperand(i);
5666 if (Entry.getOpcode() == ISD::UNDEF)
5669 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5670 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5672 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5673 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5675 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5676 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5677 VT.getVectorElementType().getSizeInBits());
5678 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5680 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5681 // starting at the appropriate offset.
5682 int *LaneMask = &Mask[i * ResMultiplier];
5684 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5685 ExtractBase += NumElts * (Src - Sources.begin());
5686 for (int j = 0; j < LanesDefined; ++j)
5687 LaneMask[j] = ExtractBase + j;
5690 // Final check before we try to produce nonsense...
5691 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5694 // We can't handle more than two sources. This should have already
5695 // been checked before this point.
5696 assert(Sources.size() <= 2 && "Too many sources!");
5698 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5699 for (unsigned i = 0; i < Sources.size(); ++i)
5700 ShuffleOps[i] = Sources[i].ShuffleVec;
5702 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5703 ShuffleOps[1], &Mask[0]);
5704 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5707 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5708 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5709 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5710 /// are assumed to be legal.
5712 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5714 if (VT.getVectorNumElements() == 4 &&
5715 (VT.is128BitVector() || VT.is64BitVector())) {
5716 unsigned PFIndexes[4];
5717 for (unsigned i = 0; i != 4; ++i) {
5721 PFIndexes[i] = M[i];
5724 // Compute the index in the perfect shuffle table.
5725 unsigned PFTableIndex =
5726 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5727 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5728 unsigned Cost = (PFEntry >> 30);
5734 bool ReverseVEXT, isV_UNDEF;
5735 unsigned Imm, WhichResult;
5737 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5738 return (EltSize >= 32 ||
5739 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5740 isVREVMask(M, VT, 64) ||
5741 isVREVMask(M, VT, 32) ||
5742 isVREVMask(M, VT, 16) ||
5743 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5744 isVTBLMask(M, VT) ||
5745 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5746 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5749 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5750 /// the specified operations to build the shuffle.
5751 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5752 SDValue RHS, SelectionDAG &DAG,
5754 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5755 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5756 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5759 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5768 OP_VUZPL, // VUZP, left result
5769 OP_VUZPR, // VUZP, right result
5770 OP_VZIPL, // VZIP, left result
5771 OP_VZIPR, // VZIP, right result
5772 OP_VTRNL, // VTRN, left result
5773 OP_VTRNR // VTRN, right result
5776 if (OpNum == OP_COPY) {
5777 if (LHSID == (1*9+2)*9+3) return LHS;
5778 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5782 SDValue OpLHS, OpRHS;
5783 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5784 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5785 EVT VT = OpLHS.getValueType();
5788 default: llvm_unreachable("Unknown shuffle opcode!");
5790 // VREV divides the vector in half and swaps within the half.
5791 if (VT.getVectorElementType() == MVT::i32 ||
5792 VT.getVectorElementType() == MVT::f32)
5793 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5794 // vrev <4 x i16> -> VREV32
5795 if (VT.getVectorElementType() == MVT::i16)
5796 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5797 // vrev <4 x i8> -> VREV16
5798 assert(VT.getVectorElementType() == MVT::i8);
5799 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5804 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5805 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5809 return DAG.getNode(ARMISD::VEXT, dl, VT,
5811 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5814 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5815 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5818 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5819 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5822 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5823 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5827 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5828 ArrayRef<int> ShuffleMask,
5829 SelectionDAG &DAG) {
5830 // Check to see if we can use the VTBL instruction.
5831 SDValue V1 = Op.getOperand(0);
5832 SDValue V2 = Op.getOperand(1);
5835 SmallVector<SDValue, 8> VTBLMask;
5836 for (ArrayRef<int>::iterator
5837 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5838 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5840 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5841 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5842 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5844 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5845 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5848 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5849 SelectionDAG &DAG) {
5851 SDValue OpLHS = Op.getOperand(0);
5852 EVT VT = OpLHS.getValueType();
5854 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5855 "Expect an v8i16/v16i8 type");
5856 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5857 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5858 // extract the first 8 bytes into the top double word and the last 8 bytes
5859 // into the bottom double word. The v8i16 case is similar.
5860 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5861 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5862 DAG.getConstant(ExtractNum, DL, MVT::i32));
5865 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5866 SDValue V1 = Op.getOperand(0);
5867 SDValue V2 = Op.getOperand(1);
5869 EVT VT = Op.getValueType();
5870 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5872 // Convert shuffles that are directly supported on NEON to target-specific
5873 // DAG nodes, instead of keeping them as shuffles and matching them again
5874 // during code selection. This is more efficient and avoids the possibility
5875 // of inconsistencies between legalization and selection.
5876 // FIXME: floating-point vectors should be canonicalized to integer vectors
5877 // of the same time so that they get CSEd properly.
5878 ArrayRef<int> ShuffleMask = SVN->getMask();
5880 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5881 if (EltSize <= 32) {
5882 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5883 int Lane = SVN->getSplatIndex();
5884 // If this is undef splat, generate it via "just" vdup, if possible.
5885 if (Lane == -1) Lane = 0;
5887 // Test if V1 is a SCALAR_TO_VECTOR.
5888 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5889 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5891 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5892 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5894 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5895 !isa<ConstantSDNode>(V1.getOperand(0))) {
5896 bool IsScalarToVector = true;
5897 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5898 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5899 IsScalarToVector = false;
5902 if (IsScalarToVector)
5903 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5905 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5906 DAG.getConstant(Lane, dl, MVT::i32));
5911 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5914 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5915 DAG.getConstant(Imm, dl, MVT::i32));
5918 if (isVREVMask(ShuffleMask, VT, 64))
5919 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5920 if (isVREVMask(ShuffleMask, VT, 32))
5921 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5922 if (isVREVMask(ShuffleMask, VT, 16))
5923 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5925 if (V2->getOpcode() == ISD::UNDEF &&
5926 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5927 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5928 DAG.getConstant(Imm, dl, MVT::i32));
5931 // Check for Neon shuffles that modify both input vectors in place.
5932 // If both results are used, i.e., if there are two shuffles with the same
5933 // source operands and with masks corresponding to both results of one of
5934 // these operations, DAG memoization will ensure that a single node is
5935 // used for both shuffles.
5936 unsigned WhichResult;
5938 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5939 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5942 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5943 .getValue(WhichResult);
5946 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5947 // shuffles that produce a result larger than their operands with:
5948 // shuffle(concat(v1, undef), concat(v2, undef))
5950 // shuffle(concat(v1, v2), undef)
5951 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5953 // This is useful in the general case, but there are special cases where
5954 // native shuffles produce larger results: the two-result ops.
5956 // Look through the concat when lowering them:
5957 // shuffle(concat(v1, v2), undef)
5959 // concat(VZIP(v1, v2):0, :1)
5961 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5962 V2->getOpcode() == ISD::UNDEF) {
5963 SDValue SubV1 = V1->getOperand(0);
5964 SDValue SubV2 = V1->getOperand(1);
5965 EVT SubVT = SubV1.getValueType();
5967 // We expect these to have been canonicalized to -1.
5968 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5969 return i < (int)VT.getVectorNumElements();
5970 }) && "Unexpected shuffle index into UNDEF operand!");
5972 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5973 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5976 assert((WhichResult == 0) &&
5977 "In-place shuffle of concat can only have one result!");
5978 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5980 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5986 // If the shuffle is not directly supported and it has 4 elements, use
5987 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5988 unsigned NumElts = VT.getVectorNumElements();
5990 unsigned PFIndexes[4];
5991 for (unsigned i = 0; i != 4; ++i) {
5992 if (ShuffleMask[i] < 0)
5995 PFIndexes[i] = ShuffleMask[i];
5998 // Compute the index in the perfect shuffle table.
5999 unsigned PFTableIndex =
6000 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6001 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6002 unsigned Cost = (PFEntry >> 30);
6005 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6008 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6009 if (EltSize >= 32) {
6010 // Do the expansion with floating-point types, since that is what the VFP
6011 // registers are defined to use, and since i64 is not legal.
6012 EVT EltVT = EVT::getFloatingPointVT(EltSize);
6013 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6014 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6015 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6016 SmallVector<SDValue, 8> Ops;
6017 for (unsigned i = 0; i < NumElts; ++i) {
6018 if (ShuffleMask[i] < 0)
6019 Ops.push_back(DAG.getUNDEF(EltVT));
6021 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6022 ShuffleMask[i] < (int)NumElts ? V1 : V2,
6023 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6026 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6027 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6030 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6031 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6033 if (VT == MVT::v8i8) {
6034 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6035 if (NewOp.getNode())
6042 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6043 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6044 SDValue Lane = Op.getOperand(2);
6045 if (!isa<ConstantSDNode>(Lane))
6051 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6052 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6053 SDValue Lane = Op.getOperand(1);
6054 if (!isa<ConstantSDNode>(Lane))
6057 SDValue Vec = Op.getOperand(0);
6058 if (Op.getValueType() == MVT::i32 &&
6059 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6061 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6067 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6068 // The only time a CONCAT_VECTORS operation can have legal types is when
6069 // two 64-bit vectors are concatenated to a 128-bit vector.
6070 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6071 "unexpected CONCAT_VECTORS");
6073 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6074 SDValue Op0 = Op.getOperand(0);
6075 SDValue Op1 = Op.getOperand(1);
6076 if (Op0.getOpcode() != ISD::UNDEF)
6077 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6078 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6079 DAG.getIntPtrConstant(0, dl));
6080 if (Op1.getOpcode() != ISD::UNDEF)
6081 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6082 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6083 DAG.getIntPtrConstant(1, dl));
6084 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6087 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6088 /// element has been zero/sign-extended, depending on the isSigned parameter,
6089 /// from an integer type half its size.
6090 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6092 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6093 EVT VT = N->getValueType(0);
6094 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6095 SDNode *BVN = N->getOperand(0).getNode();
6096 if (BVN->getValueType(0) != MVT::v4i32 ||
6097 BVN->getOpcode() != ISD::BUILD_VECTOR)
6099 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6100 unsigned HiElt = 1 - LoElt;
6101 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6102 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6103 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6104 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6105 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6108 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6109 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6112 if (Hi0->isNullValue() && Hi1->isNullValue())
6118 if (N->getOpcode() != ISD::BUILD_VECTOR)
6121 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6122 SDNode *Elt = N->getOperand(i).getNode();
6123 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6124 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6125 unsigned HalfSize = EltSize / 2;
6127 if (!isIntN(HalfSize, C->getSExtValue()))
6130 if (!isUIntN(HalfSize, C->getZExtValue()))
6141 /// isSignExtended - Check if a node is a vector value that is sign-extended
6142 /// or a constant BUILD_VECTOR with sign-extended elements.
6143 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6144 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6146 if (isExtendedBUILD_VECTOR(N, DAG, true))
6151 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6152 /// or a constant BUILD_VECTOR with zero-extended elements.
6153 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6154 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6156 if (isExtendedBUILD_VECTOR(N, DAG, false))
6161 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6162 if (OrigVT.getSizeInBits() >= 64)
6165 assert(OrigVT.isSimple() && "Expecting a simple value type");
6167 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6168 switch (OrigSimpleTy) {
6169 default: llvm_unreachable("Unexpected Vector Type");
6178 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6179 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6180 /// We insert the required extension here to get the vector to fill a D register.
6181 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6184 unsigned ExtOpcode) {
6185 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6186 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6187 // 64-bits we need to insert a new extension so that it will be 64-bits.
6188 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6189 if (OrigTy.getSizeInBits() >= 64)
6192 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6193 EVT NewVT = getExtensionTo64Bits(OrigTy);
6195 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6198 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6199 /// does not do any sign/zero extension. If the original vector is less
6200 /// than 64 bits, an appropriate extension will be added after the load to
6201 /// reach a total size of 64 bits. We have to add the extension separately
6202 /// because ARM does not have a sign/zero extending load for vectors.
6203 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6204 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6206 // The load already has the right type.
6207 if (ExtendedTy == LD->getMemoryVT())
6208 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6209 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6210 LD->isNonTemporal(), LD->isInvariant(),
6211 LD->getAlignment());
6213 // We need to create a zextload/sextload. We cannot just create a load
6214 // followed by a zext/zext node because LowerMUL is also run during normal
6215 // operation legalization where we can't create illegal types.
6216 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6217 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6218 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6219 LD->isNonTemporal(), LD->getAlignment());
6222 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6223 /// extending load, or BUILD_VECTOR with extended elements, return the
6224 /// unextended value. The unextended vector should be 64 bits so that it can
6225 /// be used as an operand to a VMULL instruction. If the original vector size
6226 /// before extension is less than 64 bits we add a an extension to resize
6227 /// the vector to 64 bits.
6228 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6229 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6230 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6231 N->getOperand(0)->getValueType(0),
6235 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6236 return SkipLoadExtensionForVMULL(LD, DAG);
6238 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6239 // have been legalized as a BITCAST from v4i32.
6240 if (N->getOpcode() == ISD::BITCAST) {
6241 SDNode *BVN = N->getOperand(0).getNode();
6242 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6243 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6244 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6245 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6246 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6248 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6249 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6250 EVT VT = N->getValueType(0);
6251 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6252 unsigned NumElts = VT.getVectorNumElements();
6253 MVT TruncVT = MVT::getIntegerVT(EltSize);
6254 SmallVector<SDValue, 8> Ops;
6256 for (unsigned i = 0; i != NumElts; ++i) {
6257 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6258 const APInt &CInt = C->getAPIntValue();
6259 // Element types smaller than 32 bits are not legal, so use i32 elements.
6260 // The values are implicitly truncated so sext vs. zext doesn't matter.
6261 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6263 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6264 MVT::getVectorVT(TruncVT, NumElts), Ops);
6267 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6268 unsigned Opcode = N->getOpcode();
6269 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6270 SDNode *N0 = N->getOperand(0).getNode();
6271 SDNode *N1 = N->getOperand(1).getNode();
6272 return N0->hasOneUse() && N1->hasOneUse() &&
6273 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6278 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6279 unsigned Opcode = N->getOpcode();
6280 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6281 SDNode *N0 = N->getOperand(0).getNode();
6282 SDNode *N1 = N->getOperand(1).getNode();
6283 return N0->hasOneUse() && N1->hasOneUse() &&
6284 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6289 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6290 // Multiplications are only custom-lowered for 128-bit vectors so that
6291 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6292 EVT VT = Op.getValueType();
6293 assert(VT.is128BitVector() && VT.isInteger() &&
6294 "unexpected type for custom-lowering ISD::MUL");
6295 SDNode *N0 = Op.getOperand(0).getNode();
6296 SDNode *N1 = Op.getOperand(1).getNode();
6297 unsigned NewOpc = 0;
6299 bool isN0SExt = isSignExtended(N0, DAG);
6300 bool isN1SExt = isSignExtended(N1, DAG);
6301 if (isN0SExt && isN1SExt)
6302 NewOpc = ARMISD::VMULLs;
6304 bool isN0ZExt = isZeroExtended(N0, DAG);
6305 bool isN1ZExt = isZeroExtended(N1, DAG);
6306 if (isN0ZExt && isN1ZExt)
6307 NewOpc = ARMISD::VMULLu;
6308 else if (isN1SExt || isN1ZExt) {
6309 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6310 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6311 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6312 NewOpc = ARMISD::VMULLs;
6314 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6315 NewOpc = ARMISD::VMULLu;
6317 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6319 NewOpc = ARMISD::VMULLu;
6325 if (VT == MVT::v2i64)
6326 // Fall through to expand this. It is not legal.
6329 // Other vector multiplications are legal.
6334 // Legalize to a VMULL instruction.
6337 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6339 Op0 = SkipExtensionForVMULL(N0, DAG);
6340 assert(Op0.getValueType().is64BitVector() &&
6341 Op1.getValueType().is64BitVector() &&
6342 "unexpected types for extended operands to VMULL");
6343 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6346 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6347 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6354 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6355 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6356 EVT Op1VT = Op1.getValueType();
6357 return DAG.getNode(N0->getOpcode(), DL, VT,
6358 DAG.getNode(NewOpc, DL, VT,
6359 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6360 DAG.getNode(NewOpc, DL, VT,
6361 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6365 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6366 // TODO: Should this propagate fast-math-flags?
6369 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6370 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6371 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6372 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6373 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6374 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6375 // Get reciprocal estimate.
6376 // float4 recip = vrecpeq_f32(yf);
6377 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6378 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6380 // Because char has a smaller range than uchar, we can actually get away
6381 // without any newton steps. This requires that we use a weird bias
6382 // of 0xb000, however (again, this has been exhaustively tested).
6383 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6384 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6385 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6386 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6387 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6388 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6389 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6390 // Convert back to short.
6391 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6392 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6397 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6398 // TODO: Should this propagate fast-math-flags?
6401 // Convert to float.
6402 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6403 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6404 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6405 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6406 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6407 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6409 // Use reciprocal estimate and one refinement step.
6410 // float4 recip = vrecpeq_f32(yf);
6411 // recip *= vrecpsq_f32(yf, recip);
6412 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6413 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6415 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6416 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6418 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6419 // Because short has a smaller range than ushort, we can actually get away
6420 // with only a single newton step. This requires that we use a weird bias
6421 // of 89, however (again, this has been exhaustively tested).
6422 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6423 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6424 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6425 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6426 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6427 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6428 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6429 // Convert back to integer and return.
6430 // return vmovn_s32(vcvt_s32_f32(result));
6431 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6432 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6436 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6437 EVT VT = Op.getValueType();
6438 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6439 "unexpected type for custom-lowering ISD::SDIV");
6442 SDValue N0 = Op.getOperand(0);
6443 SDValue N1 = Op.getOperand(1);
6446 if (VT == MVT::v8i8) {
6447 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6448 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6450 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6451 DAG.getIntPtrConstant(4, dl));
6452 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6453 DAG.getIntPtrConstant(4, dl));
6454 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6455 DAG.getIntPtrConstant(0, dl));
6456 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6457 DAG.getIntPtrConstant(0, dl));
6459 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6460 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6462 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6463 N0 = LowerCONCAT_VECTORS(N0, DAG);
6465 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6468 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6471 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6472 // TODO: Should this propagate fast-math-flags?
6473 EVT VT = Op.getValueType();
6474 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6475 "unexpected type for custom-lowering ISD::UDIV");
6478 SDValue N0 = Op.getOperand(0);
6479 SDValue N1 = Op.getOperand(1);
6482 if (VT == MVT::v8i8) {
6483 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6484 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6486 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6487 DAG.getIntPtrConstant(4, dl));
6488 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6489 DAG.getIntPtrConstant(4, dl));
6490 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6491 DAG.getIntPtrConstant(0, dl));
6492 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6493 DAG.getIntPtrConstant(0, dl));
6495 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6496 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6498 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6499 N0 = LowerCONCAT_VECTORS(N0, DAG);
6501 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6502 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6508 // v4i16 sdiv ... Convert to float.
6509 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6510 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6511 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6512 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6513 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6514 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6516 // Use reciprocal estimate and two refinement steps.
6517 // float4 recip = vrecpeq_f32(yf);
6518 // recip *= vrecpsq_f32(yf, recip);
6519 // recip *= vrecpsq_f32(yf, recip);
6520 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6521 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6523 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6524 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6526 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6527 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6528 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6530 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6531 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6532 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6533 // and that it will never cause us to return an answer too large).
6534 // float4 result = as_float4(as_int4(xf*recip) + 2);
6535 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6536 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6537 N1 = DAG.getConstant(2, dl, MVT::i32);
6538 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6539 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6540 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6541 // Convert back to integer and return.
6542 // return vmovn_u32(vcvt_s32_f32(result));
6543 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6544 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6548 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6549 EVT VT = Op.getNode()->getValueType(0);
6550 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6553 bool ExtraOp = false;
6554 switch (Op.getOpcode()) {
6555 default: llvm_unreachable("Invalid code");
6556 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6557 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6558 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6559 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6563 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6565 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6566 Op.getOperand(1), Op.getOperand(2));
6569 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6570 assert(Subtarget->isTargetDarwin());
6572 // For iOS, we want to call an alternative entry point: __sincos_stret,
6573 // return values are passed via sret.
6575 SDValue Arg = Op.getOperand(0);
6576 EVT ArgVT = Arg.getValueType();
6577 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6578 auto PtrVT = getPointerTy(DAG.getDataLayout());
6580 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6582 // Pair of floats / doubles used to pass the result.
6583 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6585 // Create stack object for sret.
6586 auto &DL = DAG.getDataLayout();
6587 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6588 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6589 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6590 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6596 Entry.Ty = RetTy->getPointerTo();
6597 Entry.isSExt = false;
6598 Entry.isZExt = false;
6599 Entry.isSRet = true;
6600 Args.push_back(Entry);
6604 Entry.isSExt = false;
6605 Entry.isZExt = false;
6606 Args.push_back(Entry);
6608 const char *LibcallName =
6609 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6610 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6612 TargetLowering::CallLoweringInfo CLI(DAG);
6613 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6614 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6616 .setDiscardResult();
6618 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6620 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6621 MachinePointerInfo(), false, false, false, 0);
6623 // Address of cos field.
6624 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6625 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6626 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6627 MachinePointerInfo(), false, false, false, 0);
6629 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6630 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6631 LoadSin.getValue(0), LoadCos.getValue(0));
6634 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6636 SDValue &Chain) const {
6637 EVT VT = Op.getValueType();
6638 assert((VT == MVT::i32 || VT == MVT::i64) &&
6639 "unexpected type for custom lowering DIV");
6642 const auto &DL = DAG.getDataLayout();
6643 const auto &TLI = DAG.getTargetLoweringInfo();
6645 const char *Name = nullptr;
6647 Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6649 Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6651 SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6653 ARMTargetLowering::ArgListTy Args;
6655 for (auto AI : {1, 0}) {
6657 Arg.Node = Op.getOperand(AI);
6658 Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6659 Args.push_back(Arg);
6662 CallLoweringInfo CLI(DAG);
6665 .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6666 ES, std::move(Args), 0);
6668 return LowerCallTo(CLI).first;
6671 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6672 bool Signed) const {
6673 assert(Op.getValueType() == MVT::i32 &&
6674 "unexpected type for custom lowering DIV");
6677 SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6678 DAG.getEntryNode(), Op.getOperand(1));
6680 return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6683 void ARMTargetLowering::ExpandDIV_Windows(
6684 SDValue Op, SelectionDAG &DAG, bool Signed,
6685 SmallVectorImpl<SDValue> &Results) const {
6686 const auto &DL = DAG.getDataLayout();
6687 const auto &TLI = DAG.getTargetLoweringInfo();
6689 assert(Op.getValueType() == MVT::i64 &&
6690 "unexpected type for custom lowering DIV");
6693 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6694 DAG.getConstant(0, dl, MVT::i32));
6695 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6696 DAG.getConstant(1, dl, MVT::i32));
6697 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6700 DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6702 SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6704 SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6705 SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6706 DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6707 Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6709 Results.push_back(Lower);
6710 Results.push_back(Upper);
6713 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6714 // Monotonic load/store is legal for all targets
6715 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6718 // Acquire/Release load/store is not legal for targets without a
6719 // dmb or equivalent available.
6723 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6724 SmallVectorImpl<SDValue> &Results,
6726 const ARMSubtarget *Subtarget) {
6728 // Under Power Management extensions, the cycle-count is:
6729 // mrc p15, #0, <Rt>, c9, c13, #0
6730 SDValue Ops[] = { N->getOperand(0), // Chain
6731 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6732 DAG.getConstant(15, DL, MVT::i32),
6733 DAG.getConstant(0, DL, MVT::i32),
6734 DAG.getConstant(9, DL, MVT::i32),
6735 DAG.getConstant(13, DL, MVT::i32),
6736 DAG.getConstant(0, DL, MVT::i32)
6739 SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6740 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6741 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6742 DAG.getConstant(0, DL, MVT::i32)));
6743 Results.push_back(Cycles32.getValue(1));
6746 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6747 switch (Op.getOpcode()) {
6748 default: llvm_unreachable("Don't know how to custom lower this!");
6749 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6750 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6751 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6752 case ISD::GlobalAddress:
6753 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6754 default: llvm_unreachable("unknown object format");
6756 return LowerGlobalAddressWindows(Op, DAG);
6758 return LowerGlobalAddressELF(Op, DAG);
6760 return LowerGlobalAddressDarwin(Op, DAG);
6762 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6763 case ISD::SELECT: return LowerSELECT(Op, DAG);
6764 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6765 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6766 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6767 case ISD::VASTART: return LowerVASTART(Op, DAG);
6768 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6769 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6770 case ISD::SINT_TO_FP:
6771 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6772 case ISD::FP_TO_SINT:
6773 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6774 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6775 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6776 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6777 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6778 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6779 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6780 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6781 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6783 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6786 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6787 case ISD::SREM: return LowerREM(Op.getNode(), DAG);
6788 case ISD::UREM: return LowerREM(Op.getNode(), DAG);
6789 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6790 case ISD::SRL_PARTS:
6791 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6793 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6794 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6795 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6796 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6797 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6798 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6799 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6800 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6801 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6802 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6803 case ISD::MUL: return LowerMUL(Op, DAG);
6805 if (Subtarget->isTargetWindows())
6806 return LowerDIV_Windows(Op, DAG, /* Signed */ true);
6807 return LowerSDIV(Op, DAG);
6809 if (Subtarget->isTargetWindows())
6810 return LowerDIV_Windows(Op, DAG, /* Signed */ false);
6811 return LowerUDIV(Op, DAG);
6815 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6820 return LowerXALUO(Op, DAG);
6821 case ISD::ATOMIC_LOAD:
6822 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6823 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6825 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6826 case ISD::DYNAMIC_STACKALLOC:
6827 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6828 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6829 llvm_unreachable("Don't know how to custom lower this!");
6830 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6831 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6832 case ARMISD::WIN__DBZCHK: return SDValue();
6836 /// ReplaceNodeResults - Replace the results of node with an illegal result
6837 /// type with new values built out of custom code.
6838 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6839 SmallVectorImpl<SDValue> &Results,
6840 SelectionDAG &DAG) const {
6842 switch (N->getOpcode()) {
6844 llvm_unreachable("Don't know how to custom expand this!");
6845 case ISD::READ_REGISTER:
6846 ExpandREAD_REGISTER(N, Results, DAG);
6849 Res = ExpandBITCAST(N, DAG);
6853 Res = Expand64BitShift(N, DAG, Subtarget);
6857 Res = LowerREM(N, DAG);
6859 case ISD::READCYCLECOUNTER:
6860 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6864 assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6865 return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6869 Results.push_back(Res);
6872 //===----------------------------------------------------------------------===//
6873 // ARM Scheduler Hooks
6874 //===----------------------------------------------------------------------===//
6876 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6877 /// registers the function context.
6878 void ARMTargetLowering::
6879 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6880 MachineBasicBlock *DispatchBB, int FI) const {
6881 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6882 DebugLoc dl = MI->getDebugLoc();
6883 MachineFunction *MF = MBB->getParent();
6884 MachineRegisterInfo *MRI = &MF->getRegInfo();
6885 MachineConstantPool *MCP = MF->getConstantPool();
6886 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6887 const Function *F = MF->getFunction();
6889 bool isThumb = Subtarget->isThumb();
6890 bool isThumb2 = Subtarget->isThumb2();
6892 unsigned PCLabelId = AFI->createPICLabelUId();
6893 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6894 ARMConstantPoolValue *CPV =
6895 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6896 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6898 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6899 : &ARM::GPRRegClass;
6901 // Grab constant pool and fixed stack memory operands.
6902 MachineMemOperand *CPMMO =
6903 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6904 MachineMemOperand::MOLoad, 4, 4);
6906 MachineMemOperand *FIMMOSt =
6907 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6908 MachineMemOperand::MOStore, 4, 4);
6910 // Load the address of the dispatch MBB into the jump buffer.
6912 // Incoming value: jbuf
6913 // ldr.n r5, LCPI1_1
6916 // str r5, [$jbuf, #+4] ; &jbuf[1]
6917 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6918 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6919 .addConstantPoolIndex(CPI)
6920 .addMemOperand(CPMMO));
6921 // Set the low bit because of thumb mode.
6922 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6924 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6925 .addReg(NewVReg1, RegState::Kill)
6927 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6928 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6929 .addReg(NewVReg2, RegState::Kill)
6931 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6932 .addReg(NewVReg3, RegState::Kill)
6934 .addImm(36) // &jbuf[1] :: pc
6935 .addMemOperand(FIMMOSt));
6936 } else if (isThumb) {
6937 // Incoming value: jbuf
6938 // ldr.n r1, LCPI1_4
6942 // add r2, $jbuf, #+4 ; &jbuf[1]
6944 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6945 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6946 .addConstantPoolIndex(CPI)
6947 .addMemOperand(CPMMO));
6948 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6949 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6950 .addReg(NewVReg1, RegState::Kill)
6952 // Set the low bit because of thumb mode.
6953 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6954 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6955 .addReg(ARM::CPSR, RegState::Define)
6957 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6958 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6959 .addReg(ARM::CPSR, RegState::Define)
6960 .addReg(NewVReg2, RegState::Kill)
6961 .addReg(NewVReg3, RegState::Kill));
6962 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6963 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6965 .addImm(36); // &jbuf[1] :: pc
6966 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6967 .addReg(NewVReg4, RegState::Kill)
6968 .addReg(NewVReg5, RegState::Kill)
6970 .addMemOperand(FIMMOSt));
6972 // Incoming value: jbuf
6975 // str r1, [$jbuf, #+4] ; &jbuf[1]
6976 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6977 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6978 .addConstantPoolIndex(CPI)
6980 .addMemOperand(CPMMO));
6981 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6982 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6983 .addReg(NewVReg1, RegState::Kill)
6984 .addImm(PCLabelId));
6985 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6986 .addReg(NewVReg2, RegState::Kill)
6988 .addImm(36) // &jbuf[1] :: pc
6989 .addMemOperand(FIMMOSt));
6993 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6994 MachineBasicBlock *MBB) const {
6995 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6996 DebugLoc dl = MI->getDebugLoc();
6997 MachineFunction *MF = MBB->getParent();
6998 MachineRegisterInfo *MRI = &MF->getRegInfo();
6999 MachineFrameInfo *MFI = MF->getFrameInfo();
7000 int FI = MFI->getFunctionContextIndex();
7002 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7003 : &ARM::GPRnopcRegClass;
7005 // Get a mapping of the call site numbers to all of the landing pads they're
7007 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7008 unsigned MaxCSNum = 0;
7009 MachineModuleInfo &MMI = MF->getMMI();
7010 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7012 if (!BB->isEHPad()) continue;
7014 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7016 for (MachineBasicBlock::iterator
7017 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7018 if (!II->isEHLabel()) continue;
7020 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7021 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7023 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7024 for (SmallVectorImpl<unsigned>::iterator
7025 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7026 CSI != CSE; ++CSI) {
7027 CallSiteNumToLPad[*CSI].push_back(BB);
7028 MaxCSNum = std::max(MaxCSNum, *CSI);
7034 // Get an ordered list of the machine basic blocks for the jump table.
7035 std::vector<MachineBasicBlock*> LPadList;
7036 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7037 LPadList.reserve(CallSiteNumToLPad.size());
7038 for (unsigned I = 1; I <= MaxCSNum; ++I) {
7039 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7040 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7041 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7042 LPadList.push_back(*II);
7043 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7047 assert(!LPadList.empty() &&
7048 "No landing pad destinations for the dispatch jump table!");
7050 // Create the jump table and associated information.
7051 MachineJumpTableInfo *JTI =
7052 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7053 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7054 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7056 // Create the MBBs for the dispatch code.
7058 // Shove the dispatch's address into the return slot in the function context.
7059 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7060 DispatchBB->setIsEHPad();
7062 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7063 unsigned trap_opcode;
7064 if (Subtarget->isThumb())
7065 trap_opcode = ARM::tTRAP;
7067 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7069 BuildMI(TrapBB, dl, TII->get(trap_opcode));
7070 DispatchBB->addSuccessor(TrapBB);
7072 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7073 DispatchBB->addSuccessor(DispContBB);
7076 MF->insert(MF->end(), DispatchBB);
7077 MF->insert(MF->end(), DispContBB);
7078 MF->insert(MF->end(), TrapBB);
7080 // Insert code into the entry block that creates and registers the function
7082 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7084 MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7085 MachinePointerInfo::getFixedStack(*MF, FI),
7086 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7088 MachineInstrBuilder MIB;
7089 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7091 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7092 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7094 // Add a register mask with no preserved registers. This results in all
7095 // registers being marked as clobbered.
7096 MIB.addRegMask(RI.getNoPreservedMask());
7098 unsigned NumLPads = LPadList.size();
7099 if (Subtarget->isThumb2()) {
7100 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7101 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7104 .addMemOperand(FIMMOLd));
7106 if (NumLPads < 256) {
7107 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7109 .addImm(LPadList.size()));
7111 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7112 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7113 .addImm(NumLPads & 0xFFFF));
7115 unsigned VReg2 = VReg1;
7116 if ((NumLPads & 0xFFFF0000) != 0) {
7117 VReg2 = MRI->createVirtualRegister(TRC);
7118 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7120 .addImm(NumLPads >> 16));
7123 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7128 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7133 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7134 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7135 .addJumpTableIndex(MJTI));
7137 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7140 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7141 .addReg(NewVReg3, RegState::Kill)
7143 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7145 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7146 .addReg(NewVReg4, RegState::Kill)
7148 .addJumpTableIndex(MJTI);
7149 } else if (Subtarget->isThumb()) {
7150 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7151 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7154 .addMemOperand(FIMMOLd));
7156 if (NumLPads < 256) {
7157 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7161 MachineConstantPool *ConstantPool = MF->getConstantPool();
7162 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7163 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7165 // MachineConstantPool wants an explicit alignment.
7166 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7168 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7169 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7171 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7172 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7173 .addReg(VReg1, RegState::Define)
7174 .addConstantPoolIndex(Idx));
7175 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7180 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7185 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7186 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7187 .addReg(ARM::CPSR, RegState::Define)
7191 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7192 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7193 .addJumpTableIndex(MJTI));
7195 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7196 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7197 .addReg(ARM::CPSR, RegState::Define)
7198 .addReg(NewVReg2, RegState::Kill)
7201 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7202 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7204 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7205 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7206 .addReg(NewVReg4, RegState::Kill)
7208 .addMemOperand(JTMMOLd));
7210 unsigned NewVReg6 = NewVReg5;
7211 if (RelocM == Reloc::PIC_) {
7212 NewVReg6 = MRI->createVirtualRegister(TRC);
7213 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7214 .addReg(ARM::CPSR, RegState::Define)
7215 .addReg(NewVReg5, RegState::Kill)
7219 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7220 .addReg(NewVReg6, RegState::Kill)
7221 .addJumpTableIndex(MJTI);
7223 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7224 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7227 .addMemOperand(FIMMOLd));
7229 if (NumLPads < 256) {
7230 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7233 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7234 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7235 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7236 .addImm(NumLPads & 0xFFFF));
7238 unsigned VReg2 = VReg1;
7239 if ((NumLPads & 0xFFFF0000) != 0) {
7240 VReg2 = MRI->createVirtualRegister(TRC);
7241 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7243 .addImm(NumLPads >> 16));
7246 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7250 MachineConstantPool *ConstantPool = MF->getConstantPool();
7251 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7252 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7254 // MachineConstantPool wants an explicit alignment.
7255 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7257 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7258 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7260 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7261 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7262 .addReg(VReg1, RegState::Define)
7263 .addConstantPoolIndex(Idx)
7265 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7267 .addReg(VReg1, RegState::Kill));
7270 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7275 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7277 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7279 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7280 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7281 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7282 .addJumpTableIndex(MJTI));
7284 MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7285 MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7286 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7288 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7289 .addReg(NewVReg3, RegState::Kill)
7292 .addMemOperand(JTMMOLd));
7294 if (RelocM == Reloc::PIC_) {
7295 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7296 .addReg(NewVReg5, RegState::Kill)
7298 .addJumpTableIndex(MJTI);
7300 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7301 .addReg(NewVReg5, RegState::Kill)
7302 .addJumpTableIndex(MJTI);
7306 // Add the jump table entries as successors to the MBB.
7307 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7308 for (std::vector<MachineBasicBlock*>::iterator
7309 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7310 MachineBasicBlock *CurMBB = *I;
7311 if (SeenMBBs.insert(CurMBB).second)
7312 DispContBB->addSuccessor(CurMBB);
7315 // N.B. the order the invoke BBs are processed in doesn't matter here.
7316 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7317 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7318 for (MachineBasicBlock *BB : InvokeBBs) {
7320 // Remove the landing pad successor from the invoke block and replace it
7321 // with the new dispatch block.
7322 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7324 while (!Successors.empty()) {
7325 MachineBasicBlock *SMBB = Successors.pop_back_val();
7326 if (SMBB->isEHPad()) {
7327 BB->removeSuccessor(SMBB);
7328 MBBLPads.push_back(SMBB);
7332 BB->addSuccessor(DispatchBB);
7334 // Find the invoke call and mark all of the callee-saved registers as
7335 // 'implicit defined' so that they're spilled. This prevents code from
7336 // moving instructions to before the EH block, where they will never be
7338 for (MachineBasicBlock::reverse_iterator
7339 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7340 if (!II->isCall()) continue;
7342 DenseMap<unsigned, bool> DefRegs;
7343 for (MachineInstr::mop_iterator
7344 OI = II->operands_begin(), OE = II->operands_end();
7346 if (!OI->isReg()) continue;
7347 DefRegs[OI->getReg()] = true;
7350 MachineInstrBuilder MIB(*MF, &*II);
7352 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7353 unsigned Reg = SavedRegs[i];
7354 if (Subtarget->isThumb2() &&
7355 !ARM::tGPRRegClass.contains(Reg) &&
7356 !ARM::hGPRRegClass.contains(Reg))
7358 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7360 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7363 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7370 // Mark all former landing pads as non-landing pads. The dispatch is the only
7372 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7373 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7374 (*I)->setIsEHPad(false);
7376 // The instruction is gone now.
7377 MI->eraseFromParent();
7381 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7382 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7383 E = MBB->succ_end(); I != E; ++I)
7386 llvm_unreachable("Expecting a BB with two successors!");
7389 /// Return the load opcode for a given load size. If load size >= 8,
7390 /// neon opcode will be returned.
7391 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7393 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7394 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7396 return LdSize == 4 ? ARM::tLDRi
7397 : LdSize == 2 ? ARM::tLDRHi
7398 : LdSize == 1 ? ARM::tLDRBi : 0;
7400 return LdSize == 4 ? ARM::t2LDR_POST
7401 : LdSize == 2 ? ARM::t2LDRH_POST
7402 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7403 return LdSize == 4 ? ARM::LDR_POST_IMM
7404 : LdSize == 2 ? ARM::LDRH_POST
7405 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7408 /// Return the store opcode for a given store size. If store size >= 8,
7409 /// neon opcode will be returned.
7410 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7412 return StSize == 16 ? ARM::VST1q32wb_fixed
7413 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7415 return StSize == 4 ? ARM::tSTRi
7416 : StSize == 2 ? ARM::tSTRHi
7417 : StSize == 1 ? ARM::tSTRBi : 0;
7419 return StSize == 4 ? ARM::t2STR_POST
7420 : StSize == 2 ? ARM::t2STRH_POST
7421 : StSize == 1 ? ARM::t2STRB_POST : 0;
7422 return StSize == 4 ? ARM::STR_POST_IMM
7423 : StSize == 2 ? ARM::STRH_POST
7424 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7427 /// Emit a post-increment load operation with given size. The instructions
7428 /// will be added to BB at Pos.
7429 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7430 const TargetInstrInfo *TII, DebugLoc dl,
7431 unsigned LdSize, unsigned Data, unsigned AddrIn,
7432 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7433 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7434 assert(LdOpc != 0 && "Should have a load opcode");
7436 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7437 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7439 } else if (IsThumb1) {
7440 // load + update AddrIn
7441 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7442 .addReg(AddrIn).addImm(0));
7443 MachineInstrBuilder MIB =
7444 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7445 MIB = AddDefaultT1CC(MIB);
7446 MIB.addReg(AddrIn).addImm(LdSize);
7447 AddDefaultPred(MIB);
7448 } else if (IsThumb2) {
7449 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7450 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7453 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7454 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7455 .addReg(0).addImm(LdSize));
7459 /// Emit a post-increment store operation with given size. The instructions
7460 /// will be added to BB at Pos.
7461 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7462 const TargetInstrInfo *TII, DebugLoc dl,
7463 unsigned StSize, unsigned Data, unsigned AddrIn,
7464 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7465 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7466 assert(StOpc != 0 && "Should have a store opcode");
7468 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7469 .addReg(AddrIn).addImm(0).addReg(Data));
7470 } else if (IsThumb1) {
7471 // store + update AddrIn
7472 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7473 .addReg(AddrIn).addImm(0));
7474 MachineInstrBuilder MIB =
7475 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7476 MIB = AddDefaultT1CC(MIB);
7477 MIB.addReg(AddrIn).addImm(StSize);
7478 AddDefaultPred(MIB);
7479 } else if (IsThumb2) {
7480 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7481 .addReg(Data).addReg(AddrIn).addImm(StSize));
7483 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7484 .addReg(Data).addReg(AddrIn).addReg(0)
7490 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7491 MachineBasicBlock *BB) const {
7492 // This pseudo instruction has 3 operands: dst, src, size
7493 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7494 // Otherwise, we will generate unrolled scalar copies.
7495 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7496 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7497 MachineFunction::iterator It = BB;
7500 unsigned dest = MI->getOperand(0).getReg();
7501 unsigned src = MI->getOperand(1).getReg();
7502 unsigned SizeVal = MI->getOperand(2).getImm();
7503 unsigned Align = MI->getOperand(3).getImm();
7504 DebugLoc dl = MI->getDebugLoc();
7506 MachineFunction *MF = BB->getParent();
7507 MachineRegisterInfo &MRI = MF->getRegInfo();
7508 unsigned UnitSize = 0;
7509 const TargetRegisterClass *TRC = nullptr;
7510 const TargetRegisterClass *VecTRC = nullptr;
7512 bool IsThumb1 = Subtarget->isThumb1Only();
7513 bool IsThumb2 = Subtarget->isThumb2();
7517 } else if (Align & 2) {
7520 // Check whether we can use NEON instructions.
7521 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7522 Subtarget->hasNEON()) {
7523 if ((Align % 16 == 0) && SizeVal >= 16)
7525 else if ((Align % 8 == 0) && SizeVal >= 8)
7528 // Can't use NEON instructions.
7533 // Select the correct opcode and register class for unit size load/store
7534 bool IsNeon = UnitSize >= 8;
7535 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7537 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7538 : UnitSize == 8 ? &ARM::DPRRegClass
7541 unsigned BytesLeft = SizeVal % UnitSize;
7542 unsigned LoopSize = SizeVal - BytesLeft;
7544 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7545 // Use LDR and STR to copy.
7546 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7547 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7548 unsigned srcIn = src;
7549 unsigned destIn = dest;
7550 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7551 unsigned srcOut = MRI.createVirtualRegister(TRC);
7552 unsigned destOut = MRI.createVirtualRegister(TRC);
7553 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7554 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7555 IsThumb1, IsThumb2);
7556 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7557 IsThumb1, IsThumb2);
7562 // Handle the leftover bytes with LDRB and STRB.
7563 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7564 // [destOut] = STRB_POST(scratch, destIn, 1)
7565 for (unsigned i = 0; i < BytesLeft; i++) {
7566 unsigned srcOut = MRI.createVirtualRegister(TRC);
7567 unsigned destOut = MRI.createVirtualRegister(TRC);
7568 unsigned scratch = MRI.createVirtualRegister(TRC);
7569 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7570 IsThumb1, IsThumb2);
7571 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7572 IsThumb1, IsThumb2);
7576 MI->eraseFromParent(); // The instruction is gone now.
7580 // Expand the pseudo op to a loop.
7583 // movw varEnd, # --> with thumb2
7585 // ldrcp varEnd, idx --> without thumb2
7586 // fallthrough --> loopMBB
7588 // PHI varPhi, varEnd, varLoop
7589 // PHI srcPhi, src, srcLoop
7590 // PHI destPhi, dst, destLoop
7591 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7592 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7593 // subs varLoop, varPhi, #UnitSize
7595 // fallthrough --> exitMBB
7597 // epilogue to handle left-over bytes
7598 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7599 // [destOut] = STRB_POST(scratch, destLoop, 1)
7600 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7601 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7602 MF->insert(It, loopMBB);
7603 MF->insert(It, exitMBB);
7605 // Transfer the remainder of BB and its successor edges to exitMBB.
7606 exitMBB->splice(exitMBB->begin(), BB,
7607 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7608 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7610 // Load an immediate to varEnd.
7611 unsigned varEnd = MRI.createVirtualRegister(TRC);
7612 if (Subtarget->useMovt(*MF)) {
7613 unsigned Vtmp = varEnd;
7614 if ((LoopSize & 0xFFFF0000) != 0)
7615 Vtmp = MRI.createVirtualRegister(TRC);
7616 AddDefaultPred(BuildMI(BB, dl,
7617 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7618 Vtmp).addImm(LoopSize & 0xFFFF));
7620 if ((LoopSize & 0xFFFF0000) != 0)
7621 AddDefaultPred(BuildMI(BB, dl,
7622 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7625 .addImm(LoopSize >> 16));
7627 MachineConstantPool *ConstantPool = MF->getConstantPool();
7628 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7629 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7631 // MachineConstantPool wants an explicit alignment.
7632 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7634 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7635 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7638 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7639 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7641 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7642 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7644 BB->addSuccessor(loopMBB);
7646 // Generate the loop body:
7647 // varPhi = PHI(varLoop, varEnd)
7648 // srcPhi = PHI(srcLoop, src)
7649 // destPhi = PHI(destLoop, dst)
7650 MachineBasicBlock *entryBB = BB;
7652 unsigned varLoop = MRI.createVirtualRegister(TRC);
7653 unsigned varPhi = MRI.createVirtualRegister(TRC);
7654 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7655 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7656 unsigned destLoop = MRI.createVirtualRegister(TRC);
7657 unsigned destPhi = MRI.createVirtualRegister(TRC);
7659 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7660 .addReg(varLoop).addMBB(loopMBB)
7661 .addReg(varEnd).addMBB(entryBB);
7662 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7663 .addReg(srcLoop).addMBB(loopMBB)
7664 .addReg(src).addMBB(entryBB);
7665 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7666 .addReg(destLoop).addMBB(loopMBB)
7667 .addReg(dest).addMBB(entryBB);
7669 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7670 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7671 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7672 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7673 IsThumb1, IsThumb2);
7674 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7675 IsThumb1, IsThumb2);
7677 // Decrement loop variable by UnitSize.
7679 MachineInstrBuilder MIB =
7680 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7681 MIB = AddDefaultT1CC(MIB);
7682 MIB.addReg(varPhi).addImm(UnitSize);
7683 AddDefaultPred(MIB);
7685 MachineInstrBuilder MIB =
7686 BuildMI(*BB, BB->end(), dl,
7687 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7688 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7689 MIB->getOperand(5).setReg(ARM::CPSR);
7690 MIB->getOperand(5).setIsDef(true);
7692 BuildMI(*BB, BB->end(), dl,
7693 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7694 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7696 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7697 BB->addSuccessor(loopMBB);
7698 BB->addSuccessor(exitMBB);
7700 // Add epilogue to handle BytesLeft.
7702 MachineInstr *StartOfExit = exitMBB->begin();
7704 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7705 // [destOut] = STRB_POST(scratch, destLoop, 1)
7706 unsigned srcIn = srcLoop;
7707 unsigned destIn = destLoop;
7708 for (unsigned i = 0; i < BytesLeft; i++) {
7709 unsigned srcOut = MRI.createVirtualRegister(TRC);
7710 unsigned destOut = MRI.createVirtualRegister(TRC);
7711 unsigned scratch = MRI.createVirtualRegister(TRC);
7712 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7713 IsThumb1, IsThumb2);
7714 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7715 IsThumb1, IsThumb2);
7720 MI->eraseFromParent(); // The instruction is gone now.
7725 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7726 MachineBasicBlock *MBB) const {
7727 const TargetMachine &TM = getTargetMachine();
7728 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7729 DebugLoc DL = MI->getDebugLoc();
7731 assert(Subtarget->isTargetWindows() &&
7732 "__chkstk is only supported on Windows");
7733 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7735 // __chkstk takes the number of words to allocate on the stack in R4, and
7736 // returns the stack adjustment in number of bytes in R4. This will not
7737 // clober any other registers (other than the obvious lr).
7739 // Although, technically, IP should be considered a register which may be
7740 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7741 // thumb-2 environment, so there is no interworking required. As a result, we
7742 // do not expect a veneer to be emitted by the linker, clobbering IP.
7744 // Each module receives its own copy of __chkstk, so no import thunk is
7745 // required, again, ensuring that IP is not clobbered.
7747 // Finally, although some linkers may theoretically provide a trampoline for
7748 // out of range calls (which is quite common due to a 32M range limitation of
7749 // branches for Thumb), we can generate the long-call version via
7750 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7753 switch (TM.getCodeModel()) {
7754 case CodeModel::Small:
7755 case CodeModel::Medium:
7756 case CodeModel::Default:
7757 case CodeModel::Kernel:
7758 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7759 .addImm((unsigned)ARMCC::AL).addReg(0)
7760 .addExternalSymbol("__chkstk")
7761 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7762 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7763 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7765 case CodeModel::Large:
7766 case CodeModel::JITDefault: {
7767 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7768 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7770 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7771 .addExternalSymbol("__chkstk");
7772 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7773 .addImm((unsigned)ARMCC::AL).addReg(0)
7774 .addReg(Reg, RegState::Kill)
7775 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7776 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7777 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7782 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7784 .addReg(ARM::SP).addReg(ARM::R4)));
7786 MI->eraseFromParent();
7791 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7792 MachineBasicBlock *MBB) const {
7793 DebugLoc DL = MI->getDebugLoc();
7794 MachineFunction *MF = MBB->getParent();
7795 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7797 MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7798 MF->push_back(ContBB);
7799 ContBB->splice(ContBB->begin(), MBB,
7800 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7801 MBB->addSuccessor(ContBB);
7803 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7804 MF->push_back(TrapBB);
7805 BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7806 MBB->addSuccessor(TrapBB);
7808 BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7809 .addReg(MI->getOperand(0).getReg())
7812 MI->eraseFromParent();
7817 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7818 MachineBasicBlock *BB) const {
7819 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7820 DebugLoc dl = MI->getDebugLoc();
7821 bool isThumb2 = Subtarget->isThumb2();
7822 switch (MI->getOpcode()) {
7825 llvm_unreachable("Unexpected instr type to insert");
7827 // The Thumb2 pre-indexed stores have the same MI operands, they just
7828 // define them differently in the .td files from the isel patterns, so
7829 // they need pseudos.
7830 case ARM::t2STR_preidx:
7831 MI->setDesc(TII->get(ARM::t2STR_PRE));
7833 case ARM::t2STRB_preidx:
7834 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7836 case ARM::t2STRH_preidx:
7837 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7840 case ARM::STRi_preidx:
7841 case ARM::STRBi_preidx: {
7842 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7843 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7844 // Decode the offset.
7845 unsigned Offset = MI->getOperand(4).getImm();
7846 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7847 Offset = ARM_AM::getAM2Offset(Offset);
7851 MachineMemOperand *MMO = *MI->memoperands_begin();
7852 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7853 .addOperand(MI->getOperand(0)) // Rn_wb
7854 .addOperand(MI->getOperand(1)) // Rt
7855 .addOperand(MI->getOperand(2)) // Rn
7856 .addImm(Offset) // offset (skip GPR==zero_reg)
7857 .addOperand(MI->getOperand(5)) // pred
7858 .addOperand(MI->getOperand(6))
7859 .addMemOperand(MMO);
7860 MI->eraseFromParent();
7863 case ARM::STRr_preidx:
7864 case ARM::STRBr_preidx:
7865 case ARM::STRH_preidx: {
7867 switch (MI->getOpcode()) {
7868 default: llvm_unreachable("unexpected opcode!");
7869 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7870 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7871 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7873 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7874 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7875 MIB.addOperand(MI->getOperand(i));
7876 MI->eraseFromParent();
7880 case ARM::tMOVCCr_pseudo: {
7881 // To "insert" a SELECT_CC instruction, we actually have to insert the
7882 // diamond control-flow pattern. The incoming instruction knows the
7883 // destination vreg to set, the condition code register to branch on, the
7884 // true/false values to select between, and a branch opcode to use.
7885 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7886 MachineFunction::iterator It = BB;
7892 // cmpTY ccX, r1, r2
7894 // fallthrough --> copy0MBB
7895 MachineBasicBlock *thisMBB = BB;
7896 MachineFunction *F = BB->getParent();
7897 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7898 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7899 F->insert(It, copy0MBB);
7900 F->insert(It, sinkMBB);
7902 // Transfer the remainder of BB and its successor edges to sinkMBB.
7903 sinkMBB->splice(sinkMBB->begin(), BB,
7904 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7905 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7907 BB->addSuccessor(copy0MBB);
7908 BB->addSuccessor(sinkMBB);
7910 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7911 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7914 // %FalseValue = ...
7915 // # fallthrough to sinkMBB
7918 // Update machine-CFG edges
7919 BB->addSuccessor(sinkMBB);
7922 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7925 BuildMI(*BB, BB->begin(), dl,
7926 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7927 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7928 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7930 MI->eraseFromParent(); // The pseudo instruction is gone now.
7935 case ARM::BCCZi64: {
7936 // If there is an unconditional branch to the other successor, remove it.
7937 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7939 // Compare both parts that make up the double comparison separately for
7941 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7943 unsigned LHS1 = MI->getOperand(1).getReg();
7944 unsigned LHS2 = MI->getOperand(2).getReg();
7946 AddDefaultPred(BuildMI(BB, dl,
7947 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7948 .addReg(LHS1).addImm(0));
7949 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7950 .addReg(LHS2).addImm(0)
7951 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7953 unsigned RHS1 = MI->getOperand(3).getReg();
7954 unsigned RHS2 = MI->getOperand(4).getReg();
7955 AddDefaultPred(BuildMI(BB, dl,
7956 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7957 .addReg(LHS1).addReg(RHS1));
7958 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7959 .addReg(LHS2).addReg(RHS2)
7960 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7963 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7964 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7965 if (MI->getOperand(0).getImm() == ARMCC::NE)
7966 std::swap(destMBB, exitMBB);
7968 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7969 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7971 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7973 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7975 MI->eraseFromParent(); // The pseudo instruction is gone now.
7979 case ARM::Int_eh_sjlj_setjmp:
7980 case ARM::Int_eh_sjlj_setjmp_nofp:
7981 case ARM::tInt_eh_sjlj_setjmp:
7982 case ARM::t2Int_eh_sjlj_setjmp:
7983 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7986 case ARM::Int_eh_sjlj_setup_dispatch:
7987 EmitSjLjDispatchBlock(MI, BB);
7992 // To insert an ABS instruction, we have to insert the
7993 // diamond control-flow pattern. The incoming instruction knows the
7994 // source vreg to test against 0, the destination vreg to set,
7995 // the condition code register to branch on, the
7996 // true/false values to select between, and a branch opcode to use.
8001 // BCC (branch to SinkBB if V0 >= 0)
8002 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
8003 // SinkBB: V1 = PHI(V2, V3)
8004 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8005 MachineFunction::iterator BBI = BB;
8007 MachineFunction *Fn = BB->getParent();
8008 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8009 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8010 Fn->insert(BBI, RSBBB);
8011 Fn->insert(BBI, SinkBB);
8013 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8014 unsigned int ABSDstReg = MI->getOperand(0).getReg();
8015 bool ABSSrcKIll = MI->getOperand(1).isKill();
8016 bool isThumb2 = Subtarget->isThumb2();
8017 MachineRegisterInfo &MRI = Fn->getRegInfo();
8018 // In Thumb mode S must not be specified if source register is the SP or
8019 // PC and if destination register is the SP, so restrict register class
8020 unsigned NewRsbDstReg =
8021 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8023 // Transfer the remainder of BB and its successor edges to sinkMBB.
8024 SinkBB->splice(SinkBB->begin(), BB,
8025 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8026 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8028 BB->addSuccessor(RSBBB);
8029 BB->addSuccessor(SinkBB);
8031 // fall through to SinkMBB
8032 RSBBB->addSuccessor(SinkBB);
8034 // insert a cmp at the end of BB
8035 AddDefaultPred(BuildMI(BB, dl,
8036 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8037 .addReg(ABSSrcReg).addImm(0));
8039 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8041 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8042 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8044 // insert rsbri in RSBBB
8045 // Note: BCC and rsbri will be converted into predicated rsbmi
8046 // by if-conversion pass
8047 BuildMI(*RSBBB, RSBBB->begin(), dl,
8048 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8049 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8050 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8052 // insert PHI in SinkBB,
8053 // reuse ABSDstReg to not change uses of ABS instruction
8054 BuildMI(*SinkBB, SinkBB->begin(), dl,
8055 TII->get(ARM::PHI), ABSDstReg)
8056 .addReg(NewRsbDstReg).addMBB(RSBBB)
8057 .addReg(ABSSrcReg).addMBB(BB);
8059 // remove ABS instruction
8060 MI->eraseFromParent();
8062 // return last added BB
8065 case ARM::COPY_STRUCT_BYVAL_I32:
8067 return EmitStructByval(MI, BB);
8068 case ARM::WIN__CHKSTK:
8069 return EmitLowered__chkstk(MI, BB);
8070 case ARM::WIN__DBZCHK:
8071 return EmitLowered__dbzchk(MI, BB);
8075 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8076 SDNode *Node) const {
8077 const MCInstrDesc *MCID = &MI->getDesc();
8078 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8079 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8080 // operand is still set to noreg. If needed, set the optional operand's
8081 // register to CPSR, and remove the redundant implicit def.
8083 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8085 // Rename pseudo opcodes.
8086 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8088 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8089 MCID = &TII->get(NewOpc);
8091 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8092 "converted opcode should be the same except for cc_out");
8096 // Add the optional cc_out operand
8097 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8099 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8101 // Any ARM instruction that sets the 's' bit should specify an optional
8102 // "cc_out" operand in the last operand position.
8103 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8104 assert(!NewOpc && "Optional cc_out operand required");
8107 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8108 // since we already have an optional CPSR def.
8109 bool definesCPSR = false;
8110 bool deadCPSR = false;
8111 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8113 const MachineOperand &MO = MI->getOperand(i);
8114 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8118 MI->RemoveOperand(i);
8123 assert(!NewOpc && "Optional cc_out operand required");
8126 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8128 assert(!MI->getOperand(ccOutIdx).getReg() &&
8129 "expect uninitialized optional cc_out operand");
8133 // If this instruction was defined with an optional CPSR def and its dag node
8134 // had a live implicit CPSR def, then activate the optional CPSR def.
8135 MachineOperand &MO = MI->getOperand(ccOutIdx);
8136 MO.setReg(ARM::CPSR);
8140 //===----------------------------------------------------------------------===//
8141 // ARM Optimization Hooks
8142 //===----------------------------------------------------------------------===//
8144 // Helper function that checks if N is a null or all ones constant.
8145 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8146 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8149 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8152 // Return true if N is conditionally 0 or all ones.
8153 // Detects these expressions where cc is an i1 value:
8155 // (select cc 0, y) [AllOnes=0]
8156 // (select cc y, 0) [AllOnes=0]
8157 // (zext cc) [AllOnes=0]
8158 // (sext cc) [AllOnes=0/1]
8159 // (select cc -1, y) [AllOnes=1]
8160 // (select cc y, -1) [AllOnes=1]
8162 // Invert is set when N is the null/all ones constant when CC is false.
8163 // OtherOp is set to the alternative value of N.
8164 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8165 SDValue &CC, bool &Invert,
8167 SelectionDAG &DAG) {
8168 switch (N->getOpcode()) {
8169 default: return false;
8171 CC = N->getOperand(0);
8172 SDValue N1 = N->getOperand(1);
8173 SDValue N2 = N->getOperand(2);
8174 if (isZeroOrAllOnes(N1, AllOnes)) {
8179 if (isZeroOrAllOnes(N2, AllOnes)) {
8186 case ISD::ZERO_EXTEND:
8187 // (zext cc) can never be the all ones value.
8191 case ISD::SIGN_EXTEND: {
8193 EVT VT = N->getValueType(0);
8194 CC = N->getOperand(0);
8195 if (CC.getValueType() != MVT::i1)
8199 // When looking for an AllOnes constant, N is an sext, and the 'other'
8201 OtherOp = DAG.getConstant(0, dl, VT);
8202 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8203 // When looking for a 0 constant, N can be zext or sext.
8204 OtherOp = DAG.getConstant(1, dl, VT);
8206 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8213 // Combine a constant select operand into its use:
8215 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8216 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8217 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8218 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8219 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8221 // The transform is rejected if the select doesn't have a constant operand that
8222 // is null, or all ones when AllOnes is set.
8224 // Also recognize sext/zext from i1:
8226 // (add (zext cc), x) -> (select cc (add x, 1), x)
8227 // (add (sext cc), x) -> (select cc (add x, -1), x)
8229 // These transformations eventually create predicated instructions.
8231 // @param N The node to transform.
8232 // @param Slct The N operand that is a select.
8233 // @param OtherOp The other N operand (x above).
8234 // @param DCI Context.
8235 // @param AllOnes Require the select constant to be all ones instead of null.
8236 // @returns The new node, or SDValue() on failure.
8238 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8239 TargetLowering::DAGCombinerInfo &DCI,
8240 bool AllOnes = false) {
8241 SelectionDAG &DAG = DCI.DAG;
8242 EVT VT = N->getValueType(0);
8243 SDValue NonConstantVal;
8246 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8247 NonConstantVal, DAG))
8250 // Slct is now know to be the desired identity constant when CC is true.
8251 SDValue TrueVal = OtherOp;
8252 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8253 OtherOp, NonConstantVal);
8254 // Unless SwapSelectOps says CC should be false.
8256 std::swap(TrueVal, FalseVal);
8258 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8259 CCOp, TrueVal, FalseVal);
8262 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8264 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8265 TargetLowering::DAGCombinerInfo &DCI) {
8266 SDValue N0 = N->getOperand(0);
8267 SDValue N1 = N->getOperand(1);
8268 if (N0.getNode()->hasOneUse()) {
8269 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8270 if (Result.getNode())
8273 if (N1.getNode()->hasOneUse()) {
8274 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8275 if (Result.getNode())
8281 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8282 // (only after legalization).
8283 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8284 TargetLowering::DAGCombinerInfo &DCI,
8285 const ARMSubtarget *Subtarget) {
8287 // Only perform optimization if after legalize, and if NEON is available. We
8288 // also expected both operands to be BUILD_VECTORs.
8289 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8290 || N0.getOpcode() != ISD::BUILD_VECTOR
8291 || N1.getOpcode() != ISD::BUILD_VECTOR)
8294 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8295 EVT VT = N->getValueType(0);
8296 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8299 // Check that the vector operands are of the right form.
8300 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8301 // operands, where N is the size of the formed vector.
8302 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8303 // index such that we have a pair wise add pattern.
8305 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8306 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8308 SDValue Vec = N0->getOperand(0)->getOperand(0);
8309 SDNode *V = Vec.getNode();
8310 unsigned nextIndex = 0;
8312 // For each operands to the ADD which are BUILD_VECTORs,
8313 // check to see if each of their operands are an EXTRACT_VECTOR with
8314 // the same vector and appropriate index.
8315 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8316 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8317 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8319 SDValue ExtVec0 = N0->getOperand(i);
8320 SDValue ExtVec1 = N1->getOperand(i);
8322 // First operand is the vector, verify its the same.
8323 if (V != ExtVec0->getOperand(0).getNode() ||
8324 V != ExtVec1->getOperand(0).getNode())
8327 // Second is the constant, verify its correct.
8328 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8329 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8331 // For the constant, we want to see all the even or all the odd.
8332 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8333 || C1->getZExtValue() != nextIndex+1)
8342 // Create VPADDL node.
8343 SelectionDAG &DAG = DCI.DAG;
8344 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8348 // Build operand list.
8349 SmallVector<SDValue, 8> Ops;
8350 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8351 TLI.getPointerTy(DAG.getDataLayout())));
8353 // Input is the vector.
8356 // Get widened type and narrowed type.
8358 unsigned numElem = VT.getVectorNumElements();
8360 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8361 switch (inputLaneType.getSimpleVT().SimpleTy) {
8362 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8363 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8364 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8366 llvm_unreachable("Invalid vector element type for padd optimization.");
8369 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8370 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8371 return DAG.getNode(ExtOp, dl, VT, tmp);
8374 static SDValue findMUL_LOHI(SDValue V) {
8375 if (V->getOpcode() == ISD::UMUL_LOHI ||
8376 V->getOpcode() == ISD::SMUL_LOHI)
8381 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8382 TargetLowering::DAGCombinerInfo &DCI,
8383 const ARMSubtarget *Subtarget) {
8385 if (Subtarget->isThumb1Only()) return SDValue();
8387 // Only perform the checks after legalize when the pattern is available.
8388 if (DCI.isBeforeLegalize()) return SDValue();
8390 // Look for multiply add opportunities.
8391 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8392 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8393 // a glue link from the first add to the second add.
8394 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8395 // a S/UMLAL instruction.
8398 // / \ [no multiline comment]
8404 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8405 SDValue AddcOp0 = AddcNode->getOperand(0);
8406 SDValue AddcOp1 = AddcNode->getOperand(1);
8408 // Check if the two operands are from the same mul_lohi node.
8409 if (AddcOp0.getNode() == AddcOp1.getNode())
8412 assert(AddcNode->getNumValues() == 2 &&
8413 AddcNode->getValueType(0) == MVT::i32 &&
8414 "Expect ADDC with two result values. First: i32");
8416 // Check that we have a glued ADDC node.
8417 if (AddcNode->getValueType(1) != MVT::Glue)
8420 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8421 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8422 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8423 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8424 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8427 // Look for the glued ADDE.
8428 SDNode* AddeNode = AddcNode->getGluedUser();
8432 // Make sure it is really an ADDE.
8433 if (AddeNode->getOpcode() != ISD::ADDE)
8436 assert(AddeNode->getNumOperands() == 3 &&
8437 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8438 "ADDE node has the wrong inputs");
8440 // Check for the triangle shape.
8441 SDValue AddeOp0 = AddeNode->getOperand(0);
8442 SDValue AddeOp1 = AddeNode->getOperand(1);
8444 // Make sure that the ADDE operands are not coming from the same node.
8445 if (AddeOp0.getNode() == AddeOp1.getNode())
8448 // Find the MUL_LOHI node walking up ADDE's operands.
8449 bool IsLeftOperandMUL = false;
8450 SDValue MULOp = findMUL_LOHI(AddeOp0);
8451 if (MULOp == SDValue())
8452 MULOp = findMUL_LOHI(AddeOp1);
8454 IsLeftOperandMUL = true;
8455 if (MULOp == SDValue())
8458 // Figure out the right opcode.
8459 unsigned Opc = MULOp->getOpcode();
8460 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8462 // Figure out the high and low input values to the MLAL node.
8463 SDValue* HiAdd = nullptr;
8464 SDValue* LoMul = nullptr;
8465 SDValue* LowAdd = nullptr;
8467 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8468 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8471 if (IsLeftOperandMUL)
8477 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8478 // whose low result is fed to the ADDC we are checking.
8480 if (AddcOp0 == MULOp.getValue(0)) {
8484 if (AddcOp1 == MULOp.getValue(0)) {
8492 // Create the merged node.
8493 SelectionDAG &DAG = DCI.DAG;
8495 // Build operand list.
8496 SmallVector<SDValue, 8> Ops;
8497 Ops.push_back(LoMul->getOperand(0));
8498 Ops.push_back(LoMul->getOperand(1));
8499 Ops.push_back(*LowAdd);
8500 Ops.push_back(*HiAdd);
8502 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8503 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8505 // Replace the ADDs' nodes uses by the MLA node's values.
8506 SDValue HiMLALResult(MLALNode.getNode(), 1);
8507 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8509 SDValue LoMLALResult(MLALNode.getNode(), 0);
8510 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8512 // Return original node to notify the driver to stop replacing.
8513 SDValue resNode(AddcNode, 0);
8517 /// PerformADDCCombine - Target-specific dag combine transform from
8518 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8519 static SDValue PerformADDCCombine(SDNode *N,
8520 TargetLowering::DAGCombinerInfo &DCI,
8521 const ARMSubtarget *Subtarget) {
8523 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8527 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8528 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8529 /// called with the default operands, and if that fails, with commuted
8531 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8532 TargetLowering::DAGCombinerInfo &DCI,
8533 const ARMSubtarget *Subtarget){
8535 // Attempt to create vpaddl for this add.
8536 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8537 if (Result.getNode())
8540 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8541 if (N0.getNode()->hasOneUse()) {
8542 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8543 if (Result.getNode()) return Result;
8548 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8550 static SDValue PerformADDCombine(SDNode *N,
8551 TargetLowering::DAGCombinerInfo &DCI,
8552 const ARMSubtarget *Subtarget) {
8553 SDValue N0 = N->getOperand(0);
8554 SDValue N1 = N->getOperand(1);
8556 // First try with the default operand order.
8557 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8558 if (Result.getNode())
8561 // If that didn't work, try again with the operands commuted.
8562 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8565 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8567 static SDValue PerformSUBCombine(SDNode *N,
8568 TargetLowering::DAGCombinerInfo &DCI) {
8569 SDValue N0 = N->getOperand(0);
8570 SDValue N1 = N->getOperand(1);
8572 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8573 if (N1.getNode()->hasOneUse()) {
8574 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8575 if (Result.getNode()) return Result;
8581 /// PerformVMULCombine
8582 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8583 /// special multiplier accumulator forwarding.
8589 // However, for (A + B) * (A + B),
8596 static SDValue PerformVMULCombine(SDNode *N,
8597 TargetLowering::DAGCombinerInfo &DCI,
8598 const ARMSubtarget *Subtarget) {
8599 if (!Subtarget->hasVMLxForwarding())
8602 SelectionDAG &DAG = DCI.DAG;
8603 SDValue N0 = N->getOperand(0);
8604 SDValue N1 = N->getOperand(1);
8605 unsigned Opcode = N0.getOpcode();
8606 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8607 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8608 Opcode = N1.getOpcode();
8609 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8610 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8618 EVT VT = N->getValueType(0);
8620 SDValue N00 = N0->getOperand(0);
8621 SDValue N01 = N0->getOperand(1);
8622 return DAG.getNode(Opcode, DL, VT,
8623 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8624 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8627 static SDValue PerformMULCombine(SDNode *N,
8628 TargetLowering::DAGCombinerInfo &DCI,
8629 const ARMSubtarget *Subtarget) {
8630 SelectionDAG &DAG = DCI.DAG;
8632 if (Subtarget->isThumb1Only())
8635 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8638 EVT VT = N->getValueType(0);
8639 if (VT.is64BitVector() || VT.is128BitVector())
8640 return PerformVMULCombine(N, DCI, Subtarget);
8644 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8648 int64_t MulAmt = C->getSExtValue();
8649 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8651 ShiftAmt = ShiftAmt & (32 - 1);
8652 SDValue V = N->getOperand(0);
8656 MulAmt >>= ShiftAmt;
8659 if (isPowerOf2_32(MulAmt - 1)) {
8660 // (mul x, 2^N + 1) => (add (shl x, N), x)
8661 Res = DAG.getNode(ISD::ADD, DL, VT,
8663 DAG.getNode(ISD::SHL, DL, VT,
8665 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8667 } else if (isPowerOf2_32(MulAmt + 1)) {
8668 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8669 Res = DAG.getNode(ISD::SUB, DL, VT,
8670 DAG.getNode(ISD::SHL, DL, VT,
8672 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8678 uint64_t MulAmtAbs = -MulAmt;
8679 if (isPowerOf2_32(MulAmtAbs + 1)) {
8680 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8681 Res = DAG.getNode(ISD::SUB, DL, VT,
8683 DAG.getNode(ISD::SHL, DL, VT,
8685 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8687 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8688 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8689 Res = DAG.getNode(ISD::ADD, DL, VT,
8691 DAG.getNode(ISD::SHL, DL, VT,
8693 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8695 Res = DAG.getNode(ISD::SUB, DL, VT,
8696 DAG.getConstant(0, DL, MVT::i32), Res);
8703 Res = DAG.getNode(ISD::SHL, DL, VT,
8704 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8706 // Do not add new nodes to DAG combiner worklist.
8707 DCI.CombineTo(N, Res, false);
8711 static SDValue PerformANDCombine(SDNode *N,
8712 TargetLowering::DAGCombinerInfo &DCI,
8713 const ARMSubtarget *Subtarget) {
8715 // Attempt to use immediate-form VBIC
8716 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8718 EVT VT = N->getValueType(0);
8719 SelectionDAG &DAG = DCI.DAG;
8721 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8724 APInt SplatBits, SplatUndef;
8725 unsigned SplatBitSize;
8728 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8729 if (SplatBitSize <= 64) {
8731 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8732 SplatUndef.getZExtValue(), SplatBitSize,
8733 DAG, dl, VbicVT, VT.is128BitVector(),
8735 if (Val.getNode()) {
8737 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8738 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8739 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8744 if (!Subtarget->isThumb1Only()) {
8745 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8746 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8747 if (Result.getNode())
8754 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8755 static SDValue PerformORCombine(SDNode *N,
8756 TargetLowering::DAGCombinerInfo &DCI,
8757 const ARMSubtarget *Subtarget) {
8758 // Attempt to use immediate-form VORR
8759 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8761 EVT VT = N->getValueType(0);
8762 SelectionDAG &DAG = DCI.DAG;
8764 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8767 APInt SplatBits, SplatUndef;
8768 unsigned SplatBitSize;
8770 if (BVN && Subtarget->hasNEON() &&
8771 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8772 if (SplatBitSize <= 64) {
8774 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8775 SplatUndef.getZExtValue(), SplatBitSize,
8776 DAG, dl, VorrVT, VT.is128BitVector(),
8778 if (Val.getNode()) {
8780 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8781 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8782 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8787 if (!Subtarget->isThumb1Only()) {
8788 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8789 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8790 if (Result.getNode())
8794 // The code below optimizes (or (and X, Y), Z).
8795 // The AND operand needs to have a single user to make these optimizations
8797 SDValue N0 = N->getOperand(0);
8798 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8800 SDValue N1 = N->getOperand(1);
8802 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8803 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8804 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8806 unsigned SplatBitSize;
8809 APInt SplatBits0, SplatBits1;
8810 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8811 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8812 // Ensure that the second operand of both ands are constants
8813 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8814 HasAnyUndefs) && !HasAnyUndefs) {
8815 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8816 HasAnyUndefs) && !HasAnyUndefs) {
8817 // Ensure that the bit width of the constants are the same and that
8818 // the splat arguments are logical inverses as per the pattern we
8819 // are trying to simplify.
8820 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8821 SplatBits0 == ~SplatBits1) {
8822 // Canonicalize the vector type to make instruction selection
8824 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8825 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8829 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8835 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8838 // BFI is only available on V6T2+
8839 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8843 // 1) or (and A, mask), val => ARMbfi A, val, mask
8844 // iff (val & mask) == val
8846 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8847 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8848 // && mask == ~mask2
8849 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8850 // && ~mask == mask2
8851 // (i.e., copy a bitfield value into another bitfield of the same width)
8856 SDValue N00 = N0.getOperand(0);
8858 // The value and the mask need to be constants so we can verify this is
8859 // actually a bitfield set. If the mask is 0xffff, we can do better
8860 // via a movt instruction, so don't use BFI in that case.
8861 SDValue MaskOp = N0.getOperand(1);
8862 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8865 unsigned Mask = MaskC->getZExtValue();
8869 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8870 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8872 unsigned Val = N1C->getZExtValue();
8873 if ((Val & ~Mask) != Val)
8876 if (ARM::isBitFieldInvertedMask(Mask)) {
8877 Val >>= countTrailingZeros(~Mask);
8879 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8880 DAG.getConstant(Val, DL, MVT::i32),
8881 DAG.getConstant(Mask, DL, MVT::i32));
8883 // Do not add new nodes to DAG combiner worklist.
8884 DCI.CombineTo(N, Res, false);
8887 } else if (N1.getOpcode() == ISD::AND) {
8888 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8889 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8892 unsigned Mask2 = N11C->getZExtValue();
8894 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8896 if (ARM::isBitFieldInvertedMask(Mask) &&
8898 // The pack halfword instruction works better for masks that fit it,
8899 // so use that when it's available.
8900 if (Subtarget->hasT2ExtractPack() &&
8901 (Mask == 0xffff || Mask == 0xffff0000))
8904 unsigned amt = countTrailingZeros(Mask2);
8905 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8906 DAG.getConstant(amt, DL, MVT::i32));
8907 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8908 DAG.getConstant(Mask, DL, MVT::i32));
8909 // Do not add new nodes to DAG combiner worklist.
8910 DCI.CombineTo(N, Res, false);
8912 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8914 // The pack halfword instruction works better for masks that fit it,
8915 // so use that when it's available.
8916 if (Subtarget->hasT2ExtractPack() &&
8917 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8920 unsigned lsb = countTrailingZeros(Mask);
8921 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8922 DAG.getConstant(lsb, DL, MVT::i32));
8923 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8924 DAG.getConstant(Mask2, DL, MVT::i32));
8925 // Do not add new nodes to DAG combiner worklist.
8926 DCI.CombineTo(N, Res, false);
8931 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8932 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8933 ARM::isBitFieldInvertedMask(~Mask)) {
8934 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8935 // where lsb(mask) == #shamt and masked bits of B are known zero.
8936 SDValue ShAmt = N00.getOperand(1);
8937 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8938 unsigned LSB = countTrailingZeros(Mask);
8942 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8943 DAG.getConstant(~Mask, DL, MVT::i32));
8945 // Do not add new nodes to DAG combiner worklist.
8946 DCI.CombineTo(N, Res, false);
8952 static SDValue PerformXORCombine(SDNode *N,
8953 TargetLowering::DAGCombinerInfo &DCI,
8954 const ARMSubtarget *Subtarget) {
8955 EVT VT = N->getValueType(0);
8956 SelectionDAG &DAG = DCI.DAG;
8958 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8961 if (!Subtarget->isThumb1Only()) {
8962 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8963 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8964 if (Result.getNode())
8971 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8972 /// the bits being cleared by the AND are not demanded by the BFI.
8973 static SDValue PerformBFICombine(SDNode *N,
8974 TargetLowering::DAGCombinerInfo &DCI) {
8975 SDValue N1 = N->getOperand(1);
8976 if (N1.getOpcode() == ISD::AND) {
8977 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8980 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8981 unsigned LSB = countTrailingZeros(~InvMask);
8982 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8984 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8985 "undefined behavior");
8986 unsigned Mask = (1u << Width) - 1;
8987 unsigned Mask2 = N11C->getZExtValue();
8988 if ((Mask & (~Mask2)) == 0)
8989 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8990 N->getOperand(0), N1.getOperand(0),
8996 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8997 /// ARMISD::VMOVRRD.
8998 static SDValue PerformVMOVRRDCombine(SDNode *N,
8999 TargetLowering::DAGCombinerInfo &DCI,
9000 const ARMSubtarget *Subtarget) {
9001 // vmovrrd(vmovdrr x, y) -> x,y
9002 SDValue InDouble = N->getOperand(0);
9003 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9004 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9006 // vmovrrd(load f64) -> (load i32), (load i32)
9007 SDNode *InNode = InDouble.getNode();
9008 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9009 InNode->getValueType(0) == MVT::f64 &&
9010 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9011 !cast<LoadSDNode>(InNode)->isVolatile()) {
9012 // TODO: Should this be done for non-FrameIndex operands?
9013 LoadSDNode *LD = cast<LoadSDNode>(InNode);
9015 SelectionDAG &DAG = DCI.DAG;
9017 SDValue BasePtr = LD->getBasePtr();
9018 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9019 LD->getPointerInfo(), LD->isVolatile(),
9020 LD->isNonTemporal(), LD->isInvariant(),
9021 LD->getAlignment());
9023 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9024 DAG.getConstant(4, DL, MVT::i32));
9025 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9026 LD->getPointerInfo(), LD->isVolatile(),
9027 LD->isNonTemporal(), LD->isInvariant(),
9028 std::min(4U, LD->getAlignment() / 2));
9030 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9031 if (DCI.DAG.getDataLayout().isBigEndian())
9032 std::swap (NewLD1, NewLD2);
9033 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9040 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9041 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
9042 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9043 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9044 SDValue Op0 = N->getOperand(0);
9045 SDValue Op1 = N->getOperand(1);
9046 if (Op0.getOpcode() == ISD::BITCAST)
9047 Op0 = Op0.getOperand(0);
9048 if (Op1.getOpcode() == ISD::BITCAST)
9049 Op1 = Op1.getOperand(0);
9050 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9051 Op0.getNode() == Op1.getNode() &&
9052 Op0.getResNo() == 0 && Op1.getResNo() == 1)
9053 return DAG.getNode(ISD::BITCAST, SDLoc(N),
9054 N->getValueType(0), Op0.getOperand(0));
9058 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9059 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9060 /// i64 vector to have f64 elements, since the value can then be loaded
9061 /// directly into a VFP register.
9062 static bool hasNormalLoadOperand(SDNode *N) {
9063 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9064 for (unsigned i = 0; i < NumElts; ++i) {
9065 SDNode *Elt = N->getOperand(i).getNode();
9066 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9072 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9073 /// ISD::BUILD_VECTOR.
9074 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9075 TargetLowering::DAGCombinerInfo &DCI,
9076 const ARMSubtarget *Subtarget) {
9077 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9078 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9079 // into a pair of GPRs, which is fine when the value is used as a scalar,
9080 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9081 SelectionDAG &DAG = DCI.DAG;
9082 if (N->getNumOperands() == 2) {
9083 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9088 // Load i64 elements as f64 values so that type legalization does not split
9089 // them up into i32 values.
9090 EVT VT = N->getValueType(0);
9091 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9094 SmallVector<SDValue, 8> Ops;
9095 unsigned NumElts = VT.getVectorNumElements();
9096 for (unsigned i = 0; i < NumElts; ++i) {
9097 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9099 // Make the DAGCombiner fold the bitcast.
9100 DCI.AddToWorklist(V.getNode());
9102 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9103 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9104 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9107 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9109 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9110 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9111 // At that time, we may have inserted bitcasts from integer to float.
9112 // If these bitcasts have survived DAGCombine, change the lowering of this
9113 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9114 // force to use floating point types.
9116 // Make sure we can change the type of the vector.
9117 // This is possible iff:
9118 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9119 // 1.1. Vector is used only once.
9120 // 1.2. Use is a bit convert to an integer type.
9121 // 2. The size of its operands are 32-bits (64-bits are not legal).
9122 EVT VT = N->getValueType(0);
9123 EVT EltVT = VT.getVectorElementType();
9125 // Check 1.1. and 2.
9126 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9129 // By construction, the input type must be float.
9130 assert(EltVT == MVT::f32 && "Unexpected type!");
9133 SDNode *Use = *N->use_begin();
9134 if (Use->getOpcode() != ISD::BITCAST ||
9135 Use->getValueType(0).isFloatingPoint())
9138 // Check profitability.
9139 // Model is, if more than half of the relevant operands are bitcast from
9140 // i32, turn the build_vector into a sequence of insert_vector_elt.
9141 // Relevant operands are everything that is not statically
9142 // (i.e., at compile time) bitcasted.
9143 unsigned NumOfBitCastedElts = 0;
9144 unsigned NumElts = VT.getVectorNumElements();
9145 unsigned NumOfRelevantElts = NumElts;
9146 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9147 SDValue Elt = N->getOperand(Idx);
9148 if (Elt->getOpcode() == ISD::BITCAST) {
9149 // Assume only bit cast to i32 will go away.
9150 if (Elt->getOperand(0).getValueType() == MVT::i32)
9151 ++NumOfBitCastedElts;
9152 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9153 // Constants are statically casted, thus do not count them as
9154 // relevant operands.
9155 --NumOfRelevantElts;
9158 // Check if more than half of the elements require a non-free bitcast.
9159 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9162 SelectionDAG &DAG = DCI.DAG;
9163 // Create the new vector type.
9164 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9165 // Check if the type is legal.
9166 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9167 if (!TLI.isTypeLegal(VecVT))
9171 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9172 // => BITCAST INSERT_VECTOR_ELT
9173 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9175 SDValue Vec = DAG.getUNDEF(VecVT);
9177 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9178 SDValue V = N->getOperand(Idx);
9179 if (V.getOpcode() == ISD::UNDEF)
9181 if (V.getOpcode() == ISD::BITCAST &&
9182 V->getOperand(0).getValueType() == MVT::i32)
9183 // Fold obvious case.
9184 V = V.getOperand(0);
9186 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9187 // Make the DAGCombiner fold the bitcasts.
9188 DCI.AddToWorklist(V.getNode());
9190 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9191 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9193 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9194 // Make the DAGCombiner fold the bitcasts.
9195 DCI.AddToWorklist(Vec.getNode());
9199 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9200 /// ISD::INSERT_VECTOR_ELT.
9201 static SDValue PerformInsertEltCombine(SDNode *N,
9202 TargetLowering::DAGCombinerInfo &DCI) {
9203 // Bitcast an i64 load inserted into a vector to f64.
9204 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9205 EVT VT = N->getValueType(0);
9206 SDNode *Elt = N->getOperand(1).getNode();
9207 if (VT.getVectorElementType() != MVT::i64 ||
9208 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9211 SelectionDAG &DAG = DCI.DAG;
9213 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9214 VT.getVectorNumElements());
9215 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9216 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9217 // Make the DAGCombiner fold the bitcasts.
9218 DCI.AddToWorklist(Vec.getNode());
9219 DCI.AddToWorklist(V.getNode());
9220 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9221 Vec, V, N->getOperand(2));
9222 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9225 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9226 /// ISD::VECTOR_SHUFFLE.
9227 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9228 // The LLVM shufflevector instruction does not require the shuffle mask
9229 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9230 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9231 // operands do not match the mask length, they are extended by concatenating
9232 // them with undef vectors. That is probably the right thing for other
9233 // targets, but for NEON it is better to concatenate two double-register
9234 // size vector operands into a single quad-register size vector. Do that
9235 // transformation here:
9236 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9237 // shuffle(concat(v1, v2), undef)
9238 SDValue Op0 = N->getOperand(0);
9239 SDValue Op1 = N->getOperand(1);
9240 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9241 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9242 Op0.getNumOperands() != 2 ||
9243 Op1.getNumOperands() != 2)
9245 SDValue Concat0Op1 = Op0.getOperand(1);
9246 SDValue Concat1Op1 = Op1.getOperand(1);
9247 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9248 Concat1Op1.getOpcode() != ISD::UNDEF)
9250 // Skip the transformation if any of the types are illegal.
9251 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9252 EVT VT = N->getValueType(0);
9253 if (!TLI.isTypeLegal(VT) ||
9254 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9255 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9258 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9259 Op0.getOperand(0), Op1.getOperand(0));
9260 // Translate the shuffle mask.
9261 SmallVector<int, 16> NewMask;
9262 unsigned NumElts = VT.getVectorNumElements();
9263 unsigned HalfElts = NumElts/2;
9264 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9265 for (unsigned n = 0; n < NumElts; ++n) {
9266 int MaskElt = SVN->getMaskElt(n);
9268 if (MaskElt < (int)HalfElts)
9270 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9271 NewElt = HalfElts + MaskElt - NumElts;
9272 NewMask.push_back(NewElt);
9274 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9275 DAG.getUNDEF(VT), NewMask.data());
9278 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9279 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9280 /// base address updates.
9281 /// For generic load/stores, the memory type is assumed to be a vector.
9282 /// The caller is assumed to have checked legality.
9283 static SDValue CombineBaseUpdate(SDNode *N,
9284 TargetLowering::DAGCombinerInfo &DCI) {
9285 SelectionDAG &DAG = DCI.DAG;
9286 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9287 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9288 const bool isStore = N->getOpcode() == ISD::STORE;
9289 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9290 SDValue Addr = N->getOperand(AddrOpIdx);
9291 MemSDNode *MemN = cast<MemSDNode>(N);
9294 // Search for a use of the address operand that is an increment.
9295 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9296 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9298 if (User->getOpcode() != ISD::ADD ||
9299 UI.getUse().getResNo() != Addr.getResNo())
9302 // Check that the add is independent of the load/store. Otherwise, folding
9303 // it would create a cycle.
9304 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9307 // Find the new opcode for the updating load/store.
9308 bool isLoadOp = true;
9309 bool isLaneOp = false;
9310 unsigned NewOpc = 0;
9311 unsigned NumVecs = 0;
9313 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9315 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9316 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9318 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9320 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9322 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9324 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9325 NumVecs = 2; isLaneOp = true; break;
9326 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9327 NumVecs = 3; isLaneOp = true; break;
9328 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9329 NumVecs = 4; isLaneOp = true; break;
9330 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9331 NumVecs = 1; isLoadOp = false; break;
9332 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9333 NumVecs = 2; isLoadOp = false; break;
9334 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9335 NumVecs = 3; isLoadOp = false; break;
9336 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9337 NumVecs = 4; isLoadOp = false; break;
9338 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9339 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9340 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9341 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9342 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9343 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9347 switch (N->getOpcode()) {
9348 default: llvm_unreachable("unexpected opcode for Neon base update");
9349 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9350 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9351 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9352 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9353 NumVecs = 1; isLaneOp = false; break;
9354 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9355 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9359 // Find the size of memory referenced by the load/store.
9362 VecTy = N->getValueType(0);
9363 } else if (isIntrinsic) {
9364 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9366 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9367 VecTy = N->getOperand(1).getValueType();
9370 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9372 NumBytes /= VecTy.getVectorNumElements();
9374 // If the increment is a constant, it must match the memory ref size.
9375 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9376 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9377 uint64_t IncVal = CInc->getZExtValue();
9378 if (IncVal != NumBytes)
9380 } else if (NumBytes >= 3 * 16) {
9381 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9382 // separate instructions that make it harder to use a non-constant update.
9386 // OK, we found an ADD we can fold into the base update.
9387 // Now, create a _UPD node, taking care of not breaking alignment.
9389 EVT AlignedVecTy = VecTy;
9390 unsigned Alignment = MemN->getAlignment();
9392 // If this is a less-than-standard-aligned load/store, change the type to
9393 // match the standard alignment.
9394 // The alignment is overlooked when selecting _UPD variants; and it's
9395 // easier to introduce bitcasts here than fix that.
9396 // There are 3 ways to get to this base-update combine:
9397 // - intrinsics: they are assumed to be properly aligned (to the standard
9398 // alignment of the memory type), so we don't need to do anything.
9399 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9400 // intrinsics, so, likewise, there's nothing to do.
9401 // - generic load/store instructions: the alignment is specified as an
9402 // explicit operand, rather than implicitly as the standard alignment
9403 // of the memory type (like the intrisics). We need to change the
9404 // memory type to match the explicit alignment. That way, we don't
9405 // generate non-standard-aligned ARMISD::VLDx nodes.
9406 if (isa<LSBaseSDNode>(N)) {
9409 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9410 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9411 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9412 assert(!isLaneOp && "Unexpected generic load/store lane.");
9413 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9414 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9416 // Don't set an explicit alignment on regular load/stores that we want
9417 // to transform to VLD/VST 1_UPD nodes.
9418 // This matches the behavior of regular load/stores, which only get an
9419 // explicit alignment if the MMO alignment is larger than the standard
9420 // alignment of the memory type.
9421 // Intrinsics, however, always get an explicit alignment, set to the
9422 // alignment of the MMO.
9426 // Create the new updating load/store node.
9427 // First, create an SDVTList for the new updating node's results.
9429 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9431 for (n = 0; n < NumResultVecs; ++n)
9432 Tys[n] = AlignedVecTy;
9433 Tys[n++] = MVT::i32;
9434 Tys[n] = MVT::Other;
9435 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9437 // Then, gather the new node's operands.
9438 SmallVector<SDValue, 8> Ops;
9439 Ops.push_back(N->getOperand(0)); // incoming chain
9440 Ops.push_back(N->getOperand(AddrOpIdx));
9443 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9444 // Try to match the intrinsic's signature
9445 Ops.push_back(StN->getValue());
9447 // Loads (and of course intrinsics) match the intrinsics' signature,
9448 // so just add all but the alignment operand.
9449 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9450 Ops.push_back(N->getOperand(i));
9453 // For all node types, the alignment operand is always the last one.
9454 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9456 // If this is a non-standard-aligned STORE, the penultimate operand is the
9457 // stored value. Bitcast it to the aligned type.
9458 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9459 SDValue &StVal = Ops[Ops.size()-2];
9460 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9463 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9465 MemN->getMemOperand());
9468 SmallVector<SDValue, 5> NewResults;
9469 for (unsigned i = 0; i < NumResultVecs; ++i)
9470 NewResults.push_back(SDValue(UpdN.getNode(), i));
9472 // If this is an non-standard-aligned LOAD, the first result is the loaded
9473 // value. Bitcast it to the expected result type.
9474 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9475 SDValue &LdVal = NewResults[0];
9476 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9479 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9480 DCI.CombineTo(N, NewResults);
9481 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9488 static SDValue PerformVLDCombine(SDNode *N,
9489 TargetLowering::DAGCombinerInfo &DCI) {
9490 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9493 return CombineBaseUpdate(N, DCI);
9496 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9497 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9498 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9500 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9501 SelectionDAG &DAG = DCI.DAG;
9502 EVT VT = N->getValueType(0);
9503 // vldN-dup instructions only support 64-bit vectors for N > 1.
9504 if (!VT.is64BitVector())
9507 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9508 SDNode *VLD = N->getOperand(0).getNode();
9509 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9511 unsigned NumVecs = 0;
9512 unsigned NewOpc = 0;
9513 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9514 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9516 NewOpc = ARMISD::VLD2DUP;
9517 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9519 NewOpc = ARMISD::VLD3DUP;
9520 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9522 NewOpc = ARMISD::VLD4DUP;
9527 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9528 // numbers match the load.
9529 unsigned VLDLaneNo =
9530 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9531 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9533 // Ignore uses of the chain result.
9534 if (UI.getUse().getResNo() == NumVecs)
9537 if (User->getOpcode() != ARMISD::VDUPLANE ||
9538 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9542 // Create the vldN-dup node.
9545 for (n = 0; n < NumVecs; ++n)
9547 Tys[n] = MVT::Other;
9548 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9549 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9550 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9551 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9552 Ops, VLDMemInt->getMemoryVT(),
9553 VLDMemInt->getMemOperand());
9556 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9558 unsigned ResNo = UI.getUse().getResNo();
9559 // Ignore uses of the chain result.
9560 if (ResNo == NumVecs)
9563 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9566 // Now the vldN-lane intrinsic is dead except for its chain result.
9567 // Update uses of the chain.
9568 std::vector<SDValue> VLDDupResults;
9569 for (unsigned n = 0; n < NumVecs; ++n)
9570 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9571 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9572 DCI.CombineTo(VLD, VLDDupResults);
9577 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9578 /// ARMISD::VDUPLANE.
9579 static SDValue PerformVDUPLANECombine(SDNode *N,
9580 TargetLowering::DAGCombinerInfo &DCI) {
9581 SDValue Op = N->getOperand(0);
9583 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9584 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9585 if (CombineVLDDUP(N, DCI))
9586 return SDValue(N, 0);
9588 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9589 // redundant. Ignore bit_converts for now; element sizes are checked below.
9590 while (Op.getOpcode() == ISD::BITCAST)
9591 Op = Op.getOperand(0);
9592 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9595 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9596 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9597 // The canonical VMOV for a zero vector uses a 32-bit element size.
9598 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9600 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9602 EVT VT = N->getValueType(0);
9603 if (EltSize > VT.getVectorElementType().getSizeInBits())
9606 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9609 static SDValue PerformLOADCombine(SDNode *N,
9610 TargetLowering::DAGCombinerInfo &DCI) {
9611 EVT VT = N->getValueType(0);
9613 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9614 if (ISD::isNormalLoad(N) && VT.isVector() &&
9615 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9616 return CombineBaseUpdate(N, DCI);
9621 /// PerformSTORECombine - Target-specific dag combine xforms for
9623 static SDValue PerformSTORECombine(SDNode *N,
9624 TargetLowering::DAGCombinerInfo &DCI) {
9625 StoreSDNode *St = cast<StoreSDNode>(N);
9626 if (St->isVolatile())
9629 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9630 // pack all of the elements in one place. Next, store to memory in fewer
9632 SDValue StVal = St->getValue();
9633 EVT VT = StVal.getValueType();
9634 if (St->isTruncatingStore() && VT.isVector()) {
9635 SelectionDAG &DAG = DCI.DAG;
9636 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9637 EVT StVT = St->getMemoryVT();
9638 unsigned NumElems = VT.getVectorNumElements();
9639 assert(StVT != VT && "Cannot truncate to the same type");
9640 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9641 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9643 // From, To sizes and ElemCount must be pow of two
9644 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9646 // We are going to use the original vector elt for storing.
9647 // Accumulated smaller vector elements must be a multiple of the store size.
9648 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9650 unsigned SizeRatio = FromEltSz / ToEltSz;
9651 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9653 // Create a type on which we perform the shuffle.
9654 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9655 NumElems*SizeRatio);
9656 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9659 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9660 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9661 for (unsigned i = 0; i < NumElems; ++i)
9662 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9663 ? (i + 1) * SizeRatio - 1
9666 // Can't shuffle using an illegal type.
9667 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9669 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9670 DAG.getUNDEF(WideVec.getValueType()),
9672 // At this point all of the data is stored at the bottom of the
9673 // register. We now need to save it to mem.
9675 // Find the largest store unit
9676 MVT StoreType = MVT::i8;
9677 for (MVT Tp : MVT::integer_valuetypes()) {
9678 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9681 // Didn't find a legal store type.
9682 if (!TLI.isTypeLegal(StoreType))
9685 // Bitcast the original vector into a vector of store-size units
9686 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9687 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9688 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9689 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9690 SmallVector<SDValue, 8> Chains;
9691 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9692 TLI.getPointerTy(DAG.getDataLayout()));
9693 SDValue BasePtr = St->getBasePtr();
9695 // Perform one or more big stores into memory.
9696 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9697 for (unsigned I = 0; I < E; I++) {
9698 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9699 StoreType, ShuffWide,
9700 DAG.getIntPtrConstant(I, DL));
9701 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9702 St->getPointerInfo(), St->isVolatile(),
9703 St->isNonTemporal(), St->getAlignment());
9704 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9706 Chains.push_back(Ch);
9708 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9711 if (!ISD::isNormalStore(St))
9714 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9715 // ARM stores of arguments in the same cache line.
9716 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9717 StVal.getNode()->hasOneUse()) {
9718 SelectionDAG &DAG = DCI.DAG;
9719 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9721 SDValue BasePtr = St->getBasePtr();
9722 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9723 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9724 BasePtr, St->getPointerInfo(), St->isVolatile(),
9725 St->isNonTemporal(), St->getAlignment());
9727 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9728 DAG.getConstant(4, DL, MVT::i32));
9729 return DAG.getStore(NewST1.getValue(0), DL,
9730 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9731 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9732 St->isNonTemporal(),
9733 std::min(4U, St->getAlignment() / 2));
9736 if (StVal.getValueType() == MVT::i64 &&
9737 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9739 // Bitcast an i64 store extracted from a vector to f64.
9740 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9741 SelectionDAG &DAG = DCI.DAG;
9743 SDValue IntVec = StVal.getOperand(0);
9744 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9745 IntVec.getValueType().getVectorNumElements());
9746 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9747 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9748 Vec, StVal.getOperand(1));
9750 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9751 // Make the DAGCombiner fold the bitcasts.
9752 DCI.AddToWorklist(Vec.getNode());
9753 DCI.AddToWorklist(ExtElt.getNode());
9754 DCI.AddToWorklist(V.getNode());
9755 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9756 St->getPointerInfo(), St->isVolatile(),
9757 St->isNonTemporal(), St->getAlignment(),
9761 // If this is a legal vector store, try to combine it into a VST1_UPD.
9762 if (ISD::isNormalStore(N) && VT.isVector() &&
9763 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9764 return CombineBaseUpdate(N, DCI);
9769 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9770 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9771 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9775 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9777 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9782 APFloat APF = C->getValueAPF();
9783 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9784 != APFloat::opOK || !isExact)
9787 c0 = (I == 0) ? cN : c0;
9788 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9795 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9796 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9797 /// when the VMUL has a constant operand that is a power of 2.
9799 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9800 /// vmul.f32 d16, d17, d16
9801 /// vcvt.s32.f32 d16, d16
9803 /// vcvt.s32.f32 d16, d16, #3
9804 static SDValue PerformVCVTCombine(SDNode *N,
9805 TargetLowering::DAGCombinerInfo &DCI,
9806 const ARMSubtarget *Subtarget) {
9807 SelectionDAG &DAG = DCI.DAG;
9808 SDValue Op = N->getOperand(0);
9810 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9811 Op.getOpcode() != ISD::FMUL)
9815 SDValue N0 = Op->getOperand(0);
9816 SDValue ConstVec = Op->getOperand(1);
9817 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9819 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9820 !isConstVecPow2(ConstVec, isSigned, C))
9823 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9824 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9825 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9826 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9828 // These instructions only exist converting from f32 to i32. We can handle
9829 // smaller integers by generating an extra truncate, but larger ones would
9830 // be lossy. We also can't handle more then 4 lanes, since these intructions
9831 // only support v2i32/v4i32 types.
9836 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9837 Intrinsic::arm_neon_vcvtfp2fxu;
9838 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9839 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9840 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9842 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9844 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9845 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9850 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9851 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9852 /// when the VDIV has a constant operand that is a power of 2.
9854 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9855 /// vcvt.f32.s32 d16, d16
9856 /// vdiv.f32 d16, d17, d16
9858 /// vcvt.f32.s32 d16, d16, #3
9859 static SDValue PerformVDIVCombine(SDNode *N,
9860 TargetLowering::DAGCombinerInfo &DCI,
9861 const ARMSubtarget *Subtarget) {
9862 SelectionDAG &DAG = DCI.DAG;
9863 SDValue Op = N->getOperand(0);
9864 unsigned OpOpcode = Op.getNode()->getOpcode();
9866 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9867 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9871 SDValue ConstVec = N->getOperand(1);
9872 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9874 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9875 !isConstVecPow2(ConstVec, isSigned, C))
9878 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9879 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9880 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9881 // These instructions only exist converting from i32 to f32. We can handle
9882 // smaller integers by generating an extra extend, but larger ones would
9888 SDValue ConvInput = Op.getOperand(0);
9889 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9890 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9891 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9892 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9895 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9896 Intrinsic::arm_neon_vcvtfxu2fp;
9897 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9899 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9900 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9903 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9904 /// operand of a vector shift operation, where all the elements of the
9905 /// build_vector must have the same constant integer value.
9906 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9907 // Ignore bit_converts.
9908 while (Op.getOpcode() == ISD::BITCAST)
9909 Op = Op.getOperand(0);
9910 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9911 APInt SplatBits, SplatUndef;
9912 unsigned SplatBitSize;
9914 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9915 HasAnyUndefs, ElementBits) ||
9916 SplatBitSize > ElementBits)
9918 Cnt = SplatBits.getSExtValue();
9922 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9923 /// operand of a vector shift left operation. That value must be in the range:
9924 /// 0 <= Value < ElementBits for a left shift; or
9925 /// 0 <= Value <= ElementBits for a long left shift.
9926 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9927 assert(VT.isVector() && "vector shift count is not a vector type");
9928 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9929 if (! getVShiftImm(Op, ElementBits, Cnt))
9931 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9934 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9935 /// operand of a vector shift right operation. For a shift opcode, the value
9936 /// is positive, but for an intrinsic the value count must be negative. The
9937 /// absolute value must be in the range:
9938 /// 1 <= |Value| <= ElementBits for a right shift; or
9939 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9940 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9942 assert(VT.isVector() && "vector shift count is not a vector type");
9943 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9944 if (! getVShiftImm(Op, ElementBits, Cnt))
9947 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9948 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9955 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9956 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9957 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9960 // Don't do anything for most intrinsics.
9963 case Intrinsic::arm_neon_vabds:
9964 if (!N->getValueType(0).isInteger())
9966 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9967 N->getOperand(1), N->getOperand(2));
9968 case Intrinsic::arm_neon_vabdu:
9969 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9970 N->getOperand(1), N->getOperand(2));
9972 // Vector shifts: check for immediate versions and lower them.
9973 // Note: This is done during DAG combining instead of DAG legalizing because
9974 // the build_vectors for 64-bit vector element shift counts are generally
9975 // not legal, and it is hard to see their values after they get legalized to
9976 // loads from a constant pool.
9977 case Intrinsic::arm_neon_vshifts:
9978 case Intrinsic::arm_neon_vshiftu:
9979 case Intrinsic::arm_neon_vrshifts:
9980 case Intrinsic::arm_neon_vrshiftu:
9981 case Intrinsic::arm_neon_vrshiftn:
9982 case Intrinsic::arm_neon_vqshifts:
9983 case Intrinsic::arm_neon_vqshiftu:
9984 case Intrinsic::arm_neon_vqshiftsu:
9985 case Intrinsic::arm_neon_vqshiftns:
9986 case Intrinsic::arm_neon_vqshiftnu:
9987 case Intrinsic::arm_neon_vqshiftnsu:
9988 case Intrinsic::arm_neon_vqrshiftns:
9989 case Intrinsic::arm_neon_vqrshiftnu:
9990 case Intrinsic::arm_neon_vqrshiftnsu: {
9991 EVT VT = N->getOperand(1).getValueType();
9993 unsigned VShiftOpc = 0;
9996 case Intrinsic::arm_neon_vshifts:
9997 case Intrinsic::arm_neon_vshiftu:
9998 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9999 VShiftOpc = ARMISD::VSHL;
10002 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10003 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10004 ARMISD::VSHRs : ARMISD::VSHRu);
10009 case Intrinsic::arm_neon_vrshifts:
10010 case Intrinsic::arm_neon_vrshiftu:
10011 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10015 case Intrinsic::arm_neon_vqshifts:
10016 case Intrinsic::arm_neon_vqshiftu:
10017 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10021 case Intrinsic::arm_neon_vqshiftsu:
10022 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10024 llvm_unreachable("invalid shift count for vqshlu intrinsic");
10026 case Intrinsic::arm_neon_vrshiftn:
10027 case Intrinsic::arm_neon_vqshiftns:
10028 case Intrinsic::arm_neon_vqshiftnu:
10029 case Intrinsic::arm_neon_vqshiftnsu:
10030 case Intrinsic::arm_neon_vqrshiftns:
10031 case Intrinsic::arm_neon_vqrshiftnu:
10032 case Intrinsic::arm_neon_vqrshiftnsu:
10033 // Narrowing shifts require an immediate right shift.
10034 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10036 llvm_unreachable("invalid shift count for narrowing vector shift "
10040 llvm_unreachable("unhandled vector shift");
10044 case Intrinsic::arm_neon_vshifts:
10045 case Intrinsic::arm_neon_vshiftu:
10046 // Opcode already set above.
10048 case Intrinsic::arm_neon_vrshifts:
10049 VShiftOpc = ARMISD::VRSHRs; break;
10050 case Intrinsic::arm_neon_vrshiftu:
10051 VShiftOpc = ARMISD::VRSHRu; break;
10052 case Intrinsic::arm_neon_vrshiftn:
10053 VShiftOpc = ARMISD::VRSHRN; break;
10054 case Intrinsic::arm_neon_vqshifts:
10055 VShiftOpc = ARMISD::VQSHLs; break;
10056 case Intrinsic::arm_neon_vqshiftu:
10057 VShiftOpc = ARMISD::VQSHLu; break;
10058 case Intrinsic::arm_neon_vqshiftsu:
10059 VShiftOpc = ARMISD::VQSHLsu; break;
10060 case Intrinsic::arm_neon_vqshiftns:
10061 VShiftOpc = ARMISD::VQSHRNs; break;
10062 case Intrinsic::arm_neon_vqshiftnu:
10063 VShiftOpc = ARMISD::VQSHRNu; break;
10064 case Intrinsic::arm_neon_vqshiftnsu:
10065 VShiftOpc = ARMISD::VQSHRNsu; break;
10066 case Intrinsic::arm_neon_vqrshiftns:
10067 VShiftOpc = ARMISD::VQRSHRNs; break;
10068 case Intrinsic::arm_neon_vqrshiftnu:
10069 VShiftOpc = ARMISD::VQRSHRNu; break;
10070 case Intrinsic::arm_neon_vqrshiftnsu:
10071 VShiftOpc = ARMISD::VQRSHRNsu; break;
10075 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10076 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10079 case Intrinsic::arm_neon_vshiftins: {
10080 EVT VT = N->getOperand(1).getValueType();
10082 unsigned VShiftOpc = 0;
10084 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10085 VShiftOpc = ARMISD::VSLI;
10086 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10087 VShiftOpc = ARMISD::VSRI;
10089 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10093 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10094 N->getOperand(1), N->getOperand(2),
10095 DAG.getConstant(Cnt, dl, MVT::i32));
10098 case Intrinsic::arm_neon_vqrshifts:
10099 case Intrinsic::arm_neon_vqrshiftu:
10100 // No immediate versions of these to check for.
10107 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10108 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10109 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10110 /// vector element shift counts are generally not legal, and it is hard to see
10111 /// their values after they get legalized to loads from a constant pool.
10112 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10113 const ARMSubtarget *ST) {
10114 EVT VT = N->getValueType(0);
10115 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10116 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10117 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10118 SDValue N1 = N->getOperand(1);
10119 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10120 SDValue N0 = N->getOperand(0);
10121 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10122 DAG.MaskedValueIsZero(N0.getOperand(0),
10123 APInt::getHighBitsSet(32, 16)))
10124 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10128 // Nothing to be done for scalar shifts.
10129 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10130 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10133 assert(ST->hasNEON() && "unexpected vector shift");
10136 switch (N->getOpcode()) {
10137 default: llvm_unreachable("unexpected shift opcode");
10140 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10142 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10143 DAG.getConstant(Cnt, dl, MVT::i32));
10149 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10150 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10151 ARMISD::VSHRs : ARMISD::VSHRu);
10153 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10154 DAG.getConstant(Cnt, dl, MVT::i32));
10160 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10161 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10162 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10163 const ARMSubtarget *ST) {
10164 SDValue N0 = N->getOperand(0);
10166 // Check for sign- and zero-extensions of vector extract operations of 8-
10167 // and 16-bit vector elements. NEON supports these directly. They are
10168 // handled during DAG combining because type legalization will promote them
10169 // to 32-bit types and it is messy to recognize the operations after that.
10170 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10171 SDValue Vec = N0.getOperand(0);
10172 SDValue Lane = N0.getOperand(1);
10173 EVT VT = N->getValueType(0);
10174 EVT EltVT = N0.getValueType();
10175 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10177 if (VT == MVT::i32 &&
10178 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10179 TLI.isTypeLegal(Vec.getValueType()) &&
10180 isa<ConstantSDNode>(Lane)) {
10183 switch (N->getOpcode()) {
10184 default: llvm_unreachable("unexpected opcode");
10185 case ISD::SIGN_EXTEND:
10186 Opc = ARMISD::VGETLANEs;
10188 case ISD::ZERO_EXTEND:
10189 case ISD::ANY_EXTEND:
10190 Opc = ARMISD::VGETLANEu;
10193 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10200 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10202 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10203 SDValue Cmp = N->getOperand(4);
10204 if (Cmp.getOpcode() != ARMISD::CMPZ)
10205 // Only looking at EQ and NE cases.
10208 EVT VT = N->getValueType(0);
10210 SDValue LHS = Cmp.getOperand(0);
10211 SDValue RHS = Cmp.getOperand(1);
10212 SDValue FalseVal = N->getOperand(0);
10213 SDValue TrueVal = N->getOperand(1);
10214 SDValue ARMcc = N->getOperand(2);
10215 ARMCC::CondCodes CC =
10216 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10234 /// FIXME: Turn this into a target neutral optimization?
10236 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10237 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10238 N->getOperand(3), Cmp);
10239 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10241 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10242 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10243 N->getOperand(3), NewCmp);
10246 if (Res.getNode()) {
10247 APInt KnownZero, KnownOne;
10248 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10249 // Capture demanded bits information that would be otherwise lost.
10250 if (KnownZero == 0xfffffffe)
10251 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10252 DAG.getValueType(MVT::i1));
10253 else if (KnownZero == 0xffffff00)
10254 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10255 DAG.getValueType(MVT::i8));
10256 else if (KnownZero == 0xffff0000)
10257 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10258 DAG.getValueType(MVT::i16));
10264 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10265 DAGCombinerInfo &DCI) const {
10266 switch (N->getOpcode()) {
10268 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10269 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10270 case ISD::SUB: return PerformSUBCombine(N, DCI);
10271 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10272 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10273 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10274 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10275 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10276 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10277 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10278 case ISD::STORE: return PerformSTORECombine(N, DCI);
10279 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10280 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10281 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10282 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10283 case ISD::FP_TO_SINT:
10284 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10285 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10286 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10289 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10290 case ISD::SIGN_EXTEND:
10291 case ISD::ZERO_EXTEND:
10292 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10293 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10294 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10295 case ARMISD::VLD2DUP:
10296 case ARMISD::VLD3DUP:
10297 case ARMISD::VLD4DUP:
10298 return PerformVLDCombine(N, DCI);
10299 case ARMISD::BUILD_VECTOR:
10300 return PerformARMBUILD_VECTORCombine(N, DCI);
10301 case ISD::INTRINSIC_VOID:
10302 case ISD::INTRINSIC_W_CHAIN:
10303 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10304 case Intrinsic::arm_neon_vld1:
10305 case Intrinsic::arm_neon_vld2:
10306 case Intrinsic::arm_neon_vld3:
10307 case Intrinsic::arm_neon_vld4:
10308 case Intrinsic::arm_neon_vld2lane:
10309 case Intrinsic::arm_neon_vld3lane:
10310 case Intrinsic::arm_neon_vld4lane:
10311 case Intrinsic::arm_neon_vst1:
10312 case Intrinsic::arm_neon_vst2:
10313 case Intrinsic::arm_neon_vst3:
10314 case Intrinsic::arm_neon_vst4:
10315 case Intrinsic::arm_neon_vst2lane:
10316 case Intrinsic::arm_neon_vst3lane:
10317 case Intrinsic::arm_neon_vst4lane:
10318 return PerformVLDCombine(N, DCI);
10326 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10328 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10331 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10334 bool *Fast) const {
10335 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10336 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10338 switch (VT.getSimpleVT().SimpleTy) {
10344 // Unaligned access can use (for example) LRDB, LRDH, LDR
10345 if (AllowsUnaligned) {
10347 *Fast = Subtarget->hasV7Ops();
10354 // For any little-endian targets with neon, we can support unaligned ld/st
10355 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10356 // A big-endian target may also explicitly support unaligned accesses
10357 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10367 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10368 unsigned AlignCheck) {
10369 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10370 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10373 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10374 unsigned DstAlign, unsigned SrcAlign,
10375 bool IsMemset, bool ZeroMemset,
10377 MachineFunction &MF) const {
10378 const Function *F = MF.getFunction();
10380 // See if we can use NEON instructions for this...
10381 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10382 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10385 (memOpAlign(SrcAlign, DstAlign, 16) ||
10386 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10388 } else if (Size >= 8 &&
10389 (memOpAlign(SrcAlign, DstAlign, 8) ||
10390 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10396 // Lowering to i32/i16 if the size permits.
10399 else if (Size >= 2)
10402 // Let the target-independent logic figure it out.
10406 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10407 if (Val.getOpcode() != ISD::LOAD)
10410 EVT VT1 = Val.getValueType();
10411 if (!VT1.isSimple() || !VT1.isInteger() ||
10412 !VT2.isSimple() || !VT2.isInteger())
10415 switch (VT1.getSimpleVT().SimpleTy) {
10420 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10427 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10428 EVT VT = ExtVal.getValueType();
10430 if (!isTypeLegal(VT))
10433 // Don't create a loadext if we can fold the extension into a wide/long
10435 // If there's more than one user instruction, the loadext is desirable no
10436 // matter what. There can be two uses by the same instruction.
10437 if (ExtVal->use_empty() ||
10438 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10441 SDNode *U = *ExtVal->use_begin();
10442 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10443 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10449 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10450 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10453 if (!isTypeLegal(EVT::getEVT(Ty1)))
10456 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10458 // Assuming the caller doesn't have a zeroext or signext return parameter,
10459 // truncation all the way down to i1 is valid.
10464 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10468 unsigned Scale = 1;
10469 switch (VT.getSimpleVT().SimpleTy) {
10470 default: return false;
10485 if ((V & (Scale - 1)) != 0)
10488 return V == (V & ((1LL << 5) - 1));
10491 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10492 const ARMSubtarget *Subtarget) {
10493 bool isNeg = false;
10499 switch (VT.getSimpleVT().SimpleTy) {
10500 default: return false;
10505 // + imm12 or - imm8
10507 return V == (V & ((1LL << 8) - 1));
10508 return V == (V & ((1LL << 12) - 1));
10511 // Same as ARM mode. FIXME: NEON?
10512 if (!Subtarget->hasVFP2())
10517 return V == (V & ((1LL << 8) - 1));
10521 /// isLegalAddressImmediate - Return true if the integer value can be used
10522 /// as the offset of the target addressing mode for load / store of the
10524 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10525 const ARMSubtarget *Subtarget) {
10529 if (!VT.isSimple())
10532 if (Subtarget->isThumb1Only())
10533 return isLegalT1AddressImmediate(V, VT);
10534 else if (Subtarget->isThumb2())
10535 return isLegalT2AddressImmediate(V, VT, Subtarget);
10540 switch (VT.getSimpleVT().SimpleTy) {
10541 default: return false;
10546 return V == (V & ((1LL << 12) - 1));
10549 return V == (V & ((1LL << 8) - 1));
10552 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10557 return V == (V & ((1LL << 8) - 1));
10561 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10563 int Scale = AM.Scale;
10567 switch (VT.getSimpleVT().SimpleTy) {
10568 default: return false;
10576 Scale = Scale & ~1;
10577 return Scale == 2 || Scale == 4 || Scale == 8;
10580 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10584 // Note, we allow "void" uses (basically, uses that aren't loads or
10585 // stores), because arm allows folding a scale into many arithmetic
10586 // operations. This should be made more precise and revisited later.
10588 // Allow r << imm, but the imm has to be a multiple of two.
10589 if (Scale & 1) return false;
10590 return isPowerOf2_32(Scale);
10594 /// isLegalAddressingMode - Return true if the addressing mode represented
10595 /// by AM is legal for this target, for a load/store of the specified type.
10596 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10597 const AddrMode &AM, Type *Ty,
10598 unsigned AS) const {
10599 EVT VT = getValueType(DL, Ty, true);
10600 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10603 // Can never fold addr of global into load/store.
10607 switch (AM.Scale) {
10608 case 0: // no scale reg, must be "r+i" or "r", or "i".
10611 if (Subtarget->isThumb1Only())
10615 // ARM doesn't support any R+R*scale+imm addr modes.
10619 if (!VT.isSimple())
10622 if (Subtarget->isThumb2())
10623 return isLegalT2ScaledAddressingMode(AM, VT);
10625 int Scale = AM.Scale;
10626 switch (VT.getSimpleVT().SimpleTy) {
10627 default: return false;
10631 if (Scale < 0) Scale = -Scale;
10635 return isPowerOf2_32(Scale & ~1);
10639 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10644 // Note, we allow "void" uses (basically, uses that aren't loads or
10645 // stores), because arm allows folding a scale into many arithmetic
10646 // operations. This should be made more precise and revisited later.
10648 // Allow r << imm, but the imm has to be a multiple of two.
10649 if (Scale & 1) return false;
10650 return isPowerOf2_32(Scale);
10656 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10657 /// icmp immediate, that is the target has icmp instructions which can compare
10658 /// a register against the immediate without having to materialize the
10659 /// immediate into a register.
10660 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10661 // Thumb2 and ARM modes can use cmn for negative immediates.
10662 if (!Subtarget->isThumb())
10663 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10664 if (Subtarget->isThumb2())
10665 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10666 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10667 return Imm >= 0 && Imm <= 255;
10670 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10671 /// *or sub* immediate, that is the target has add or sub instructions which can
10672 /// add a register with the immediate without having to materialize the
10673 /// immediate into a register.
10674 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10675 // Same encoding for add/sub, just flip the sign.
10676 int64_t AbsImm = std::abs(Imm);
10677 if (!Subtarget->isThumb())
10678 return ARM_AM::getSOImmVal(AbsImm) != -1;
10679 if (Subtarget->isThumb2())
10680 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10681 // Thumb1 only has 8-bit unsigned immediate.
10682 return AbsImm >= 0 && AbsImm <= 255;
10685 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10686 bool isSEXTLoad, SDValue &Base,
10687 SDValue &Offset, bool &isInc,
10688 SelectionDAG &DAG) {
10689 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10692 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10693 // AddressingMode 3
10694 Base = Ptr->getOperand(0);
10695 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10696 int RHSC = (int)RHS->getZExtValue();
10697 if (RHSC < 0 && RHSC > -256) {
10698 assert(Ptr->getOpcode() == ISD::ADD);
10700 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10704 isInc = (Ptr->getOpcode() == ISD::ADD);
10705 Offset = Ptr->getOperand(1);
10707 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10708 // AddressingMode 2
10709 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10710 int RHSC = (int)RHS->getZExtValue();
10711 if (RHSC < 0 && RHSC > -0x1000) {
10712 assert(Ptr->getOpcode() == ISD::ADD);
10714 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10715 Base = Ptr->getOperand(0);
10720 if (Ptr->getOpcode() == ISD::ADD) {
10722 ARM_AM::ShiftOpc ShOpcVal=
10723 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10724 if (ShOpcVal != ARM_AM::no_shift) {
10725 Base = Ptr->getOperand(1);
10726 Offset = Ptr->getOperand(0);
10728 Base = Ptr->getOperand(0);
10729 Offset = Ptr->getOperand(1);
10734 isInc = (Ptr->getOpcode() == ISD::ADD);
10735 Base = Ptr->getOperand(0);
10736 Offset = Ptr->getOperand(1);
10740 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10744 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10745 bool isSEXTLoad, SDValue &Base,
10746 SDValue &Offset, bool &isInc,
10747 SelectionDAG &DAG) {
10748 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10751 Base = Ptr->getOperand(0);
10752 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10753 int RHSC = (int)RHS->getZExtValue();
10754 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10755 assert(Ptr->getOpcode() == ISD::ADD);
10757 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10759 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10760 isInc = Ptr->getOpcode() == ISD::ADD;
10761 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10769 /// getPreIndexedAddressParts - returns true by value, base pointer and
10770 /// offset pointer and addressing mode by reference if the node's address
10771 /// can be legally represented as pre-indexed load / store address.
10773 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10775 ISD::MemIndexedMode &AM,
10776 SelectionDAG &DAG) const {
10777 if (Subtarget->isThumb1Only())
10782 bool isSEXTLoad = false;
10783 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10784 Ptr = LD->getBasePtr();
10785 VT = LD->getMemoryVT();
10786 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10787 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10788 Ptr = ST->getBasePtr();
10789 VT = ST->getMemoryVT();
10794 bool isLegal = false;
10795 if (Subtarget->isThumb2())
10796 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10797 Offset, isInc, DAG);
10799 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10800 Offset, isInc, DAG);
10804 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10808 /// getPostIndexedAddressParts - returns true by value, base pointer and
10809 /// offset pointer and addressing mode by reference if this node can be
10810 /// combined with a load / store to form a post-indexed load / store.
10811 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10814 ISD::MemIndexedMode &AM,
10815 SelectionDAG &DAG) const {
10816 if (Subtarget->isThumb1Only())
10821 bool isSEXTLoad = false;
10822 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10823 VT = LD->getMemoryVT();
10824 Ptr = LD->getBasePtr();
10825 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10826 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10827 VT = ST->getMemoryVT();
10828 Ptr = ST->getBasePtr();
10833 bool isLegal = false;
10834 if (Subtarget->isThumb2())
10835 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10838 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10844 // Swap base ptr and offset to catch more post-index load / store when
10845 // it's legal. In Thumb2 mode, offset must be an immediate.
10846 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10847 !Subtarget->isThumb2())
10848 std::swap(Base, Offset);
10850 // Post-indexed load / store update the base pointer.
10855 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10859 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10862 const SelectionDAG &DAG,
10863 unsigned Depth) const {
10864 unsigned BitWidth = KnownOne.getBitWidth();
10865 KnownZero = KnownOne = APInt(BitWidth, 0);
10866 switch (Op.getOpcode()) {
10872 // These nodes' second result is a boolean
10873 if (Op.getResNo() == 0)
10875 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10877 case ARMISD::CMOV: {
10878 // Bits are known zero/one if known on the LHS and RHS.
10879 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10880 if (KnownZero == 0 && KnownOne == 0) return;
10882 APInt KnownZeroRHS, KnownOneRHS;
10883 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10884 KnownZero &= KnownZeroRHS;
10885 KnownOne &= KnownOneRHS;
10888 case ISD::INTRINSIC_W_CHAIN: {
10889 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10890 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10893 case Intrinsic::arm_ldaex:
10894 case Intrinsic::arm_ldrex: {
10895 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10896 unsigned MemBits = VT.getScalarType().getSizeInBits();
10897 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10905 //===----------------------------------------------------------------------===//
10906 // ARM Inline Assembly Support
10907 //===----------------------------------------------------------------------===//
10909 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10910 // Looking for "rev" which is V6+.
10911 if (!Subtarget->hasV6Ops())
10914 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10915 std::string AsmStr = IA->getAsmString();
10916 SmallVector<StringRef, 4> AsmPieces;
10917 SplitString(AsmStr, AsmPieces, ";\n");
10919 switch (AsmPieces.size()) {
10920 default: return false;
10922 AsmStr = AsmPieces[0];
10924 SplitString(AsmStr, AsmPieces, " \t,");
10927 if (AsmPieces.size() == 3 &&
10928 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10929 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10930 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10931 if (Ty && Ty->getBitWidth() == 32)
10932 return IntrinsicLowering::LowerToByteSwap(CI);
10940 /// getConstraintType - Given a constraint letter, return the type of
10941 /// constraint it is for this target.
10942 ARMTargetLowering::ConstraintType
10943 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10944 if (Constraint.size() == 1) {
10945 switch (Constraint[0]) {
10947 case 'l': return C_RegisterClass;
10948 case 'w': return C_RegisterClass;
10949 case 'h': return C_RegisterClass;
10950 case 'x': return C_RegisterClass;
10951 case 't': return C_RegisterClass;
10952 case 'j': return C_Other; // Constant for movw.
10953 // An address with a single base register. Due to the way we
10954 // currently handle addresses it is the same as an 'r' memory constraint.
10955 case 'Q': return C_Memory;
10957 } else if (Constraint.size() == 2) {
10958 switch (Constraint[0]) {
10960 // All 'U+' constraints are addresses.
10961 case 'U': return C_Memory;
10964 return TargetLowering::getConstraintType(Constraint);
10967 /// Examine constraint type and operand type and determine a weight value.
10968 /// This object must already have been set up with the operand type
10969 /// and the current alternative constraint selected.
10970 TargetLowering::ConstraintWeight
10971 ARMTargetLowering::getSingleConstraintMatchWeight(
10972 AsmOperandInfo &info, const char *constraint) const {
10973 ConstraintWeight weight = CW_Invalid;
10974 Value *CallOperandVal = info.CallOperandVal;
10975 // If we don't have a value, we can't do a match,
10976 // but allow it at the lowest weight.
10977 if (!CallOperandVal)
10979 Type *type = CallOperandVal->getType();
10980 // Look at the constraint type.
10981 switch (*constraint) {
10983 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10986 if (type->isIntegerTy()) {
10987 if (Subtarget->isThumb())
10988 weight = CW_SpecificReg;
10990 weight = CW_Register;
10994 if (type->isFloatingPointTy())
10995 weight = CW_Register;
11001 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11002 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11003 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11004 if (Constraint.size() == 1) {
11005 // GCC ARM Constraint Letters
11006 switch (Constraint[0]) {
11007 case 'l': // Low regs or general regs.
11008 if (Subtarget->isThumb())
11009 return RCPair(0U, &ARM::tGPRRegClass);
11010 return RCPair(0U, &ARM::GPRRegClass);
11011 case 'h': // High regs or no regs.
11012 if (Subtarget->isThumb())
11013 return RCPair(0U, &ARM::hGPRRegClass);
11016 if (Subtarget->isThumb1Only())
11017 return RCPair(0U, &ARM::tGPRRegClass);
11018 return RCPair(0U, &ARM::GPRRegClass);
11020 if (VT == MVT::Other)
11022 if (VT == MVT::f32)
11023 return RCPair(0U, &ARM::SPRRegClass);
11024 if (VT.getSizeInBits() == 64)
11025 return RCPair(0U, &ARM::DPRRegClass);
11026 if (VT.getSizeInBits() == 128)
11027 return RCPair(0U, &ARM::QPRRegClass);
11030 if (VT == MVT::Other)
11032 if (VT == MVT::f32)
11033 return RCPair(0U, &ARM::SPR_8RegClass);
11034 if (VT.getSizeInBits() == 64)
11035 return RCPair(0U, &ARM::DPR_8RegClass);
11036 if (VT.getSizeInBits() == 128)
11037 return RCPair(0U, &ARM::QPR_8RegClass);
11040 if (VT == MVT::f32)
11041 return RCPair(0U, &ARM::SPRRegClass);
11045 if (StringRef("{cc}").equals_lower(Constraint))
11046 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11048 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11051 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11052 /// vector. If it is invalid, don't add anything to Ops.
11053 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11054 std::string &Constraint,
11055 std::vector<SDValue>&Ops,
11056 SelectionDAG &DAG) const {
11059 // Currently only support length 1 constraints.
11060 if (Constraint.length() != 1) return;
11062 char ConstraintLetter = Constraint[0];
11063 switch (ConstraintLetter) {
11066 case 'I': case 'J': case 'K': case 'L':
11067 case 'M': case 'N': case 'O':
11068 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11072 int64_t CVal64 = C->getSExtValue();
11073 int CVal = (int) CVal64;
11074 // None of these constraints allow values larger than 32 bits. Check
11075 // that the value fits in an int.
11076 if (CVal != CVal64)
11079 switch (ConstraintLetter) {
11081 // Constant suitable for movw, must be between 0 and
11083 if (Subtarget->hasV6T2Ops())
11084 if (CVal >= 0 && CVal <= 65535)
11088 if (Subtarget->isThumb1Only()) {
11089 // This must be a constant between 0 and 255, for ADD
11091 if (CVal >= 0 && CVal <= 255)
11093 } else if (Subtarget->isThumb2()) {
11094 // A constant that can be used as an immediate value in a
11095 // data-processing instruction.
11096 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11099 // A constant that can be used as an immediate value in a
11100 // data-processing instruction.
11101 if (ARM_AM::getSOImmVal(CVal) != -1)
11107 if (Subtarget->isThumb()) { // FIXME thumb2
11108 // This must be a constant between -255 and -1, for negated ADD
11109 // immediates. This can be used in GCC with an "n" modifier that
11110 // prints the negated value, for use with SUB instructions. It is
11111 // not useful otherwise but is implemented for compatibility.
11112 if (CVal >= -255 && CVal <= -1)
11115 // This must be a constant between -4095 and 4095. It is not clear
11116 // what this constraint is intended for. Implemented for
11117 // compatibility with GCC.
11118 if (CVal >= -4095 && CVal <= 4095)
11124 if (Subtarget->isThumb1Only()) {
11125 // A 32-bit value where only one byte has a nonzero value. Exclude
11126 // zero to match GCC. This constraint is used by GCC internally for
11127 // constants that can be loaded with a move/shift combination.
11128 // It is not useful otherwise but is implemented for compatibility.
11129 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11131 } else if (Subtarget->isThumb2()) {
11132 // A constant whose bitwise inverse can be used as an immediate
11133 // value in a data-processing instruction. This can be used in GCC
11134 // with a "B" modifier that prints the inverted value, for use with
11135 // BIC and MVN instructions. It is not useful otherwise but is
11136 // implemented for compatibility.
11137 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11140 // A constant whose bitwise inverse can be used as an immediate
11141 // value in a data-processing instruction. This can be used in GCC
11142 // with a "B" modifier that prints the inverted value, for use with
11143 // BIC and MVN instructions. It is not useful otherwise but is
11144 // implemented for compatibility.
11145 if (ARM_AM::getSOImmVal(~CVal) != -1)
11151 if (Subtarget->isThumb1Only()) {
11152 // This must be a constant between -7 and 7,
11153 // for 3-operand ADD/SUB immediate instructions.
11154 if (CVal >= -7 && CVal < 7)
11156 } else if (Subtarget->isThumb2()) {
11157 // A constant whose negation can be used as an immediate value in a
11158 // data-processing instruction. This can be used in GCC with an "n"
11159 // modifier that prints the negated value, for use with SUB
11160 // instructions. It is not useful otherwise but is implemented for
11162 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11165 // A constant whose negation can be used as an immediate value in a
11166 // data-processing instruction. This can be used in GCC with an "n"
11167 // modifier that prints the negated value, for use with SUB
11168 // instructions. It is not useful otherwise but is implemented for
11170 if (ARM_AM::getSOImmVal(-CVal) != -1)
11176 if (Subtarget->isThumb()) { // FIXME thumb2
11177 // This must be a multiple of 4 between 0 and 1020, for
11178 // ADD sp + immediate.
11179 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11182 // A power of two or a constant between 0 and 32. This is used in
11183 // GCC for the shift amount on shifted register operands, but it is
11184 // useful in general for any shift amounts.
11185 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11191 if (Subtarget->isThumb()) { // FIXME thumb2
11192 // This must be a constant between 0 and 31, for shift amounts.
11193 if (CVal >= 0 && CVal <= 31)
11199 if (Subtarget->isThumb()) { // FIXME thumb2
11200 // This must be a multiple of 4 between -508 and 508, for
11201 // ADD/SUB sp = sp + immediate.
11202 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11207 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11211 if (Result.getNode()) {
11212 Ops.push_back(Result);
11215 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11218 static RTLIB::Libcall getDivRemLibcall(
11219 const SDNode *N, MVT::SimpleValueType SVT) {
11220 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11221 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11222 "Unhandled Opcode in getDivRemLibcall");
11223 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11224 N->getOpcode() == ISD::SREM;
11227 default: llvm_unreachable("Unexpected request for libcall!");
11228 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11229 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11230 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11231 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11236 static TargetLowering::ArgListTy getDivRemArgList(
11237 const SDNode *N, LLVMContext *Context) {
11238 assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11239 N->getOpcode() == ISD::SREM || N->getOpcode() == ISD::UREM) &&
11240 "Unhandled Opcode in getDivRemArgList");
11241 bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11242 N->getOpcode() == ISD::SREM;
11243 TargetLowering::ArgListTy Args;
11244 TargetLowering::ArgListEntry Entry;
11245 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11246 EVT ArgVT = N->getOperand(i).getValueType();
11247 Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11248 Entry.Node = N->getOperand(i);
11250 Entry.isSExt = isSigned;
11251 Entry.isZExt = !isSigned;
11252 Args.push_back(Entry);
11257 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11258 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11259 "Register-based DivRem lowering only");
11260 unsigned Opcode = Op->getOpcode();
11261 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11262 "Invalid opcode for Div/Rem lowering");
11263 bool isSigned = (Opcode == ISD::SDIVREM);
11264 EVT VT = Op->getValueType(0);
11265 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11267 RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11268 VT.getSimpleVT().SimpleTy);
11269 SDValue InChain = DAG.getEntryNode();
11271 TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11274 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11275 getPointerTy(DAG.getDataLayout()));
11277 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11280 TargetLowering::CallLoweringInfo CLI(DAG);
11281 CLI.setDebugLoc(dl).setChain(InChain)
11282 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11283 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11285 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11286 return CallInfo.first;
11289 // Lowers REM using divmod helpers
11290 // see RTABI section 4.2/4.3
11291 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11292 // Build return types (div and rem)
11293 std::vector<Type*> RetTyParams;
11294 Type *RetTyElement;
11296 switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11297 default: llvm_unreachable("Unexpected request for libcall!");
11298 case MVT::i8: RetTyElement = Type::getInt8Ty(*DAG.getContext()); break;
11299 case MVT::i16: RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11300 case MVT::i32: RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11301 case MVT::i64: RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11304 RetTyParams.push_back(RetTyElement);
11305 RetTyParams.push_back(RetTyElement);
11306 ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11307 Type *RetTy = StructType::get(*DAG.getContext(), ret);
11309 RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11311 SDValue InChain = DAG.getEntryNode();
11312 TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11313 bool isSigned = N->getOpcode() == ISD::SREM;
11314 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11315 getPointerTy(DAG.getDataLayout()));
11318 CallLoweringInfo CLI(DAG);
11319 CLI.setChain(InChain)
11320 .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11321 .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11322 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11324 // Return second (rem) result operand (first contains div)
11325 SDNode *ResNode = CallResult.first.getNode();
11326 assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11327 return ResNode->getOperand(1);
11331 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11332 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11336 SDValue Chain = Op.getOperand(0);
11337 SDValue Size = Op.getOperand(1);
11339 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11340 DAG.getConstant(2, DL, MVT::i32));
11343 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11344 Flag = Chain.getValue(1);
11346 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11347 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11349 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11350 Chain = NewSP.getValue(1);
11352 SDValue Ops[2] = { NewSP, Chain };
11353 return DAG.getMergeValues(Ops, DL);
11356 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11357 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11358 "Unexpected type for custom-lowering FP_EXTEND");
11361 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11363 SDValue SrcVal = Op.getOperand(0);
11364 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11365 /*isSigned*/ false, SDLoc(Op)).first;
11368 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11369 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11370 Subtarget->isFPOnlySP() &&
11371 "Unexpected type for custom-lowering FP_ROUND");
11374 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11376 SDValue SrcVal = Op.getOperand(0);
11377 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11378 /*isSigned*/ false, SDLoc(Op)).first;
11382 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11383 // The ARM target isn't yet aware of offsets.
11387 bool ARM::isBitFieldInvertedMask(unsigned v) {
11388 if (v == 0xffffffff)
11391 // there can be 1's on either or both "outsides", all the "inside"
11392 // bits must be 0's
11393 return isShiftedMask_32(~v);
11396 /// isFPImmLegal - Returns true if the target can instruction select the
11397 /// specified FP immediate natively. If false, the legalizer will
11398 /// materialize the FP immediate as a load from a constant pool.
11399 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11400 if (!Subtarget->hasVFP3())
11402 if (VT == MVT::f32)
11403 return ARM_AM::getFP32Imm(Imm) != -1;
11404 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11405 return ARM_AM::getFP64Imm(Imm) != -1;
11409 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11410 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11411 /// specified in the intrinsic calls.
11412 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11414 unsigned Intrinsic) const {
11415 switch (Intrinsic) {
11416 case Intrinsic::arm_neon_vld1:
11417 case Intrinsic::arm_neon_vld2:
11418 case Intrinsic::arm_neon_vld3:
11419 case Intrinsic::arm_neon_vld4:
11420 case Intrinsic::arm_neon_vld2lane:
11421 case Intrinsic::arm_neon_vld3lane:
11422 case Intrinsic::arm_neon_vld4lane: {
11423 Info.opc = ISD::INTRINSIC_W_CHAIN;
11424 // Conservatively set memVT to the entire set of vectors loaded.
11425 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11426 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11427 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11428 Info.ptrVal = I.getArgOperand(0);
11430 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11431 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11432 Info.vol = false; // volatile loads with NEON intrinsics not supported
11433 Info.readMem = true;
11434 Info.writeMem = false;
11437 case Intrinsic::arm_neon_vst1:
11438 case Intrinsic::arm_neon_vst2:
11439 case Intrinsic::arm_neon_vst3:
11440 case Intrinsic::arm_neon_vst4:
11441 case Intrinsic::arm_neon_vst2lane:
11442 case Intrinsic::arm_neon_vst3lane:
11443 case Intrinsic::arm_neon_vst4lane: {
11444 Info.opc = ISD::INTRINSIC_VOID;
11445 // Conservatively set memVT to the entire set of vectors stored.
11446 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11447 unsigned NumElts = 0;
11448 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11449 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11450 if (!ArgTy->isVectorTy())
11452 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11454 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11455 Info.ptrVal = I.getArgOperand(0);
11457 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11458 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11459 Info.vol = false; // volatile stores with NEON intrinsics not supported
11460 Info.readMem = false;
11461 Info.writeMem = true;
11464 case Intrinsic::arm_ldaex:
11465 case Intrinsic::arm_ldrex: {
11466 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11467 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11468 Info.opc = ISD::INTRINSIC_W_CHAIN;
11469 Info.memVT = MVT::getVT(PtrTy->getElementType());
11470 Info.ptrVal = I.getArgOperand(0);
11472 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11474 Info.readMem = true;
11475 Info.writeMem = false;
11478 case Intrinsic::arm_stlex:
11479 case Intrinsic::arm_strex: {
11480 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11481 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11482 Info.opc = ISD::INTRINSIC_W_CHAIN;
11483 Info.memVT = MVT::getVT(PtrTy->getElementType());
11484 Info.ptrVal = I.getArgOperand(1);
11486 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11488 Info.readMem = false;
11489 Info.writeMem = true;
11492 case Intrinsic::arm_stlexd:
11493 case Intrinsic::arm_strexd: {
11494 Info.opc = ISD::INTRINSIC_W_CHAIN;
11495 Info.memVT = MVT::i64;
11496 Info.ptrVal = I.getArgOperand(2);
11500 Info.readMem = false;
11501 Info.writeMem = true;
11504 case Intrinsic::arm_ldaexd:
11505 case Intrinsic::arm_ldrexd: {
11506 Info.opc = ISD::INTRINSIC_W_CHAIN;
11507 Info.memVT = MVT::i64;
11508 Info.ptrVal = I.getArgOperand(0);
11512 Info.readMem = true;
11513 Info.writeMem = false;
11523 /// \brief Returns true if it is beneficial to convert a load of a constant
11524 /// to just the constant itself.
11525 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11527 assert(Ty->isIntegerTy());
11529 unsigned Bits = Ty->getPrimitiveSizeInBits();
11530 if (Bits == 0 || Bits > 32)
11535 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11536 ARM_MB::MemBOpt Domain) const {
11537 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11539 // First, if the target has no DMB, see what fallback we can use.
11540 if (!Subtarget->hasDataBarrier()) {
11541 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11542 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11544 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11545 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11546 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11547 Builder.getInt32(0), Builder.getInt32(7),
11548 Builder.getInt32(10), Builder.getInt32(5)};
11549 return Builder.CreateCall(MCR, args);
11551 // Instead of using barriers, atomic accesses on these subtargets use
11553 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11556 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11557 // Only a full system barrier exists in the M-class architectures.
11558 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11559 Constant *CDomain = Builder.getInt32(Domain);
11560 return Builder.CreateCall(DMB, CDomain);
11564 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11565 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11566 AtomicOrdering Ord, bool IsStore,
11567 bool IsLoad) const {
11568 if (!getInsertFencesForAtomic())
11574 llvm_unreachable("Invalid fence: unordered/non-atomic");
11577 return nullptr; // Nothing to do
11578 case SequentiallyConsistent:
11580 return nullptr; // Nothing to do
11583 case AcquireRelease:
11584 if (Subtarget->isSwift())
11585 return makeDMB(Builder, ARM_MB::ISHST);
11586 // FIXME: add a comment with a link to documentation justifying this.
11588 return makeDMB(Builder, ARM_MB::ISH);
11590 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11593 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11594 AtomicOrdering Ord, bool IsStore,
11595 bool IsLoad) const {
11596 if (!getInsertFencesForAtomic())
11602 llvm_unreachable("Invalid fence: unordered/not-atomic");
11605 return nullptr; // Nothing to do
11607 case AcquireRelease:
11608 case SequentiallyConsistent:
11609 return makeDMB(Builder, ARM_MB::ISH);
11611 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11614 // Loads and stores less than 64-bits are already atomic; ones above that
11615 // are doomed anyway, so defer to the default libcall and blame the OS when
11616 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11617 // anything for those.
11618 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11619 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11620 return (Size == 64) && !Subtarget->isMClass();
11623 // Loads and stores less than 64-bits are already atomic; ones above that
11624 // are doomed anyway, so defer to the default libcall and blame the OS when
11625 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11626 // anything for those.
11627 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11628 // guarantee, see DDI0406C ARM architecture reference manual,
11629 // sections A8.8.72-74 LDRD)
11630 TargetLowering::AtomicExpansionKind
11631 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11632 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11633 return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11634 : AtomicExpansionKind::None;
11637 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11638 // and up to 64 bits on the non-M profiles
11639 TargetLowering::AtomicExpansionKind
11640 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11641 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11642 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11643 ? AtomicExpansionKind::LLSC
11644 : AtomicExpansionKind::None;
11647 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11648 AtomicCmpXchgInst *AI) const {
11652 // This has so far only been implemented for MachO.
11653 bool ARMTargetLowering::useLoadStackGuardNode() const {
11654 return Subtarget->isTargetMachO();
11657 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11658 unsigned &Cost) const {
11659 // If we do not have NEON, vector types are not natively supported.
11660 if (!Subtarget->hasNEON())
11663 // Floating point values and vector values map to the same register file.
11664 // Therefore, although we could do a store extract of a vector type, this is
11665 // better to leave at float as we have more freedom in the addressing mode for
11667 if (VectorTy->isFPOrFPVectorTy())
11670 // If the index is unknown at compile time, this is very expensive to lower
11671 // and it is not possible to combine the store with the extract.
11672 if (!isa<ConstantInt>(Idx))
11675 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11676 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11677 // We can do a store + vector extract on any vector that fits perfectly in a D
11679 if (BitWidth == 64 || BitWidth == 128) {
11686 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11687 AtomicOrdering Ord) const {
11688 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11689 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11690 bool IsAcquire = isAtLeastAcquire(Ord);
11692 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11693 // intrinsic must return {i32, i32} and we have to recombine them into a
11694 // single i64 here.
11695 if (ValTy->getPrimitiveSizeInBits() == 64) {
11696 Intrinsic::ID Int =
11697 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11698 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11700 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11701 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11703 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11704 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11705 if (!Subtarget->isLittle())
11706 std::swap (Lo, Hi);
11707 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11708 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11709 return Builder.CreateOr(
11710 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11713 Type *Tys[] = { Addr->getType() };
11714 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11715 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11717 return Builder.CreateTruncOrBitCast(
11718 Builder.CreateCall(Ldrex, Addr),
11719 cast<PointerType>(Addr->getType())->getElementType());
11722 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11723 IRBuilder<> &Builder) const {
11724 if (!Subtarget->hasV7Ops())
11726 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11727 Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
11730 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11732 AtomicOrdering Ord) const {
11733 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11734 bool IsRelease = isAtLeastRelease(Ord);
11736 // Since the intrinsics must have legal type, the i64 intrinsics take two
11737 // parameters: "i32, i32". We must marshal Val into the appropriate form
11738 // before the call.
11739 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11740 Intrinsic::ID Int =
11741 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11742 Function *Strex = Intrinsic::getDeclaration(M, Int);
11743 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11745 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11746 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11747 if (!Subtarget->isLittle())
11748 std::swap (Lo, Hi);
11749 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11750 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11753 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11754 Type *Tys[] = { Addr->getType() };
11755 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11757 return Builder.CreateCall(
11758 Strex, {Builder.CreateZExtOrBitCast(
11759 Val, Strex->getFunctionType()->getParamType(0)),
11763 /// \brief Lower an interleaved load into a vldN intrinsic.
11765 /// E.g. Lower an interleaved load (Factor = 2):
11766 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11767 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
11768 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
11771 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11772 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11773 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11774 bool ARMTargetLowering::lowerInterleavedLoad(
11775 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11776 ArrayRef<unsigned> Indices, unsigned Factor) const {
11777 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11778 "Invalid interleave factor");
11779 assert(!Shuffles.empty() && "Empty shufflevector input");
11780 assert(Shuffles.size() == Indices.size() &&
11781 "Unmatched number of shufflevectors and indices");
11783 VectorType *VecTy = Shuffles[0]->getType();
11784 Type *EltTy = VecTy->getVectorElementType();
11786 const DataLayout &DL = LI->getModule()->getDataLayout();
11787 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11788 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11790 // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11791 // support i64/f64 element).
11792 if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11795 // A pointer vector can not be the return type of the ldN intrinsics. Need to
11796 // load integer vectors first and then convert to pointer vectors.
11797 if (EltTy->isPointerTy())
11799 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11801 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11802 Intrinsic::arm_neon_vld3,
11803 Intrinsic::arm_neon_vld4};
11805 IRBuilder<> Builder(LI);
11806 SmallVector<Value *, 2> Ops;
11808 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11809 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11810 Ops.push_back(Builder.getInt32(LI->getAlignment()));
11812 Type *Tys[] = { VecTy, Int8Ptr };
11813 Function *VldnFunc =
11814 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
11815 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11817 // Replace uses of each shufflevector with the corresponding vector loaded
11819 for (unsigned i = 0; i < Shuffles.size(); i++) {
11820 ShuffleVectorInst *SV = Shuffles[i];
11821 unsigned Index = Indices[i];
11823 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11825 // Convert the integer vector to pointer vector if the element is pointer.
11826 if (EltTy->isPointerTy())
11827 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11829 SV->replaceAllUsesWith(SubVec);
11835 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11837 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11838 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11839 unsigned NumElts) {
11840 SmallVector<Constant *, 16> Mask;
11841 for (unsigned i = 0; i < NumElts; i++)
11842 Mask.push_back(Builder.getInt32(Start + i));
11844 return ConstantVector::get(Mask);
11847 /// \brief Lower an interleaved store into a vstN intrinsic.
11849 /// E.g. Lower an interleaved store (Factor = 3):
11850 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11851 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11852 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11855 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11856 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11857 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11858 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11860 /// Note that the new shufflevectors will be removed and we'll only generate one
11861 /// vst3 instruction in CodeGen.
11862 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11863 ShuffleVectorInst *SVI,
11864 unsigned Factor) const {
11865 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11866 "Invalid interleave factor");
11868 VectorType *VecTy = SVI->getType();
11869 assert(VecTy->getVectorNumElements() % Factor == 0 &&
11870 "Invalid interleaved store");
11872 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11873 Type *EltTy = VecTy->getVectorElementType();
11874 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11876 const DataLayout &DL = SI->getModule()->getDataLayout();
11877 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11878 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11880 // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11881 // doesn't support i64/f64 element).
11882 if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11885 Value *Op0 = SVI->getOperand(0);
11886 Value *Op1 = SVI->getOperand(1);
11887 IRBuilder<> Builder(SI);
11889 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11890 // vectors to integer vectors.
11891 if (EltTy->isPointerTy()) {
11892 Type *IntTy = DL.getIntPtrType(EltTy);
11894 // Convert to the corresponding integer vector.
11896 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11897 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11898 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11900 SubVecTy = VectorType::get(IntTy, NumSubElts);
11903 static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11904 Intrinsic::arm_neon_vst3,
11905 Intrinsic::arm_neon_vst4};
11906 SmallVector<Value *, 6> Ops;
11908 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11909 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11911 Type *Tys[] = { Int8Ptr, SubVecTy };
11912 Function *VstNFunc = Intrinsic::getDeclaration(
11913 SI->getModule(), StoreInts[Factor - 2], Tys);
11915 // Split the shufflevector operands into sub vectors for the new vstN call.
11916 for (unsigned i = 0; i < Factor; i++)
11917 Ops.push_back(Builder.CreateShuffleVector(
11918 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11920 Ops.push_back(Builder.getInt32(SI->getAlignment()));
11921 Builder.CreateCall(VstNFunc, Ops);
11933 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11934 uint64_t &Members) {
11935 if (auto *ST = dyn_cast<StructType>(Ty)) {
11936 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11937 uint64_t SubMembers = 0;
11938 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11940 Members += SubMembers;
11942 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11943 uint64_t SubMembers = 0;
11944 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11946 Members += SubMembers * AT->getNumElements();
11947 } else if (Ty->isFloatTy()) {
11948 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11952 } else if (Ty->isDoubleTy()) {
11953 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11957 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11964 return VT->getBitWidth() == 64;
11966 return VT->getBitWidth() == 128;
11968 switch (VT->getBitWidth()) {
11981 return (Members > 0 && Members <= 4);
11984 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11985 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11986 /// passing according to AAPCS rules.
11987 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11988 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11989 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11990 CallingConv::ARM_AAPCS_VFP)
11993 HABaseType Base = HA_UNKNOWN;
11994 uint64_t Members = 0;
11995 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11996 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11998 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11999 return IsHA || IsIntArray;