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/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
53 #define DEBUG_TYPE "arm-isel"
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61 cl::desc("Generate calls via indirect call instructions"),
65 ARMInterworking("arm-interworking", cl::Hidden,
66 cl::desc("Enable / disable ARM interworking (for debugging only)"),
70 class ARMCCState : public CCState {
72 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
74 LLVMContext &C, ParmContext PC)
75 : CCState(CC, isVarArg, MF, TM, locs, C) {
76 assert(((PC == Call) || (PC == Prologue)) &&
77 "ARMCCState users must specify whether their context is call"
78 "or prologue generation.");
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86 ARM::R0, ARM::R1, ARM::R2, ARM::R3
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90 MVT PromotedBitwiseVT) {
91 if (VT != PromotedLdStVT) {
92 setOperationAction(ISD::LOAD, VT, Promote);
93 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
95 setOperationAction(ISD::STORE, VT, Promote);
96 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
99 MVT ElemTy = VT.getVectorElementType();
100 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101 setOperationAction(ISD::SETCC, VT, Custom);
102 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104 if (ElemTy == MVT::i32) {
105 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
110 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
115 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
116 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
117 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
118 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119 setOperationAction(ISD::SELECT, VT, Expand);
120 setOperationAction(ISD::SELECT_CC, VT, Expand);
121 setOperationAction(ISD::VSELECT, VT, Expand);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123 if (VT.isInteger()) {
124 setOperationAction(ISD::SHL, VT, Custom);
125 setOperationAction(ISD::SRA, VT, Custom);
126 setOperationAction(ISD::SRL, VT, Custom);
129 // Promote all bit-wise operations.
130 if (VT.isInteger() && VT != PromotedBitwiseVT) {
131 setOperationAction(ISD::AND, VT, Promote);
132 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133 setOperationAction(ISD::OR, VT, Promote);
134 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
135 setOperationAction(ISD::XOR, VT, Promote);
136 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
139 // Neon does not support vector divide/remainder operations.
140 setOperationAction(ISD::SDIV, VT, Expand);
141 setOperationAction(ISD::UDIV, VT, Expand);
142 setOperationAction(ISD::FDIV, VT, Expand);
143 setOperationAction(ISD::SREM, VT, Expand);
144 setOperationAction(ISD::UREM, VT, Expand);
145 setOperationAction(ISD::FREM, VT, Expand);
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149 addRegisterClass(VT, &ARM::DPRRegClass);
150 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154 addRegisterClass(VT, &ARM::DPairRegClass);
155 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
158 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
159 if (TT.isOSBinFormatMachO())
160 return new TargetLoweringObjectFileMachO();
161 if (TT.isOSWindows())
162 return new TargetLoweringObjectFileCOFF();
163 return new ARMElfTargetObjectFile();
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
168 Subtarget = &TM.getSubtarget<ARMSubtarget>();
169 RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
170 Itins = TM.getSubtargetImpl()->getInstrItineraryData();
172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174 if (Subtarget->isTargetMachO()) {
175 // Uses VFP for Thumb libfuncs if available.
176 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
177 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
178 // Single-precision floating-point arithmetic.
179 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
180 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
181 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
182 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
184 // Double-precision floating-point arithmetic.
185 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
186 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
187 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
188 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
190 // Single-precision comparisons.
191 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
192 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
193 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
194 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
195 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
196 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
197 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
198 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
200 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
209 // Double-precision comparisons.
210 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
211 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
212 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
213 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
214 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
215 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
216 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
217 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
219 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
228 // Floating-point to integer conversions.
229 // i64 conversions are done via library routines even when generating VFP
230 // instructions, so use the same ones.
231 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
232 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
233 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
234 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
236 // Conversions between floating types.
237 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
238 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
240 // Integer to floating-point conversions.
241 // i64 conversions are done via library routines even when generating VFP
242 // instructions, so use the same ones.
243 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
244 // e.g., __floatunsidf vs. __floatunssidfvfp.
245 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
246 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
247 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
248 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
252 // These libcalls are not available in 32-bit.
253 setLibcallName(RTLIB::SHL_I128, nullptr);
254 setLibcallName(RTLIB::SRL_I128, nullptr);
255 setLibcallName(RTLIB::SRA_I128, nullptr);
257 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
258 !Subtarget->isTargetWindows()) {
259 static const struct {
260 const RTLIB::Libcall Op;
261 const char * const Name;
262 const CallingConv::ID CC;
263 const ISD::CondCode Cond;
265 // Double-precision floating-point arithmetic helper functions
266 // RTABI chapter 4.1.2, Table 2
267 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272 // Double-precision floating-point comparison helper functions
273 // RTABI chapter 4.1.2, Table 3
274 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
276 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
277 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
278 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
279 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
280 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
281 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
283 // Single-precision floating-point arithmetic helper functions
284 // RTABI chapter 4.1.2, Table 4
285 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290 // Single-precision floating-point comparison helper functions
291 // RTABI chapter 4.1.2, Table 5
292 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
294 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
295 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
296 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
297 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
298 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
299 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
301 // Floating-point to integer conversions.
302 // RTABI chapter 4.1.2, Table 6
303 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 // Conversions between floating types.
313 // RTABI chapter 4.1.2, Table 7
314 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 // Integer to floating-point conversions.
319 // RTABI chapter 4.1.2, Table 8
320 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 // Long long helper functions
330 // RTABI chapter 4.2, Table 9
331 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 // Integer division functions
337 // RTABI chapter 4.3.1
338 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348 // RTABI chapter 4.3.4
349 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
354 for (const auto &LC : LibraryCalls) {
355 setLibcallName(LC.Op, LC.Name);
356 setLibcallCallingConv(LC.Op, LC.CC);
357 if (LC.Cond != ISD::SETCC_INVALID)
358 setCmpLibcallCC(LC.Op, LC.Cond);
362 if (Subtarget->isTargetWindows()) {
363 static const struct {
364 const RTLIB::Libcall Op;
365 const char * const Name;
366 const CallingConv::ID CC;
368 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
371 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
372 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
373 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
374 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
375 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
378 for (const auto &LC : LibraryCalls) {
379 setLibcallName(LC.Op, LC.Name);
380 setLibcallCallingConv(LC.Op, LC.CC);
384 // Use divmod compiler-rt calls for iOS 5.0 and later.
385 if (Subtarget->getTargetTriple().isiOS() &&
386 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
387 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
388 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
391 if (Subtarget->isThumb1Only())
392 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
394 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
395 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
396 !Subtarget->isThumb1Only()) {
397 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
398 if (!Subtarget->isFPOnlySP())
399 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
402 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
403 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
404 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
405 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
406 setTruncStoreAction((MVT::SimpleValueType)VT,
407 (MVT::SimpleValueType)InnerVT, Expand);
408 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
409 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
410 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
412 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
413 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
414 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
415 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
417 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
420 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
421 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
423 if (Subtarget->hasNEON()) {
424 addDRTypeForNEON(MVT::v2f32);
425 addDRTypeForNEON(MVT::v8i8);
426 addDRTypeForNEON(MVT::v4i16);
427 addDRTypeForNEON(MVT::v2i32);
428 addDRTypeForNEON(MVT::v1i64);
430 addQRTypeForNEON(MVT::v4f32);
431 addQRTypeForNEON(MVT::v2f64);
432 addQRTypeForNEON(MVT::v16i8);
433 addQRTypeForNEON(MVT::v8i16);
434 addQRTypeForNEON(MVT::v4i32);
435 addQRTypeForNEON(MVT::v2i64);
437 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
438 // neither Neon nor VFP support any arithmetic operations on it.
439 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
440 // supported for v4f32.
441 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
442 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
443 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
444 // FIXME: Code duplication: FDIV and FREM are expanded always, see
445 // ARMTargetLowering::addTypeForNEON method for details.
446 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
447 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
448 // FIXME: Create unittest.
449 // In another words, find a way when "copysign" appears in DAG with vector
451 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
452 // FIXME: Code duplication: SETCC has custom operation action, see
453 // ARMTargetLowering::addTypeForNEON method for details.
454 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
455 // FIXME: Create unittest for FNEG and for FABS.
456 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
457 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
458 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
459 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
460 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
461 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
462 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
463 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
464 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
465 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
466 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
467 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
468 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
469 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
470 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
471 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
472 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
473 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
474 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
476 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
477 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
478 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
479 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
480 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
481 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
482 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
483 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
484 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
485 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
486 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
487 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
488 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
489 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
490 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
492 // Mark v2f32 intrinsics.
493 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
494 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
495 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
496 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
497 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
498 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
499 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
500 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
501 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
502 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
503 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
504 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
505 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
506 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
507 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
509 // Neon does not support some operations on v1i64 and v2i64 types.
510 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
511 // Custom handling for some quad-vector types to detect VMULL.
512 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
513 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
514 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
515 // Custom handling for some vector types to avoid expensive expansions
516 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
517 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
518 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
519 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
520 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
521 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
522 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
523 // a destination type that is wider than the source, and nor does
524 // it have a FP_TO_[SU]INT instruction with a narrower destination than
526 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
527 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
528 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
529 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
531 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
532 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
534 // NEON does not have single instruction CTPOP for vectors with element
535 // types wider than 8-bits. However, custom lowering can leverage the
536 // v8i8/v16i8 vcnt instruction.
537 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
538 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
539 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
540 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
542 // NEON only has FMA instructions as of VFP4.
543 if (!Subtarget->hasVFP4()) {
544 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
545 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
548 setTargetDAGCombine(ISD::INTRINSIC_VOID);
549 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
550 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
551 setTargetDAGCombine(ISD::SHL);
552 setTargetDAGCombine(ISD::SRL);
553 setTargetDAGCombine(ISD::SRA);
554 setTargetDAGCombine(ISD::SIGN_EXTEND);
555 setTargetDAGCombine(ISD::ZERO_EXTEND);
556 setTargetDAGCombine(ISD::ANY_EXTEND);
557 setTargetDAGCombine(ISD::SELECT_CC);
558 setTargetDAGCombine(ISD::BUILD_VECTOR);
559 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
560 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
561 setTargetDAGCombine(ISD::STORE);
562 setTargetDAGCombine(ISD::FP_TO_SINT);
563 setTargetDAGCombine(ISD::FP_TO_UINT);
564 setTargetDAGCombine(ISD::FDIV);
566 // It is legal to extload from v4i8 to v4i16 or v4i32.
567 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
568 MVT::v4i16, MVT::v2i16,
570 for (unsigned i = 0; i < 6; ++i) {
571 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
572 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
573 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
577 // ARM and Thumb2 support UMLAL/SMLAL.
578 if (!Subtarget->isThumb1Only())
579 setTargetDAGCombine(ISD::ADDC);
582 computeRegisterProperties();
584 // ARM does not have floating-point extending loads.
585 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
586 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
588 // ... or truncating stores
589 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
590 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
591 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
593 // ARM does not have i1 sign extending load.
594 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
596 // ARM supports all 4 flavors of integer indexed load / store.
597 if (!Subtarget->isThumb1Only()) {
598 for (unsigned im = (unsigned)ISD::PRE_INC;
599 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
600 setIndexedLoadAction(im, MVT::i1, Legal);
601 setIndexedLoadAction(im, MVT::i8, Legal);
602 setIndexedLoadAction(im, MVT::i16, Legal);
603 setIndexedLoadAction(im, MVT::i32, Legal);
604 setIndexedStoreAction(im, MVT::i1, Legal);
605 setIndexedStoreAction(im, MVT::i8, Legal);
606 setIndexedStoreAction(im, MVT::i16, Legal);
607 setIndexedStoreAction(im, MVT::i32, Legal);
611 setOperationAction(ISD::SADDO, MVT::i32, Custom);
612 setOperationAction(ISD::UADDO, MVT::i32, Custom);
613 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
614 setOperationAction(ISD::USUBO, MVT::i32, Custom);
616 // i64 operation support.
617 setOperationAction(ISD::MUL, MVT::i64, Expand);
618 setOperationAction(ISD::MULHU, MVT::i32, Expand);
619 if (Subtarget->isThumb1Only()) {
620 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
621 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
623 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
624 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
625 setOperationAction(ISD::MULHS, MVT::i32, Expand);
627 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
628 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
629 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
630 setOperationAction(ISD::SRL, MVT::i64, Custom);
631 setOperationAction(ISD::SRA, MVT::i64, Custom);
633 if (!Subtarget->isThumb1Only()) {
634 // FIXME: We should do this for Thumb1 as well.
635 setOperationAction(ISD::ADDC, MVT::i32, Custom);
636 setOperationAction(ISD::ADDE, MVT::i32, Custom);
637 setOperationAction(ISD::SUBC, MVT::i32, Custom);
638 setOperationAction(ISD::SUBE, MVT::i32, Custom);
641 // ARM does not have ROTL.
642 setOperationAction(ISD::ROTL, MVT::i32, Expand);
643 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
644 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
645 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
646 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
648 // These just redirect to CTTZ and CTLZ on ARM.
649 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
650 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
652 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
654 // Only ARMv6 has BSWAP.
655 if (!Subtarget->hasV6Ops())
656 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
658 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
659 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
660 // These are expanded into libcalls if the cpu doesn't have HW divider.
661 setOperationAction(ISD::SDIV, MVT::i32, Expand);
662 setOperationAction(ISD::UDIV, MVT::i32, Expand);
665 // FIXME: Also set divmod for SREM on EABI
666 setOperationAction(ISD::SREM, MVT::i32, Expand);
667 setOperationAction(ISD::UREM, MVT::i32, Expand);
668 // Register based DivRem for AEABI (RTABI 4.2)
669 if (Subtarget->isTargetAEABI()) {
670 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
671 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
672 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
673 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
674 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
675 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
676 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
677 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
679 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
680 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
681 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
682 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
683 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
684 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
685 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
686 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
688 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
689 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
691 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
692 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
695 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
696 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
697 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
698 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
699 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
701 setOperationAction(ISD::TRAP, MVT::Other, Legal);
703 // Use the default implementation.
704 setOperationAction(ISD::VASTART, MVT::Other, Custom);
705 setOperationAction(ISD::VAARG, MVT::Other, Expand);
706 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
707 setOperationAction(ISD::VAEND, MVT::Other, Expand);
708 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
709 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
711 if (!Subtarget->isTargetMachO()) {
712 // Non-MachO platforms may return values in these registers via the
713 // personality function.
714 setExceptionPointerRegister(ARM::R0);
715 setExceptionSelectorRegister(ARM::R1);
718 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
719 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
721 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
723 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
724 // the default expansion.
725 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
726 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
727 // to ldrex/strex loops already.
728 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
730 // On v8, we have particularly efficient implementations of atomic fences
731 // if they can be combined with nearby atomic loads and stores.
732 if (!Subtarget->hasV8Ops()) {
733 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
734 setInsertFencesForAtomic(true);
737 // If there's anything we can use as a barrier, go through custom lowering
739 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
740 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
742 // Set them all for expansion, which will force libcalls.
743 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
744 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
745 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
746 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
747 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
748 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
749 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
750 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
751 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
752 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
753 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
754 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
755 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
756 // Unordered/Monotonic case.
757 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
758 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
761 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
763 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
764 if (!Subtarget->hasV6Ops()) {
765 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
766 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
768 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
770 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
771 !Subtarget->isThumb1Only()) {
772 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
773 // iff target supports vfp2.
774 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
775 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
778 // We want to custom lower some of our intrinsics.
779 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
780 if (Subtarget->isTargetDarwin()) {
781 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
782 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
783 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
786 setOperationAction(ISD::SETCC, MVT::i32, Expand);
787 setOperationAction(ISD::SETCC, MVT::f32, Expand);
788 setOperationAction(ISD::SETCC, MVT::f64, Expand);
789 setOperationAction(ISD::SELECT, MVT::i32, Custom);
790 setOperationAction(ISD::SELECT, MVT::f32, Custom);
791 setOperationAction(ISD::SELECT, MVT::f64, Custom);
792 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
793 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
794 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
796 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
797 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
798 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
799 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
800 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
802 // We don't support sin/cos/fmod/copysign/pow
803 setOperationAction(ISD::FSIN, MVT::f64, Expand);
804 setOperationAction(ISD::FSIN, MVT::f32, Expand);
805 setOperationAction(ISD::FCOS, MVT::f32, Expand);
806 setOperationAction(ISD::FCOS, MVT::f64, Expand);
807 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
808 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
809 setOperationAction(ISD::FREM, MVT::f64, Expand);
810 setOperationAction(ISD::FREM, MVT::f32, Expand);
811 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
812 !Subtarget->isThumb1Only()) {
813 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
814 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
816 setOperationAction(ISD::FPOW, MVT::f64, Expand);
817 setOperationAction(ISD::FPOW, MVT::f32, Expand);
819 if (!Subtarget->hasVFP4()) {
820 setOperationAction(ISD::FMA, MVT::f64, Expand);
821 setOperationAction(ISD::FMA, MVT::f32, Expand);
824 // Various VFP goodness
825 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
826 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
827 if (Subtarget->hasVFP2()) {
828 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
829 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
830 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
831 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
834 // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
835 if (!Subtarget->hasV8Ops()) {
836 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
837 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
840 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
841 if (!Subtarget->hasFP16()) {
842 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
843 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
847 // Combine sin / cos into one node or libcall if possible.
848 if (Subtarget->hasSinCos()) {
849 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
850 setLibcallName(RTLIB::SINCOS_F64, "sincos");
851 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
852 // For iOS, we don't want to the normal expansion of a libcall to
853 // sincos. We want to issue a libcall to __sincos_stret.
854 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
855 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
859 // We have target-specific dag combine patterns for the following nodes:
860 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
861 setTargetDAGCombine(ISD::ADD);
862 setTargetDAGCombine(ISD::SUB);
863 setTargetDAGCombine(ISD::MUL);
864 setTargetDAGCombine(ISD::AND);
865 setTargetDAGCombine(ISD::OR);
866 setTargetDAGCombine(ISD::XOR);
868 if (Subtarget->hasV6Ops())
869 setTargetDAGCombine(ISD::SRL);
871 setStackPointerRegisterToSaveRestore(ARM::SP);
873 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
874 !Subtarget->hasVFP2())
875 setSchedulingPreference(Sched::RegPressure);
877 setSchedulingPreference(Sched::Hybrid);
879 //// temporary - rewrite interface to use type
880 MaxStoresPerMemset = 8;
881 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
882 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
883 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
884 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
885 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
887 // On ARM arguments smaller than 4 bytes are extended, so all arguments
888 // are at least 4 bytes aligned.
889 setMinStackArgumentAlignment(4);
891 // Prefer likely predicted branches to selects on out-of-order cores.
892 PredictableSelectIsExpensive = Subtarget->isLikeA9();
894 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
897 // FIXME: It might make sense to define the representative register class as the
898 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
899 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
900 // SPR's representative would be DPR_VFP2. This should work well if register
901 // pressure tracking were modified such that a register use would increment the
902 // pressure of the register class's representative and all of it's super
903 // classes' representatives transitively. We have not implemented this because
904 // of the difficulty prior to coalescing of modeling operand register classes
905 // due to the common occurrence of cross class copies and subregister insertions
907 std::pair<const TargetRegisterClass*, uint8_t>
908 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
909 const TargetRegisterClass *RRC = nullptr;
911 switch (VT.SimpleTy) {
913 return TargetLowering::findRepresentativeClass(VT);
914 // Use DPR as representative register class for all floating point
915 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
916 // the cost is 1 for both f32 and f64.
917 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
918 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
919 RRC = &ARM::DPRRegClass;
920 // When NEON is used for SP, only half of the register file is available
921 // because operations that define both SP and DP results will be constrained
922 // to the VFP2 class (D0-D15). We currently model this constraint prior to
923 // coalescing by double-counting the SP regs. See the FIXME above.
924 if (Subtarget->useNEONForSinglePrecisionFP())
927 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
928 case MVT::v4f32: case MVT::v2f64:
929 RRC = &ARM::DPRRegClass;
933 RRC = &ARM::DPRRegClass;
937 RRC = &ARM::DPRRegClass;
941 return std::make_pair(RRC, Cost);
944 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
946 default: return nullptr;
947 case ARMISD::Wrapper: return "ARMISD::Wrapper";
948 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
949 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
950 case ARMISD::CALL: return "ARMISD::CALL";
951 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
952 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
953 case ARMISD::tCALL: return "ARMISD::tCALL";
954 case ARMISD::BRCOND: return "ARMISD::BRCOND";
955 case ARMISD::BR_JT: return "ARMISD::BR_JT";
956 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
957 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
958 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
959 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
960 case ARMISD::CMP: return "ARMISD::CMP";
961 case ARMISD::CMN: return "ARMISD::CMN";
962 case ARMISD::CMPZ: return "ARMISD::CMPZ";
963 case ARMISD::CMPFP: return "ARMISD::CMPFP";
964 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
965 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
966 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
968 case ARMISD::CMOV: return "ARMISD::CMOV";
970 case ARMISD::RBIT: return "ARMISD::RBIT";
972 case ARMISD::FTOSI: return "ARMISD::FTOSI";
973 case ARMISD::FTOUI: return "ARMISD::FTOUI";
974 case ARMISD::SITOF: return "ARMISD::SITOF";
975 case ARMISD::UITOF: return "ARMISD::UITOF";
977 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
978 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
979 case ARMISD::RRX: return "ARMISD::RRX";
981 case ARMISD::ADDC: return "ARMISD::ADDC";
982 case ARMISD::ADDE: return "ARMISD::ADDE";
983 case ARMISD::SUBC: return "ARMISD::SUBC";
984 case ARMISD::SUBE: return "ARMISD::SUBE";
986 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
987 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
989 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
990 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
992 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
994 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
996 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
998 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1000 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1002 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1004 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1005 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1006 case ARMISD::VCGE: return "ARMISD::VCGE";
1007 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1008 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1009 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1010 case ARMISD::VCGT: return "ARMISD::VCGT";
1011 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1012 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1013 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1014 case ARMISD::VTST: return "ARMISD::VTST";
1016 case ARMISD::VSHL: return "ARMISD::VSHL";
1017 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1018 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1019 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1020 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1021 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1022 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1023 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1024 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1025 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1026 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1027 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1028 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1029 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1030 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1031 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1032 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1033 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1034 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1035 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1036 case ARMISD::VDUP: return "ARMISD::VDUP";
1037 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1038 case ARMISD::VEXT: return "ARMISD::VEXT";
1039 case ARMISD::VREV64: return "ARMISD::VREV64";
1040 case ARMISD::VREV32: return "ARMISD::VREV32";
1041 case ARMISD::VREV16: return "ARMISD::VREV16";
1042 case ARMISD::VZIP: return "ARMISD::VZIP";
1043 case ARMISD::VUZP: return "ARMISD::VUZP";
1044 case ARMISD::VTRN: return "ARMISD::VTRN";
1045 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1046 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1047 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1048 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1049 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1050 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1051 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1052 case ARMISD::FMAX: return "ARMISD::FMAX";
1053 case ARMISD::FMIN: return "ARMISD::FMIN";
1054 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1055 case ARMISD::VMINNM: return "ARMISD::VMIN";
1056 case ARMISD::BFI: return "ARMISD::BFI";
1057 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1058 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1059 case ARMISD::VBSL: return "ARMISD::VBSL";
1060 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1061 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1062 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1063 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1064 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1065 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1066 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1067 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1068 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1069 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1070 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1071 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1072 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1073 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1074 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1075 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1076 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1077 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1078 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1079 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1083 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1084 if (!VT.isVector()) return getPointerTy();
1085 return VT.changeVectorElementTypeToInteger();
1088 /// getRegClassFor - Return the register class that should be used for the
1089 /// specified value type.
1090 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1091 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1092 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1093 // load / store 4 to 8 consecutive D registers.
1094 if (Subtarget->hasNEON()) {
1095 if (VT == MVT::v4i64)
1096 return &ARM::QQPRRegClass;
1097 if (VT == MVT::v8i64)
1098 return &ARM::QQQQPRRegClass;
1100 return TargetLowering::getRegClassFor(VT);
1103 // Create a fast isel object.
1105 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1106 const TargetLibraryInfo *libInfo) const {
1107 return ARM::createFastISel(funcInfo, libInfo);
1110 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1111 /// be used for loads / stores from the global.
1112 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1113 return (Subtarget->isThumb1Only() ? 127 : 4095);
1116 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1117 unsigned NumVals = N->getNumValues();
1119 return Sched::RegPressure;
1121 for (unsigned i = 0; i != NumVals; ++i) {
1122 EVT VT = N->getValueType(i);
1123 if (VT == MVT::Glue || VT == MVT::Other)
1125 if (VT.isFloatingPoint() || VT.isVector())
1129 if (!N->isMachineOpcode())
1130 return Sched::RegPressure;
1132 // Load are scheduled for latency even if there instruction itinerary
1133 // is not available.
1134 const TargetInstrInfo *TII =
1135 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1136 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1138 if (MCID.getNumDefs() == 0)
1139 return Sched::RegPressure;
1140 if (!Itins->isEmpty() &&
1141 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1144 return Sched::RegPressure;
1147 //===----------------------------------------------------------------------===//
1149 //===----------------------------------------------------------------------===//
1151 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1152 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1154 default: llvm_unreachable("Unknown condition code!");
1155 case ISD::SETNE: return ARMCC::NE;
1156 case ISD::SETEQ: return ARMCC::EQ;
1157 case ISD::SETGT: return ARMCC::GT;
1158 case ISD::SETGE: return ARMCC::GE;
1159 case ISD::SETLT: return ARMCC::LT;
1160 case ISD::SETLE: return ARMCC::LE;
1161 case ISD::SETUGT: return ARMCC::HI;
1162 case ISD::SETUGE: return ARMCC::HS;
1163 case ISD::SETULT: return ARMCC::LO;
1164 case ISD::SETULE: return ARMCC::LS;
1168 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1169 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1170 ARMCC::CondCodes &CondCode2) {
1171 CondCode2 = ARMCC::AL;
1173 default: llvm_unreachable("Unknown FP condition!");
1175 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1177 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1179 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1180 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1181 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1182 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1183 case ISD::SETO: CondCode = ARMCC::VC; break;
1184 case ISD::SETUO: CondCode = ARMCC::VS; break;
1185 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1186 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1187 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1189 case ISD::SETULT: CondCode = ARMCC::LT; break;
1191 case ISD::SETULE: CondCode = ARMCC::LE; break;
1193 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1197 //===----------------------------------------------------------------------===//
1198 // Calling Convention Implementation
1199 //===----------------------------------------------------------------------===//
1201 #include "ARMGenCallingConv.inc"
1203 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1204 /// account presence of floating point hardware and calling convention
1205 /// limitations, such as support for variadic functions.
1207 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1208 bool isVarArg) const {
1211 llvm_unreachable("Unsupported calling convention");
1212 case CallingConv::ARM_AAPCS:
1213 case CallingConv::ARM_APCS:
1214 case CallingConv::GHC:
1216 case CallingConv::ARM_AAPCS_VFP:
1217 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1218 case CallingConv::C:
1219 if (!Subtarget->isAAPCS_ABI())
1220 return CallingConv::ARM_APCS;
1221 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1222 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1224 return CallingConv::ARM_AAPCS_VFP;
1226 return CallingConv::ARM_AAPCS;
1227 case CallingConv::Fast:
1228 if (!Subtarget->isAAPCS_ABI()) {
1229 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1230 return CallingConv::Fast;
1231 return CallingConv::ARM_APCS;
1232 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1233 return CallingConv::ARM_AAPCS_VFP;
1235 return CallingConv::ARM_AAPCS;
1239 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1240 /// CallingConvention.
1241 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1243 bool isVarArg) const {
1244 switch (getEffectiveCallingConv(CC, isVarArg)) {
1246 llvm_unreachable("Unsupported calling convention");
1247 case CallingConv::ARM_APCS:
1248 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1249 case CallingConv::ARM_AAPCS:
1250 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1251 case CallingConv::ARM_AAPCS_VFP:
1252 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1253 case CallingConv::Fast:
1254 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1255 case CallingConv::GHC:
1256 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1260 /// LowerCallResult - Lower the result values of a call into the
1261 /// appropriate copies out of appropriate physical registers.
1263 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1264 CallingConv::ID CallConv, bool isVarArg,
1265 const SmallVectorImpl<ISD::InputArg> &Ins,
1266 SDLoc dl, SelectionDAG &DAG,
1267 SmallVectorImpl<SDValue> &InVals,
1268 bool isThisReturn, SDValue ThisVal) const {
1270 // Assign locations to each value returned by this call.
1271 SmallVector<CCValAssign, 16> RVLocs;
1272 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1273 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1274 CCInfo.AnalyzeCallResult(Ins,
1275 CCAssignFnForNode(CallConv, /* Return*/ true,
1278 // Copy all of the result registers out of their specified physreg.
1279 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1280 CCValAssign VA = RVLocs[i];
1282 // Pass 'this' value directly from the argument to return value, to avoid
1283 // reg unit interference
1284 if (i == 0 && isThisReturn) {
1285 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1286 "unexpected return calling convention register assignment");
1287 InVals.push_back(ThisVal);
1292 if (VA.needsCustom()) {
1293 // Handle f64 or half of a v2f64.
1294 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1296 Chain = Lo.getValue(1);
1297 InFlag = Lo.getValue(2);
1298 VA = RVLocs[++i]; // skip ahead to next loc
1299 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1301 Chain = Hi.getValue(1);
1302 InFlag = Hi.getValue(2);
1303 if (!Subtarget->isLittle())
1305 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1307 if (VA.getLocVT() == MVT::v2f64) {
1308 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1309 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1310 DAG.getConstant(0, MVT::i32));
1312 VA = RVLocs[++i]; // skip ahead to next loc
1313 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1314 Chain = Lo.getValue(1);
1315 InFlag = Lo.getValue(2);
1316 VA = RVLocs[++i]; // skip ahead to next loc
1317 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1318 Chain = Hi.getValue(1);
1319 InFlag = Hi.getValue(2);
1320 if (!Subtarget->isLittle())
1322 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1323 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1324 DAG.getConstant(1, MVT::i32));
1327 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1329 Chain = Val.getValue(1);
1330 InFlag = Val.getValue(2);
1333 switch (VA.getLocInfo()) {
1334 default: llvm_unreachable("Unknown loc info!");
1335 case CCValAssign::Full: break;
1336 case CCValAssign::BCvt:
1337 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1341 InVals.push_back(Val);
1347 /// LowerMemOpCallTo - Store the argument to the stack.
1349 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1350 SDValue StackPtr, SDValue Arg,
1351 SDLoc dl, SelectionDAG &DAG,
1352 const CCValAssign &VA,
1353 ISD::ArgFlagsTy Flags) const {
1354 unsigned LocMemOffset = VA.getLocMemOffset();
1355 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1356 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1357 return DAG.getStore(Chain, dl, Arg, PtrOff,
1358 MachinePointerInfo::getStack(LocMemOffset),
1362 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1363 SDValue Chain, SDValue &Arg,
1364 RegsToPassVector &RegsToPass,
1365 CCValAssign &VA, CCValAssign &NextVA,
1367 SmallVectorImpl<SDValue> &MemOpChains,
1368 ISD::ArgFlagsTy Flags) const {
1370 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1371 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1372 unsigned id = Subtarget->isLittle() ? 0 : 1;
1373 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1375 if (NextVA.isRegLoc())
1376 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1378 assert(NextVA.isMemLoc());
1379 if (!StackPtr.getNode())
1380 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1382 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1388 /// LowerCall - Lowering a call into a callseq_start <-
1389 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1392 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1393 SmallVectorImpl<SDValue> &InVals) const {
1394 SelectionDAG &DAG = CLI.DAG;
1396 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1397 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1398 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1399 SDValue Chain = CLI.Chain;
1400 SDValue Callee = CLI.Callee;
1401 bool &isTailCall = CLI.IsTailCall;
1402 CallingConv::ID CallConv = CLI.CallConv;
1403 bool doesNotRet = CLI.DoesNotReturn;
1404 bool isVarArg = CLI.IsVarArg;
1406 MachineFunction &MF = DAG.getMachineFunction();
1407 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1408 bool isThisReturn = false;
1409 bool isSibCall = false;
1411 // Disable tail calls if they're not supported.
1412 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1416 // Check if it's really possible to do a tail call.
1417 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1418 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1419 Outs, OutVals, Ins, DAG);
1420 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1421 report_fatal_error("failed to perform tail call elimination on a call "
1422 "site marked musttail");
1423 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1424 // detected sibcalls.
1431 // Analyze operands of the call, assigning locations to each operand.
1432 SmallVector<CCValAssign, 16> ArgLocs;
1433 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1434 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1435 CCInfo.AnalyzeCallOperands(Outs,
1436 CCAssignFnForNode(CallConv, /* Return*/ false,
1439 // Get a count of how many bytes are to be pushed on the stack.
1440 unsigned NumBytes = CCInfo.getNextStackOffset();
1442 // For tail calls, memory operands are available in our caller's stack.
1446 // Adjust the stack pointer for the new arguments...
1447 // These operations are automatically eliminated by the prolog/epilog pass
1449 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1452 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1454 RegsToPassVector RegsToPass;
1455 SmallVector<SDValue, 8> MemOpChains;
1457 // Walk the register/memloc assignments, inserting copies/loads. In the case
1458 // of tail call optimization, arguments are handled later.
1459 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1461 ++i, ++realArgIdx) {
1462 CCValAssign &VA = ArgLocs[i];
1463 SDValue Arg = OutVals[realArgIdx];
1464 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1465 bool isByVal = Flags.isByVal();
1467 // Promote the value if needed.
1468 switch (VA.getLocInfo()) {
1469 default: llvm_unreachable("Unknown loc info!");
1470 case CCValAssign::Full: break;
1471 case CCValAssign::SExt:
1472 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1474 case CCValAssign::ZExt:
1475 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1477 case CCValAssign::AExt:
1478 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1480 case CCValAssign::BCvt:
1481 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1485 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1486 if (VA.needsCustom()) {
1487 if (VA.getLocVT() == MVT::v2f64) {
1488 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1489 DAG.getConstant(0, MVT::i32));
1490 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1491 DAG.getConstant(1, MVT::i32));
1493 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1494 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1496 VA = ArgLocs[++i]; // skip ahead to next loc
1497 if (VA.isRegLoc()) {
1498 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1499 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1501 assert(VA.isMemLoc());
1503 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1504 dl, DAG, VA, Flags));
1507 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1508 StackPtr, MemOpChains, Flags);
1510 } else if (VA.isRegLoc()) {
1511 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1512 assert(VA.getLocVT() == MVT::i32 &&
1513 "unexpected calling convention register assignment");
1514 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1515 "unexpected use of 'returned'");
1516 isThisReturn = true;
1518 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1519 } else if (isByVal) {
1520 assert(VA.isMemLoc());
1521 unsigned offset = 0;
1523 // True if this byval aggregate will be split between registers
1525 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1526 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1528 if (CurByValIdx < ByValArgsCount) {
1530 unsigned RegBegin, RegEnd;
1531 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1533 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1535 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1536 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1537 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1538 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1539 MachinePointerInfo(),
1540 false, false, false,
1541 DAG.InferPtrAlignment(AddArg));
1542 MemOpChains.push_back(Load.getValue(1));
1543 RegsToPass.push_back(std::make_pair(j, Load));
1546 // If parameter size outsides register area, "offset" value
1547 // helps us to calculate stack slot for remained part properly.
1548 offset = RegEnd - RegBegin;
1550 CCInfo.nextInRegsParam();
1553 if (Flags.getByValSize() > 4*offset) {
1554 unsigned LocMemOffset = VA.getLocMemOffset();
1555 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1556 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1558 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1559 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1560 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1562 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1564 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1565 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1566 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1569 } else if (!isSibCall) {
1570 assert(VA.isMemLoc());
1572 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1573 dl, DAG, VA, Flags));
1577 if (!MemOpChains.empty())
1578 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1580 // Build a sequence of copy-to-reg nodes chained together with token chain
1581 // and flag operands which copy the outgoing args into the appropriate regs.
1583 // Tail call byval lowering might overwrite argument registers so in case of
1584 // tail call optimization the copies to registers are lowered later.
1586 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1587 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1588 RegsToPass[i].second, InFlag);
1589 InFlag = Chain.getValue(1);
1592 // For tail calls lower the arguments to the 'real' stack slot.
1594 // Force all the incoming stack arguments to be loaded from the stack
1595 // before any new outgoing arguments are stored to the stack, because the
1596 // outgoing stack slots may alias the incoming argument stack slots, and
1597 // the alias isn't otherwise explicit. This is slightly more conservative
1598 // than necessary, because it means that each store effectively depends
1599 // on every argument instead of just those arguments it would clobber.
1601 // Do not flag preceding copytoreg stuff together with the following stuff.
1603 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1604 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1605 RegsToPass[i].second, InFlag);
1606 InFlag = Chain.getValue(1);
1611 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1612 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1613 // node so that legalize doesn't hack it.
1614 bool isDirect = false;
1615 bool isARMFunc = false;
1616 bool isLocalARMFunc = false;
1617 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1619 if (EnableARMLongCalls) {
1620 assert((Subtarget->isTargetWindows() ||
1621 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1622 "long-calls with non-static relocation model!");
1623 // Handle a global address or an external symbol. If it's not one of
1624 // those, the target's already in a register, so we don't need to do
1626 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1627 const GlobalValue *GV = G->getGlobal();
1628 // Create a constant pool entry for the callee address
1629 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1630 ARMConstantPoolValue *CPV =
1631 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1633 // Get the address of the callee into a register
1634 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1635 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1636 Callee = DAG.getLoad(getPointerTy(), dl,
1637 DAG.getEntryNode(), CPAddr,
1638 MachinePointerInfo::getConstantPool(),
1639 false, false, false, 0);
1640 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1641 const char *Sym = S->getSymbol();
1643 // Create a constant pool entry for the callee address
1644 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1645 ARMConstantPoolValue *CPV =
1646 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1647 ARMPCLabelIndex, 0);
1648 // Get the address of the callee into a register
1649 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1650 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1651 Callee = DAG.getLoad(getPointerTy(), dl,
1652 DAG.getEntryNode(), CPAddr,
1653 MachinePointerInfo::getConstantPool(),
1654 false, false, false, 0);
1656 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1657 const GlobalValue *GV = G->getGlobal();
1659 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1660 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1661 getTargetMachine().getRelocationModel() != Reloc::Static;
1662 isARMFunc = !Subtarget->isThumb() || isStub;
1663 // ARM call to a local ARM function is predicable.
1664 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1665 // tBX takes a register source operand.
1666 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1667 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1668 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1669 DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1670 } else if (Subtarget->isTargetCOFF()) {
1671 assert(Subtarget->isTargetWindows() &&
1672 "Windows is the only supported COFF target");
1673 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1674 ? ARMII::MO_DLLIMPORT
1675 : ARMII::MO_NO_FLAG;
1676 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1678 if (GV->hasDLLImportStorageClass())
1679 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1680 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1681 Callee), MachinePointerInfo::getGOT(),
1682 false, false, false, 0);
1684 // On ELF targets for PIC code, direct calls should go through the PLT
1685 unsigned OpFlags = 0;
1686 if (Subtarget->isTargetELF() &&
1687 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1688 OpFlags = ARMII::MO_PLT;
1689 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1691 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1693 bool isStub = Subtarget->isTargetMachO() &&
1694 getTargetMachine().getRelocationModel() != Reloc::Static;
1695 isARMFunc = !Subtarget->isThumb() || isStub;
1696 // tBX takes a register source operand.
1697 const char *Sym = S->getSymbol();
1698 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1699 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1700 ARMConstantPoolValue *CPV =
1701 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1702 ARMPCLabelIndex, 4);
1703 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1704 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1705 Callee = DAG.getLoad(getPointerTy(), dl,
1706 DAG.getEntryNode(), CPAddr,
1707 MachinePointerInfo::getConstantPool(),
1708 false, false, false, 0);
1709 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1710 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1711 getPointerTy(), Callee, PICLabel);
1713 unsigned OpFlags = 0;
1714 // On ELF targets for PIC code, direct calls should go through the PLT
1715 if (Subtarget->isTargetELF() &&
1716 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1717 OpFlags = ARMII::MO_PLT;
1718 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1722 // FIXME: handle tail calls differently.
1724 bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1725 AttributeSet::FunctionIndex, Attribute::MinSize);
1726 if (Subtarget->isThumb()) {
1727 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1728 CallOpc = ARMISD::CALL_NOLINK;
1730 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1732 if (!isDirect && !Subtarget->hasV5TOps())
1733 CallOpc = ARMISD::CALL_NOLINK;
1734 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1735 // Emit regular call when code size is the priority
1737 // "mov lr, pc; b _foo" to avoid confusing the RSP
1738 CallOpc = ARMISD::CALL_NOLINK;
1740 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1743 std::vector<SDValue> Ops;
1744 Ops.push_back(Chain);
1745 Ops.push_back(Callee);
1747 // Add argument registers to the end of the list so that they are known live
1749 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1750 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1751 RegsToPass[i].second.getValueType()));
1753 // Add a register mask operand representing the call-preserved registers.
1755 const uint32_t *Mask;
1756 const TargetRegisterInfo *TRI =
1757 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1758 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1760 // For 'this' returns, use the R0-preserving mask if applicable
1761 Mask = ARI->getThisReturnPreservedMask(CallConv);
1763 // Set isThisReturn to false if the calling convention is not one that
1764 // allows 'returned' to be modeled in this way, so LowerCallResult does
1765 // not try to pass 'this' straight through
1766 isThisReturn = false;
1767 Mask = ARI->getCallPreservedMask(CallConv);
1770 Mask = ARI->getCallPreservedMask(CallConv);
1772 assert(Mask && "Missing call preserved mask for calling convention");
1773 Ops.push_back(DAG.getRegisterMask(Mask));
1776 if (InFlag.getNode())
1777 Ops.push_back(InFlag);
1779 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1781 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1783 // Returns a chain and a flag for retval copy to use.
1784 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1785 InFlag = Chain.getValue(1);
1787 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1788 DAG.getIntPtrConstant(0, true), InFlag, dl);
1790 InFlag = Chain.getValue(1);
1792 // Handle result values, copying them out of physregs into vregs that we
1794 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1795 InVals, isThisReturn,
1796 isThisReturn ? OutVals[0] : SDValue());
1799 /// HandleByVal - Every parameter *after* a byval parameter is passed
1800 /// on the stack. Remember the next parameter register to allocate,
1801 /// and then confiscate the rest of the parameter registers to insure
1804 ARMTargetLowering::HandleByVal(
1805 CCState *State, unsigned &size, unsigned Align) const {
1806 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1807 assert((State->getCallOrPrologue() == Prologue ||
1808 State->getCallOrPrologue() == Call) &&
1809 "unhandled ParmContext");
1811 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1812 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1813 unsigned AlignInRegs = Align / 4;
1814 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1815 for (unsigned i = 0; i < Waste; ++i)
1816 reg = State->AllocateReg(GPRArgRegs, 4);
1819 unsigned excess = 4 * (ARM::R4 - reg);
1821 // Special case when NSAA != SP and parameter size greater than size of
1822 // all remained GPR regs. In that case we can't split parameter, we must
1823 // send it to stack. We also must set NCRN to R4, so waste all
1824 // remained registers.
1825 const unsigned NSAAOffset = State->getNextStackOffset();
1826 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1827 while (State->AllocateReg(GPRArgRegs, 4))
1832 // First register for byval parameter is the first register that wasn't
1833 // allocated before this method call, so it would be "reg".
1834 // If parameter is small enough to be saved in range [reg, r4), then
1835 // the end (first after last) register would be reg + param-size-in-regs,
1836 // else parameter would be splitted between registers and stack,
1837 // end register would be r4 in this case.
1838 unsigned ByValRegBegin = reg;
1839 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1840 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1841 // Note, first register is allocated in the beginning of function already,
1842 // allocate remained amount of registers we need.
1843 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1844 State->AllocateReg(GPRArgRegs, 4);
1845 // A byval parameter that is split between registers and memory needs its
1846 // size truncated here.
1847 // In the case where the entire structure fits in registers, we set the
1848 // size in memory to zero.
1857 /// MatchingStackOffset - Return true if the given stack call argument is
1858 /// already available in the same position (relatively) of the caller's
1859 /// incoming argument stack.
1861 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1862 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1863 const TargetInstrInfo *TII) {
1864 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1866 if (Arg.getOpcode() == ISD::CopyFromReg) {
1867 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1868 if (!TargetRegisterInfo::isVirtualRegister(VR))
1870 MachineInstr *Def = MRI->getVRegDef(VR);
1873 if (!Flags.isByVal()) {
1874 if (!TII->isLoadFromStackSlot(Def, FI))
1879 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1880 if (Flags.isByVal())
1881 // ByVal argument is passed in as a pointer but it's now being
1882 // dereferenced. e.g.
1883 // define @foo(%struct.X* %A) {
1884 // tail call @bar(%struct.X* byval %A)
1887 SDValue Ptr = Ld->getBasePtr();
1888 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1891 FI = FINode->getIndex();
1895 assert(FI != INT_MAX);
1896 if (!MFI->isFixedObjectIndex(FI))
1898 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1901 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1902 /// for tail call optimization. Targets which want to do tail call
1903 /// optimization should implement this function.
1905 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1906 CallingConv::ID CalleeCC,
1908 bool isCalleeStructRet,
1909 bool isCallerStructRet,
1910 const SmallVectorImpl<ISD::OutputArg> &Outs,
1911 const SmallVectorImpl<SDValue> &OutVals,
1912 const SmallVectorImpl<ISD::InputArg> &Ins,
1913 SelectionDAG& DAG) const {
1914 const Function *CallerF = DAG.getMachineFunction().getFunction();
1915 CallingConv::ID CallerCC = CallerF->getCallingConv();
1916 bool CCMatch = CallerCC == CalleeCC;
1918 // Look for obvious safe cases to perform tail call optimization that do not
1919 // require ABI changes. This is what gcc calls sibcall.
1921 // Do not sibcall optimize vararg calls unless the call site is not passing
1923 if (isVarArg && !Outs.empty())
1926 // Exception-handling functions need a special set of instructions to indicate
1927 // a return to the hardware. Tail-calling another function would probably
1929 if (CallerF->hasFnAttribute("interrupt"))
1932 // Also avoid sibcall optimization if either caller or callee uses struct
1933 // return semantics.
1934 if (isCalleeStructRet || isCallerStructRet)
1937 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1938 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1939 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1940 // support in the assembler and linker to be used. This would need to be
1941 // fixed to fully support tail calls in Thumb1.
1943 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1944 // LR. This means if we need to reload LR, it takes an extra instructions,
1945 // which outweighs the value of the tail call; but here we don't know yet
1946 // whether LR is going to be used. Probably the right approach is to
1947 // generate the tail call here and turn it back into CALL/RET in
1948 // emitEpilogue if LR is used.
1950 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1951 // but we need to make sure there are enough registers; the only valid
1952 // registers are the 4 used for parameters. We don't currently do this
1954 if (Subtarget->isThumb1Only())
1957 // If the calling conventions do not match, then we'd better make sure the
1958 // results are returned in the same way as what the caller expects.
1960 SmallVector<CCValAssign, 16> RVLocs1;
1961 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1962 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1963 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1965 SmallVector<CCValAssign, 16> RVLocs2;
1966 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1967 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1968 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1970 if (RVLocs1.size() != RVLocs2.size())
1972 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1973 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1975 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1977 if (RVLocs1[i].isRegLoc()) {
1978 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1981 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1987 // If Caller's vararg or byval argument has been split between registers and
1988 // stack, do not perform tail call, since part of the argument is in caller's
1990 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1991 getInfo<ARMFunctionInfo>();
1992 if (AFI_Caller->getArgRegsSaveSize())
1995 // If the callee takes no arguments then go on to check the results of the
1997 if (!Outs.empty()) {
1998 // Check if stack adjustment is needed. For now, do not do this if any
1999 // argument is passed on the stack.
2000 SmallVector<CCValAssign, 16> ArgLocs;
2001 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2002 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2003 CCInfo.AnalyzeCallOperands(Outs,
2004 CCAssignFnForNode(CalleeCC, false, isVarArg));
2005 if (CCInfo.getNextStackOffset()) {
2006 MachineFunction &MF = DAG.getMachineFunction();
2008 // Check if the arguments are already laid out in the right way as
2009 // the caller's fixed stack objects.
2010 MachineFrameInfo *MFI = MF.getFrameInfo();
2011 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2012 const TargetInstrInfo *TII =
2013 getTargetMachine().getSubtargetImpl()->getInstrInfo();
2014 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2016 ++i, ++realArgIdx) {
2017 CCValAssign &VA = ArgLocs[i];
2018 EVT RegVT = VA.getLocVT();
2019 SDValue Arg = OutVals[realArgIdx];
2020 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2021 if (VA.getLocInfo() == CCValAssign::Indirect)
2023 if (VA.needsCustom()) {
2024 // f64 and vector types are split into multiple registers or
2025 // register/stack-slot combinations. The types will not match
2026 // the registers; give up on memory f64 refs until we figure
2027 // out what to do about this.
2030 if (!ArgLocs[++i].isRegLoc())
2032 if (RegVT == MVT::v2f64) {
2033 if (!ArgLocs[++i].isRegLoc())
2035 if (!ArgLocs[++i].isRegLoc())
2038 } else if (!VA.isRegLoc()) {
2039 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2051 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2052 MachineFunction &MF, bool isVarArg,
2053 const SmallVectorImpl<ISD::OutputArg> &Outs,
2054 LLVMContext &Context) const {
2055 SmallVector<CCValAssign, 16> RVLocs;
2056 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2057 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2061 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2062 SDLoc DL, SelectionDAG &DAG) {
2063 const MachineFunction &MF = DAG.getMachineFunction();
2064 const Function *F = MF.getFunction();
2066 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2068 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2069 // version of the "preferred return address". These offsets affect the return
2070 // instruction if this is a return from PL1 without hypervisor extensions.
2071 // IRQ/FIQ: +4 "subs pc, lr, #4"
2072 // SWI: 0 "subs pc, lr, #0"
2073 // ABORT: +4 "subs pc, lr, #4"
2074 // UNDEF: +4/+2 "subs pc, lr, #0"
2075 // UNDEF varies depending on where the exception came from ARM or Thumb
2076 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2079 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2082 else if (IntKind == "SWI" || IntKind == "UNDEF")
2085 report_fatal_error("Unsupported interrupt attribute. If present, value "
2086 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2088 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2090 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2094 ARMTargetLowering::LowerReturn(SDValue Chain,
2095 CallingConv::ID CallConv, bool isVarArg,
2096 const SmallVectorImpl<ISD::OutputArg> &Outs,
2097 const SmallVectorImpl<SDValue> &OutVals,
2098 SDLoc dl, SelectionDAG &DAG) const {
2100 // CCValAssign - represent the assignment of the return value to a location.
2101 SmallVector<CCValAssign, 16> RVLocs;
2103 // CCState - Info about the registers and stack slots.
2104 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2105 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2107 // Analyze outgoing return values.
2108 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2112 SmallVector<SDValue, 4> RetOps;
2113 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2114 bool isLittleEndian = Subtarget->isLittle();
2116 MachineFunction &MF = DAG.getMachineFunction();
2117 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2118 AFI->setReturnRegsCount(RVLocs.size());
2120 // Copy the result values into the output registers.
2121 for (unsigned i = 0, realRVLocIdx = 0;
2123 ++i, ++realRVLocIdx) {
2124 CCValAssign &VA = RVLocs[i];
2125 assert(VA.isRegLoc() && "Can only return in registers!");
2127 SDValue Arg = OutVals[realRVLocIdx];
2129 switch (VA.getLocInfo()) {
2130 default: llvm_unreachable("Unknown loc info!");
2131 case CCValAssign::Full: break;
2132 case CCValAssign::BCvt:
2133 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2137 if (VA.needsCustom()) {
2138 if (VA.getLocVT() == MVT::v2f64) {
2139 // Extract the first half and return it in two registers.
2140 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2141 DAG.getConstant(0, MVT::i32));
2142 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2143 DAG.getVTList(MVT::i32, MVT::i32), Half);
2145 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2146 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2148 Flag = Chain.getValue(1);
2149 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2150 VA = RVLocs[++i]; // skip ahead to next loc
2151 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2152 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2154 Flag = Chain.getValue(1);
2155 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2156 VA = RVLocs[++i]; // skip ahead to next loc
2158 // Extract the 2nd half and fall through to handle it as an f64 value.
2159 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2160 DAG.getConstant(1, MVT::i32));
2162 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2164 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2165 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2166 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2167 fmrrd.getValue(isLittleEndian ? 0 : 1),
2169 Flag = Chain.getValue(1);
2170 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2171 VA = RVLocs[++i]; // skip ahead to next loc
2172 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2173 fmrrd.getValue(isLittleEndian ? 1 : 0),
2176 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2178 // Guarantee that all emitted copies are
2179 // stuck together, avoiding something bad.
2180 Flag = Chain.getValue(1);
2181 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2184 // Update chain and glue.
2187 RetOps.push_back(Flag);
2189 // CPUs which aren't M-class use a special sequence to return from
2190 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2191 // though we use "subs pc, lr, #N").
2193 // M-class CPUs actually use a normal return sequence with a special
2194 // (hardware-provided) value in LR, so the normal code path works.
2195 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2196 !Subtarget->isMClass()) {
2197 if (Subtarget->isThumb1Only())
2198 report_fatal_error("interrupt attribute is not supported in Thumb1");
2199 return LowerInterruptReturn(RetOps, dl, DAG);
2202 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2205 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2206 if (N->getNumValues() != 1)
2208 if (!N->hasNUsesOfValue(1, 0))
2211 SDValue TCChain = Chain;
2212 SDNode *Copy = *N->use_begin();
2213 if (Copy->getOpcode() == ISD::CopyToReg) {
2214 // If the copy has a glue operand, we conservatively assume it isn't safe to
2215 // perform a tail call.
2216 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2218 TCChain = Copy->getOperand(0);
2219 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2220 SDNode *VMov = Copy;
2221 // f64 returned in a pair of GPRs.
2222 SmallPtrSet<SDNode*, 2> Copies;
2223 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2225 if (UI->getOpcode() != ISD::CopyToReg)
2229 if (Copies.size() > 2)
2232 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2234 SDValue UseChain = UI->getOperand(0);
2235 if (Copies.count(UseChain.getNode()))
2242 } else if (Copy->getOpcode() == ISD::BITCAST) {
2243 // f32 returned in a single GPR.
2244 if (!Copy->hasOneUse())
2246 Copy = *Copy->use_begin();
2247 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2249 TCChain = Copy->getOperand(0);
2254 bool HasRet = false;
2255 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2257 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2258 UI->getOpcode() != ARMISD::INTRET_FLAG)
2270 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2271 if (!Subtarget->supportsTailCall())
2274 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2277 return !Subtarget->isThumb1Only();
2280 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2281 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2282 // one of the above mentioned nodes. It has to be wrapped because otherwise
2283 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2284 // be used to form addressing mode. These wrapped nodes will be selected
2286 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2287 EVT PtrVT = Op.getValueType();
2288 // FIXME there is no actual debug info here
2290 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2292 if (CP->isMachineConstantPoolEntry())
2293 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2294 CP->getAlignment());
2296 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2297 CP->getAlignment());
2298 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2301 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2302 return MachineJumpTableInfo::EK_Inline;
2305 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2306 SelectionDAG &DAG) const {
2307 MachineFunction &MF = DAG.getMachineFunction();
2308 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2309 unsigned ARMPCLabelIndex = 0;
2311 EVT PtrVT = getPointerTy();
2312 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2313 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2315 if (RelocM == Reloc::Static) {
2316 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2318 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2319 ARMPCLabelIndex = AFI->createPICLabelUId();
2320 ARMConstantPoolValue *CPV =
2321 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2322 ARMCP::CPBlockAddress, PCAdj);
2323 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2325 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2326 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2327 MachinePointerInfo::getConstantPool(),
2328 false, false, false, 0);
2329 if (RelocM == Reloc::Static)
2331 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2332 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2335 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2337 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2338 SelectionDAG &DAG) const {
2340 EVT PtrVT = getPointerTy();
2341 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2342 MachineFunction &MF = DAG.getMachineFunction();
2343 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2344 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2345 ARMConstantPoolValue *CPV =
2346 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2347 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2348 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2349 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2350 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2351 MachinePointerInfo::getConstantPool(),
2352 false, false, false, 0);
2353 SDValue Chain = Argument.getValue(1);
2355 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2356 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2358 // call __tls_get_addr.
2361 Entry.Node = Argument;
2362 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2363 Args.push_back(Entry);
2365 // FIXME: is there useful debug info available here?
2366 TargetLowering::CallLoweringInfo CLI(DAG);
2367 CLI.setDebugLoc(dl).setChain(Chain)
2368 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2369 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2372 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2373 return CallResult.first;
2376 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2377 // "local exec" model.
2379 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2381 TLSModel::Model model) const {
2382 const GlobalValue *GV = GA->getGlobal();
2385 SDValue Chain = DAG.getEntryNode();
2386 EVT PtrVT = getPointerTy();
2387 // Get the Thread Pointer
2388 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2390 if (model == TLSModel::InitialExec) {
2391 MachineFunction &MF = DAG.getMachineFunction();
2392 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2393 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2394 // Initial exec model.
2395 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2396 ARMConstantPoolValue *CPV =
2397 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2398 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2400 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2401 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2402 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2403 MachinePointerInfo::getConstantPool(),
2404 false, false, false, 0);
2405 Chain = Offset.getValue(1);
2407 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2408 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2410 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2411 MachinePointerInfo::getConstantPool(),
2412 false, false, false, 0);
2415 assert(model == TLSModel::LocalExec);
2416 ARMConstantPoolValue *CPV =
2417 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2418 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2419 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2420 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2421 MachinePointerInfo::getConstantPool(),
2422 false, false, false, 0);
2425 // The address of the thread local variable is the add of the thread
2426 // pointer with the offset of the variable.
2427 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2431 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2432 // TODO: implement the "local dynamic" model
2433 assert(Subtarget->isTargetELF() &&
2434 "TLS not implemented for non-ELF targets");
2435 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2437 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2440 case TLSModel::GeneralDynamic:
2441 case TLSModel::LocalDynamic:
2442 return LowerToTLSGeneralDynamicModel(GA, DAG);
2443 case TLSModel::InitialExec:
2444 case TLSModel::LocalExec:
2445 return LowerToTLSExecModels(GA, DAG, model);
2447 llvm_unreachable("bogus TLS model");
2450 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2451 SelectionDAG &DAG) const {
2452 EVT PtrVT = getPointerTy();
2454 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2455 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2456 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2457 ARMConstantPoolValue *CPV =
2458 ARMConstantPoolConstant::Create(GV,
2459 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2460 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2461 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2462 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2464 MachinePointerInfo::getConstantPool(),
2465 false, false, false, 0);
2466 SDValue Chain = Result.getValue(1);
2467 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2468 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2470 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2471 MachinePointerInfo::getGOT(),
2472 false, false, false, 0);
2476 // If we have T2 ops, we can materialize the address directly via movt/movw
2477 // pair. This is always cheaper.
2478 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2480 // FIXME: Once remat is capable of dealing with instructions with register
2481 // operands, expand this into two nodes.
2482 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2483 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2485 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2486 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2487 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2488 MachinePointerInfo::getConstantPool(),
2489 false, false, false, 0);
2493 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2494 SelectionDAG &DAG) const {
2495 EVT PtrVT = getPointerTy();
2497 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2498 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2500 if (Subtarget->useMovt(DAG.getMachineFunction()))
2503 // FIXME: Once remat is capable of dealing with instructions with register
2504 // operands, expand this into multiple nodes
2506 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2508 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2509 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2511 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2512 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2513 MachinePointerInfo::getGOT(), false, false, false, 0);
2517 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2518 SelectionDAG &DAG) const {
2519 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2520 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2521 "Windows on ARM expects to use movw/movt");
2523 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2524 const ARMII::TOF TargetFlags =
2525 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2526 EVT PtrVT = getPointerTy();
2532 // FIXME: Once remat is capable of dealing with instructions with register
2533 // operands, expand this into two nodes.
2534 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2535 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2537 if (GV->hasDLLImportStorageClass())
2538 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2539 MachinePointerInfo::getGOT(), false, false, false, 0);
2543 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2544 SelectionDAG &DAG) const {
2545 assert(Subtarget->isTargetELF() &&
2546 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2547 MachineFunction &MF = DAG.getMachineFunction();
2548 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2549 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2550 EVT PtrVT = getPointerTy();
2552 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2553 ARMConstantPoolValue *CPV =
2554 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2555 ARMPCLabelIndex, PCAdj);
2556 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2557 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2558 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2559 MachinePointerInfo::getConstantPool(),
2560 false, false, false, 0);
2561 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2562 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2566 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2568 SDValue Val = DAG.getConstant(0, MVT::i32);
2569 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2570 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2571 Op.getOperand(1), Val);
2575 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2577 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2578 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2582 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2583 const ARMSubtarget *Subtarget) const {
2584 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2587 default: return SDValue(); // Don't custom lower most intrinsics.
2588 case Intrinsic::arm_rbit: {
2589 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2590 "RBIT intrinsic must have i32 type!");
2591 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2593 case Intrinsic::arm_thread_pointer: {
2594 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2595 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2597 case Intrinsic::eh_sjlj_lsda: {
2598 MachineFunction &MF = DAG.getMachineFunction();
2599 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2600 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2601 EVT PtrVT = getPointerTy();
2602 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2604 unsigned PCAdj = (RelocM != Reloc::PIC_)
2605 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2606 ARMConstantPoolValue *CPV =
2607 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2608 ARMCP::CPLSDA, PCAdj);
2609 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2610 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2612 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2613 MachinePointerInfo::getConstantPool(),
2614 false, false, false, 0);
2616 if (RelocM == Reloc::PIC_) {
2617 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2618 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2622 case Intrinsic::arm_neon_vmulls:
2623 case Intrinsic::arm_neon_vmullu: {
2624 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2625 ? ARMISD::VMULLs : ARMISD::VMULLu;
2626 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2627 Op.getOperand(1), Op.getOperand(2));
2632 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2633 const ARMSubtarget *Subtarget) {
2634 // FIXME: handle "fence singlethread" more efficiently.
2636 if (!Subtarget->hasDataBarrier()) {
2637 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2638 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2640 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2641 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2642 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2643 DAG.getConstant(0, MVT::i32));
2646 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2647 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2648 unsigned Domain = ARM_MB::ISH;
2649 if (Subtarget->isMClass()) {
2650 // Only a full system barrier exists in the M-class architectures.
2651 Domain = ARM_MB::SY;
2652 } else if (Subtarget->isSwift() && Ord == Release) {
2653 // Swift happens to implement ISHST barriers in a way that's compatible with
2654 // Release semantics but weaker than ISH so we'd be fools not to use
2655 // it. Beware: other processors probably don't!
2656 Domain = ARM_MB::ISHST;
2659 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2660 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2661 DAG.getConstant(Domain, MVT::i32));
2664 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2665 const ARMSubtarget *Subtarget) {
2666 // ARM pre v5TE and Thumb1 does not have preload instructions.
2667 if (!(Subtarget->isThumb2() ||
2668 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2669 // Just preserve the chain.
2670 return Op.getOperand(0);
2673 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2675 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2676 // ARMv7 with MP extension has PLDW.
2677 return Op.getOperand(0);
2679 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2680 if (Subtarget->isThumb()) {
2682 isRead = ~isRead & 1;
2683 isData = ~isData & 1;
2686 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2687 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2688 DAG.getConstant(isData, MVT::i32));
2691 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2692 MachineFunction &MF = DAG.getMachineFunction();
2693 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2695 // vastart just stores the address of the VarArgsFrameIndex slot into the
2696 // memory location argument.
2698 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2699 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2700 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2701 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2702 MachinePointerInfo(SV), false, false, 0);
2706 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2707 SDValue &Root, SelectionDAG &DAG,
2709 MachineFunction &MF = DAG.getMachineFunction();
2710 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2712 const TargetRegisterClass *RC;
2713 if (AFI->isThumb1OnlyFunction())
2714 RC = &ARM::tGPRRegClass;
2716 RC = &ARM::GPRRegClass;
2718 // Transform the arguments stored in physical registers into virtual ones.
2719 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2720 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2723 if (NextVA.isMemLoc()) {
2724 MachineFrameInfo *MFI = MF.getFrameInfo();
2725 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2727 // Create load node to retrieve arguments from the stack.
2728 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2729 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2730 MachinePointerInfo::getFixedStack(FI),
2731 false, false, false, 0);
2733 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2734 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2736 if (!Subtarget->isLittle())
2737 std::swap (ArgValue, ArgValue2);
2738 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2742 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2743 unsigned InRegsParamRecordIdx,
2745 unsigned &ArgRegsSize,
2746 unsigned &ArgRegsSaveSize)
2749 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2750 unsigned RBegin, REnd;
2751 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2752 NumGPRs = REnd - RBegin;
2754 unsigned int firstUnalloced;
2755 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2756 sizeof(GPRArgRegs) /
2757 sizeof(GPRArgRegs[0]));
2758 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2761 unsigned Align = MF.getTarget()
2763 ->getFrameLowering()
2764 ->getStackAlignment();
2765 ArgRegsSize = NumGPRs * 4;
2767 // If parameter is split between stack and GPRs...
2768 if (NumGPRs && Align > 4 &&
2769 (ArgRegsSize < ArgSize ||
2770 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2771 // Add padding for part of param recovered from GPRs. For example,
2772 // if Align == 8, its last byte must be at address K*8 - 1.
2773 // We need to do it, since remained (stack) part of parameter has
2774 // stack alignment, and we need to "attach" "GPRs head" without gaps
2777 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2778 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2780 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2782 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2783 ArgRegsSaveSize = ArgRegsSize + Padding;
2785 // We don't need to extend regs save size for byval parameters if they
2786 // are passed via GPRs only.
2787 ArgRegsSaveSize = ArgRegsSize;
2790 // The remaining GPRs hold either the beginning of variable-argument
2791 // data, or the beginning of an aggregate passed by value (usually
2792 // byval). Either way, we allocate stack slots adjacent to the data
2793 // provided by our caller, and store the unallocated registers there.
2794 // If this is a variadic function, the va_list pointer will begin with
2795 // these values; otherwise, this reassembles a (byval) structure that
2796 // was split between registers and memory.
2797 // Return: The frame index registers were stored into.
2799 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2800 SDLoc dl, SDValue &Chain,
2801 const Value *OrigArg,
2802 unsigned InRegsParamRecordIdx,
2803 unsigned OffsetFromOrigArg,
2807 unsigned ByValStoreOffset,
2808 unsigned TotalArgRegsSaveSize) const {
2810 // Currently, two use-cases possible:
2811 // Case #1. Non-var-args function, and we meet first byval parameter.
2812 // Setup first unallocated register as first byval register;
2813 // eat all remained registers
2814 // (these two actions are performed by HandleByVal method).
2815 // Then, here, we initialize stack frame with
2816 // "store-reg" instructions.
2817 // Case #2. Var-args function, that doesn't contain byval parameters.
2818 // The same: eat all remained unallocated registers,
2819 // initialize stack frame.
2821 MachineFunction &MF = DAG.getMachineFunction();
2822 MachineFrameInfo *MFI = MF.getFrameInfo();
2823 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2824 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2825 unsigned RBegin, REnd;
2826 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2827 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2828 firstRegToSaveIndex = RBegin - ARM::R0;
2829 lastRegToSaveIndex = REnd - ARM::R0;
2831 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2832 (GPRArgRegs, array_lengthof(GPRArgRegs));
2833 lastRegToSaveIndex = 4;
2836 unsigned ArgRegsSize, ArgRegsSaveSize;
2837 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2838 ArgRegsSize, ArgRegsSaveSize);
2840 // Store any by-val regs to their spots on the stack so that they may be
2841 // loaded by deferencing the result of formal parameter pointer or va_next.
2842 // Note: once stack area for byval/varargs registers
2843 // was initialized, it can't be initialized again.
2844 if (ArgRegsSaveSize) {
2845 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2848 assert(AFI->getStoredByValParamsPadding() == 0 &&
2849 "The only parameter may be padded.");
2850 AFI->setStoredByValParamsPadding(Padding);
2853 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2856 (int64_t)TotalArgRegsSaveSize,
2858 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2860 MFI->CreateFixedObject(Padding,
2861 ArgOffset + ByValStoreOffset -
2862 (int64_t)ArgRegsSaveSize,
2866 SmallVector<SDValue, 4> MemOps;
2867 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2868 ++firstRegToSaveIndex, ++i) {
2869 const TargetRegisterClass *RC;
2870 if (AFI->isThumb1OnlyFunction())
2871 RC = &ARM::tGPRRegClass;
2873 RC = &ARM::GPRRegClass;
2875 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2876 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2878 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2879 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2881 MemOps.push_back(Store);
2882 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2883 DAG.getConstant(4, getPointerTy()));
2886 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2888 if (!MemOps.empty())
2889 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2893 // We cannot allocate a zero-byte object for the first variadic argument,
2894 // so just make up a size.
2897 // This will point to the next argument passed via stack.
2898 return MFI->CreateFixedObject(
2899 ArgSize, ArgOffset, !ForceMutable);
2903 // Setup stack frame, the va_list pointer will start from.
2905 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2906 SDLoc dl, SDValue &Chain,
2908 unsigned TotalArgRegsSaveSize,
2909 bool ForceMutable) const {
2910 MachineFunction &MF = DAG.getMachineFunction();
2911 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2913 // Try to store any remaining integer argument regs
2914 // to their spots on the stack so that they may be loaded by deferencing
2915 // the result of va_next.
2916 // If there is no regs to be stored, just point address after last
2917 // argument passed via stack.
2919 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2920 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2921 0, TotalArgRegsSaveSize);
2923 AFI->setVarArgsFrameIndex(FrameIndex);
2927 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2928 CallingConv::ID CallConv, bool isVarArg,
2929 const SmallVectorImpl<ISD::InputArg>
2931 SDLoc dl, SelectionDAG &DAG,
2932 SmallVectorImpl<SDValue> &InVals)
2934 MachineFunction &MF = DAG.getMachineFunction();
2935 MachineFrameInfo *MFI = MF.getFrameInfo();
2937 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2939 // Assign locations to all of the incoming arguments.
2940 SmallVector<CCValAssign, 16> ArgLocs;
2941 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2942 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2943 CCInfo.AnalyzeFormalArguments(Ins,
2944 CCAssignFnForNode(CallConv, /* Return*/ false,
2947 SmallVector<SDValue, 16> ArgValues;
2948 int lastInsIndex = -1;
2950 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2951 unsigned CurArgIdx = 0;
2953 // Initially ArgRegsSaveSize is zero.
2954 // Then we increase this value each time we meet byval parameter.
2955 // We also increase this value in case of varargs function.
2956 AFI->setArgRegsSaveSize(0);
2958 unsigned ByValStoreOffset = 0;
2959 unsigned TotalArgRegsSaveSize = 0;
2960 unsigned ArgRegsSaveSizeMaxAlign = 4;
2962 // Calculate the amount of stack space that we need to allocate to store
2963 // byval and variadic arguments that are passed in registers.
2964 // We need to know this before we allocate the first byval or variadic
2965 // argument, as they will be allocated a stack slot below the CFA (Canonical
2966 // Frame Address, the stack pointer at entry to the function).
2967 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2968 CCValAssign &VA = ArgLocs[i];
2969 if (VA.isMemLoc()) {
2970 int index = VA.getValNo();
2971 if (index != lastInsIndex) {
2972 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2973 if (Flags.isByVal()) {
2974 unsigned ExtraArgRegsSize;
2975 unsigned ExtraArgRegsSaveSize;
2976 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2977 Flags.getByValSize(),
2978 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2980 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2981 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2982 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2983 CCInfo.nextInRegsParam();
2985 lastInsIndex = index;
2989 CCInfo.rewindByValRegsInfo();
2992 unsigned ExtraArgRegsSize;
2993 unsigned ExtraArgRegsSaveSize;
2994 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2995 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2996 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2998 // If the arg regs save area contains N-byte aligned values, the
2999 // bottom of it must be at least N-byte aligned.
3000 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3001 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3003 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3004 CCValAssign &VA = ArgLocs[i];
3005 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3006 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3007 // Arguments stored in registers.
3008 if (VA.isRegLoc()) {
3009 EVT RegVT = VA.getLocVT();
3011 if (VA.needsCustom()) {
3012 // f64 and vector types are split up into multiple registers or
3013 // combinations of registers and stack slots.
3014 if (VA.getLocVT() == MVT::v2f64) {
3015 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3017 VA = ArgLocs[++i]; // skip ahead to next loc
3019 if (VA.isMemLoc()) {
3020 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3021 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3022 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3023 MachinePointerInfo::getFixedStack(FI),
3024 false, false, false, 0);
3026 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3029 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3030 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3031 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3032 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3033 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3035 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3038 const TargetRegisterClass *RC;
3040 if (RegVT == MVT::f32)
3041 RC = &ARM::SPRRegClass;
3042 else if (RegVT == MVT::f64)
3043 RC = &ARM::DPRRegClass;
3044 else if (RegVT == MVT::v2f64)
3045 RC = &ARM::QPRRegClass;
3046 else if (RegVT == MVT::i32)
3047 RC = AFI->isThumb1OnlyFunction() ?
3048 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3049 (const TargetRegisterClass*)&ARM::GPRRegClass;
3051 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3053 // Transform the arguments in physical registers into virtual ones.
3054 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3055 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3058 // If this is an 8 or 16-bit value, it is really passed promoted
3059 // to 32 bits. Insert an assert[sz]ext to capture this, then
3060 // truncate to the right size.
3061 switch (VA.getLocInfo()) {
3062 default: llvm_unreachable("Unknown loc info!");
3063 case CCValAssign::Full: break;
3064 case CCValAssign::BCvt:
3065 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3067 case CCValAssign::SExt:
3068 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3069 DAG.getValueType(VA.getValVT()));
3070 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3072 case CCValAssign::ZExt:
3073 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3074 DAG.getValueType(VA.getValVT()));
3075 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3079 InVals.push_back(ArgValue);
3081 } else { // VA.isRegLoc()
3084 assert(VA.isMemLoc());
3085 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3087 int index = ArgLocs[i].getValNo();
3089 // Some Ins[] entries become multiple ArgLoc[] entries.
3090 // Process them only once.
3091 if (index != lastInsIndex)
3093 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3094 // FIXME: For now, all byval parameter objects are marked mutable.
3095 // This can be changed with more analysis.
3096 // In case of tail call optimization mark all arguments mutable.
3097 // Since they could be overwritten by lowering of arguments in case of
3099 if (Flags.isByVal()) {
3100 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3102 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3103 int FrameIndex = StoreByValRegs(
3104 CCInfo, DAG, dl, Chain, CurOrigArg,
3106 Ins[VA.getValNo()].PartOffset,
3107 VA.getLocMemOffset(),
3108 Flags.getByValSize(),
3109 true /*force mutable frames*/,
3111 TotalArgRegsSaveSize);
3112 ByValStoreOffset += Flags.getByValSize();
3113 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3114 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3115 CCInfo.nextInRegsParam();
3117 unsigned FIOffset = VA.getLocMemOffset();
3118 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3121 // Create load nodes to retrieve arguments from the stack.
3122 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3123 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3124 MachinePointerInfo::getFixedStack(FI),
3125 false, false, false, 0));
3127 lastInsIndex = index;
3134 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3135 CCInfo.getNextStackOffset(),
3136 TotalArgRegsSaveSize);
3138 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3143 /// isFloatingPointZero - Return true if this is +0.0.
3144 static bool isFloatingPointZero(SDValue Op) {
3145 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3146 return CFP->getValueAPF().isPosZero();
3147 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3148 // Maybe this has already been legalized into the constant pool?
3149 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3150 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3151 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3152 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3153 return CFP->getValueAPF().isPosZero();
3159 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3160 /// the given operands.
3162 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3163 SDValue &ARMcc, SelectionDAG &DAG,
3165 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3166 unsigned C = RHSC->getZExtValue();
3167 if (!isLegalICmpImmediate(C)) {
3168 // Constant does not fit, try adjusting it by one?
3173 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3174 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3175 RHS = DAG.getConstant(C-1, MVT::i32);
3180 if (C != 0 && isLegalICmpImmediate(C-1)) {
3181 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3182 RHS = DAG.getConstant(C-1, MVT::i32);
3187 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3188 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3189 RHS = DAG.getConstant(C+1, MVT::i32);
3194 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3195 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3196 RHS = DAG.getConstant(C+1, MVT::i32);
3203 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3204 ARMISD::NodeType CompareType;
3207 CompareType = ARMISD::CMP;
3212 CompareType = ARMISD::CMPZ;
3215 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3216 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3219 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3221 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3224 if (!isFloatingPointZero(RHS))
3225 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3227 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3228 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3231 /// duplicateCmp - Glue values can have only one use, so this function
3232 /// duplicates a comparison node.
3234 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3235 unsigned Opc = Cmp.getOpcode();
3237 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3238 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3240 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3241 Cmp = Cmp.getOperand(0);
3242 Opc = Cmp.getOpcode();
3243 if (Opc == ARMISD::CMPFP)
3244 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3246 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3247 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3249 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3252 std::pair<SDValue, SDValue>
3253 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3254 SDValue &ARMcc) const {
3255 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3257 SDValue Value, OverflowCmp;
3258 SDValue LHS = Op.getOperand(0);
3259 SDValue RHS = Op.getOperand(1);
3262 // FIXME: We are currently always generating CMPs because we don't support
3263 // generating CMN through the backend. This is not as good as the natural
3264 // CMP case because it causes a register dependency and cannot be folded
3267 switch (Op.getOpcode()) {
3269 llvm_unreachable("Unknown overflow instruction!");
3271 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3272 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3273 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3276 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3277 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3278 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3281 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3282 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3283 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3286 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3287 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3288 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3292 return std::make_pair(Value, OverflowCmp);
3297 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3298 // Let legalize expand this if it isn't a legal type yet.
3299 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3302 SDValue Value, OverflowCmp;
3304 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3305 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3306 // We use 0 and 1 as false and true values.
3307 SDValue TVal = DAG.getConstant(1, MVT::i32);
3308 SDValue FVal = DAG.getConstant(0, MVT::i32);
3309 EVT VT = Op.getValueType();
3311 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3312 ARMcc, CCR, OverflowCmp);
3314 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3315 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3319 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3320 SDValue Cond = Op.getOperand(0);
3321 SDValue SelectTrue = Op.getOperand(1);
3322 SDValue SelectFalse = Op.getOperand(2);
3324 unsigned Opc = Cond.getOpcode();
3326 if (Cond.getResNo() == 1 &&
3327 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3328 Opc == ISD::USUBO)) {
3329 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3332 SDValue Value, OverflowCmp;
3334 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3335 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3336 EVT VT = Op.getValueType();
3338 return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3339 ARMcc, CCR, OverflowCmp);
3345 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3346 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3348 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3349 const ConstantSDNode *CMOVTrue =
3350 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3351 const ConstantSDNode *CMOVFalse =
3352 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3354 if (CMOVTrue && CMOVFalse) {
3355 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3356 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3360 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3362 False = SelectFalse;
3363 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3368 if (True.getNode() && False.getNode()) {
3369 EVT VT = Op.getValueType();
3370 SDValue ARMcc = Cond.getOperand(2);
3371 SDValue CCR = Cond.getOperand(3);
3372 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3373 assert(True.getValueType() == VT);
3374 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3379 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3380 // undefined bits before doing a full-word comparison with zero.
3381 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3382 DAG.getConstant(1, Cond.getValueType()));
3384 return DAG.getSelectCC(dl, Cond,
3385 DAG.getConstant(0, Cond.getValueType()),
3386 SelectTrue, SelectFalse, ISD::SETNE);
3389 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3390 if (CC == ISD::SETNE)
3392 return ISD::getSetCCInverse(CC, true);
3395 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3396 bool &swpCmpOps, bool &swpVselOps) {
3397 // Start by selecting the GE condition code for opcodes that return true for
3399 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3401 CondCode = ARMCC::GE;
3403 // and GT for opcodes that return false for 'equality'.
3404 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3406 CondCode = ARMCC::GT;
3408 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3409 // to swap the compare operands.
3410 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3414 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3415 // If we have an unordered opcode, we need to swap the operands to the VSEL
3416 // instruction (effectively negating the condition).
3418 // This also has the effect of swapping which one of 'less' or 'greater'
3419 // returns true, so we also swap the compare operands. It also switches
3420 // whether we return true for 'equality', so we compensate by picking the
3421 // opposite condition code to our original choice.
3422 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3423 CC == ISD::SETUGT) {
3424 swpCmpOps = !swpCmpOps;
3425 swpVselOps = !swpVselOps;
3426 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3429 // 'ordered' is 'anything but unordered', so use the VS condition code and
3430 // swap the VSEL operands.
3431 if (CC == ISD::SETO) {
3432 CondCode = ARMCC::VS;
3436 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3437 // code and swap the VSEL operands.
3438 if (CC == ISD::SETUNE) {
3439 CondCode = ARMCC::EQ;
3444 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3445 EVT VT = Op.getValueType();
3446 SDValue LHS = Op.getOperand(0);
3447 SDValue RHS = Op.getOperand(1);
3448 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3449 SDValue TrueVal = Op.getOperand(2);
3450 SDValue FalseVal = Op.getOperand(3);
3453 if (LHS.getValueType() == MVT::i32) {
3454 // Try to generate VSEL on ARMv8.
3455 // The VSEL instruction can't use all the usual ARM condition
3456 // codes: it only has two bits to select the condition code, so it's
3457 // constrained to use only GE, GT, VS and EQ.
3459 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3460 // swap the operands of the previous compare instruction (effectively
3461 // inverting the compare condition, swapping 'less' and 'greater') and
3462 // sometimes need to swap the operands to the VSEL (which inverts the
3463 // condition in the sense of firing whenever the previous condition didn't)
3464 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3465 TrueVal.getValueType() == MVT::f64)) {
3466 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3467 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3468 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3469 CC = getInverseCCForVSEL(CC);
3470 std::swap(TrueVal, FalseVal);
3475 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3476 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3477 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3481 ARMCC::CondCodes CondCode, CondCode2;
3482 FPCCToARMCC(CC, CondCode, CondCode2);
3484 // Try to generate VSEL on ARMv8.
3485 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3486 TrueVal.getValueType() == MVT::f64)) {
3487 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3488 // same operands, as follows:
3489 // c = fcmp [ogt, olt, ugt, ult] a, b
3491 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3492 // handled differently than the original code sequence.
3493 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3495 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3496 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3497 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3498 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3501 bool swpCmpOps = false;
3502 bool swpVselOps = false;
3503 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3505 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3506 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3508 std::swap(LHS, RHS);
3510 std::swap(TrueVal, FalseVal);
3514 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3515 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3516 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3517 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3519 if (CondCode2 != ARMCC::AL) {
3520 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3521 // FIXME: Needs another CMP because flag can have but one use.
3522 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3523 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3524 Result, TrueVal, ARMcc2, CCR, Cmp2);
3529 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3530 /// to morph to an integer compare sequence.
3531 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3532 const ARMSubtarget *Subtarget) {
3533 SDNode *N = Op.getNode();
3534 if (!N->hasOneUse())
3535 // Otherwise it requires moving the value from fp to integer registers.
3537 if (!N->getNumValues())
3539 EVT VT = Op.getValueType();
3540 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3541 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3542 // vmrs are very slow, e.g. cortex-a8.
3545 if (isFloatingPointZero(Op)) {
3549 return ISD::isNormalLoad(N);
3552 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3553 if (isFloatingPointZero(Op))
3554 return DAG.getConstant(0, MVT::i32);
3556 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3557 return DAG.getLoad(MVT::i32, SDLoc(Op),
3558 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3559 Ld->isVolatile(), Ld->isNonTemporal(),
3560 Ld->isInvariant(), Ld->getAlignment());
3562 llvm_unreachable("Unknown VFP cmp argument!");
3565 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3566 SDValue &RetVal1, SDValue &RetVal2) {
3567 if (isFloatingPointZero(Op)) {
3568 RetVal1 = DAG.getConstant(0, MVT::i32);
3569 RetVal2 = DAG.getConstant(0, MVT::i32);
3573 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3574 SDValue Ptr = Ld->getBasePtr();
3575 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3576 Ld->getChain(), Ptr,
3577 Ld->getPointerInfo(),
3578 Ld->isVolatile(), Ld->isNonTemporal(),
3579 Ld->isInvariant(), Ld->getAlignment());
3581 EVT PtrType = Ptr.getValueType();
3582 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3583 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3584 PtrType, Ptr, DAG.getConstant(4, PtrType));
3585 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3586 Ld->getChain(), NewPtr,
3587 Ld->getPointerInfo().getWithOffset(4),
3588 Ld->isVolatile(), Ld->isNonTemporal(),
3589 Ld->isInvariant(), NewAlign);
3593 llvm_unreachable("Unknown VFP cmp argument!");
3596 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3597 /// f32 and even f64 comparisons to integer ones.
3599 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3600 SDValue Chain = Op.getOperand(0);
3601 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3602 SDValue LHS = Op.getOperand(2);
3603 SDValue RHS = Op.getOperand(3);
3604 SDValue Dest = Op.getOperand(4);
3607 bool LHSSeenZero = false;
3608 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3609 bool RHSSeenZero = false;
3610 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3611 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3612 // If unsafe fp math optimization is enabled and there are no other uses of
3613 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3614 // to an integer comparison.
3615 if (CC == ISD::SETOEQ)
3617 else if (CC == ISD::SETUNE)
3620 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3622 if (LHS.getValueType() == MVT::f32) {
3623 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3624 bitcastf32Toi32(LHS, DAG), Mask);
3625 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3626 bitcastf32Toi32(RHS, DAG), Mask);
3627 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3628 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3629 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3630 Chain, Dest, ARMcc, CCR, Cmp);
3635 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3636 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3637 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3638 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3639 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3640 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3641 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3642 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3643 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3649 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3650 SDValue Chain = Op.getOperand(0);
3651 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3652 SDValue LHS = Op.getOperand(2);
3653 SDValue RHS = Op.getOperand(3);
3654 SDValue Dest = Op.getOperand(4);
3657 if (LHS.getValueType() == MVT::i32) {
3659 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3660 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3661 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3662 Chain, Dest, ARMcc, CCR, Cmp);
3665 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3667 if (getTargetMachine().Options.UnsafeFPMath &&
3668 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3669 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3670 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3671 if (Result.getNode())
3675 ARMCC::CondCodes CondCode, CondCode2;
3676 FPCCToARMCC(CC, CondCode, CondCode2);
3678 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3679 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3680 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3681 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3682 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3683 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3684 if (CondCode2 != ARMCC::AL) {
3685 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3686 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3687 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3692 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3693 SDValue Chain = Op.getOperand(0);
3694 SDValue Table = Op.getOperand(1);
3695 SDValue Index = Op.getOperand(2);
3698 EVT PTy = getPointerTy();
3699 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3700 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3701 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3702 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3703 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3704 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3705 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3706 if (Subtarget->isThumb2()) {
3707 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3708 // which does another jump to the destination. This also makes it easier
3709 // to translate it to TBB / TBH later.
3710 // FIXME: This might not work if the function is extremely large.
3711 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3712 Addr, Op.getOperand(2), JTI, UId);
3714 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3715 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3716 MachinePointerInfo::getJumpTable(),
3717 false, false, false, 0);
3718 Chain = Addr.getValue(1);
3719 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3720 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3722 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3723 MachinePointerInfo::getJumpTable(),
3724 false, false, false, 0);
3725 Chain = Addr.getValue(1);
3726 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3730 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3731 EVT VT = Op.getValueType();
3734 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3735 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3737 return DAG.UnrollVectorOp(Op.getNode());
3740 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3741 "Invalid type for custom lowering!");
3742 if (VT != MVT::v4i16)
3743 return DAG.UnrollVectorOp(Op.getNode());
3745 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3746 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3749 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3750 EVT VT = Op.getValueType();
3752 return LowerVectorFP_TO_INT(Op, DAG);
3757 switch (Op.getOpcode()) {
3758 default: llvm_unreachable("Invalid opcode!");
3759 case ISD::FP_TO_SINT:
3760 Opc = ARMISD::FTOSI;
3762 case ISD::FP_TO_UINT:
3763 Opc = ARMISD::FTOUI;
3766 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3767 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3770 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3771 EVT VT = Op.getValueType();
3774 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3775 if (VT.getVectorElementType() == MVT::f32)
3777 return DAG.UnrollVectorOp(Op.getNode());
3780 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3781 "Invalid type for custom lowering!");
3782 if (VT != MVT::v4f32)
3783 return DAG.UnrollVectorOp(Op.getNode());
3787 switch (Op.getOpcode()) {
3788 default: llvm_unreachable("Invalid opcode!");
3789 case ISD::SINT_TO_FP:
3790 CastOpc = ISD::SIGN_EXTEND;
3791 Opc = ISD::SINT_TO_FP;
3793 case ISD::UINT_TO_FP:
3794 CastOpc = ISD::ZERO_EXTEND;
3795 Opc = ISD::UINT_TO_FP;
3799 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3800 return DAG.getNode(Opc, dl, VT, Op);
3803 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3804 EVT VT = Op.getValueType();
3806 return LowerVectorINT_TO_FP(Op, DAG);
3811 switch (Op.getOpcode()) {
3812 default: llvm_unreachable("Invalid opcode!");
3813 case ISD::SINT_TO_FP:
3814 Opc = ARMISD::SITOF;
3816 case ISD::UINT_TO_FP:
3817 Opc = ARMISD::UITOF;
3821 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3822 return DAG.getNode(Opc, dl, VT, Op);
3825 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3826 // Implement fcopysign with a fabs and a conditional fneg.
3827 SDValue Tmp0 = Op.getOperand(0);
3828 SDValue Tmp1 = Op.getOperand(1);
3830 EVT VT = Op.getValueType();
3831 EVT SrcVT = Tmp1.getValueType();
3832 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3833 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3834 bool UseNEON = !InGPR && Subtarget->hasNEON();
3837 // Use VBSL to copy the sign bit.
3838 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3839 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3840 DAG.getTargetConstant(EncodedVal, MVT::i32));
3841 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3843 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3844 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3845 DAG.getConstant(32, MVT::i32));
3846 else /*if (VT == MVT::f32)*/
3847 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3848 if (SrcVT == MVT::f32) {
3849 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3851 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3852 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3853 DAG.getConstant(32, MVT::i32));
3854 } else if (VT == MVT::f32)
3855 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3856 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3857 DAG.getConstant(32, MVT::i32));
3858 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3859 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3861 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3863 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3864 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3865 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3867 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3868 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3869 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3870 if (VT == MVT::f32) {
3871 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3872 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3873 DAG.getConstant(0, MVT::i32));
3875 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3881 // Bitcast operand 1 to i32.
3882 if (SrcVT == MVT::f64)
3883 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3885 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3887 // Or in the signbit with integer operations.
3888 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3889 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3890 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3891 if (VT == MVT::f32) {
3892 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3893 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3894 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3895 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3898 // f64: Or the high part with signbit and then combine two parts.
3899 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3901 SDValue Lo = Tmp0.getValue(0);
3902 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3903 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3904 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3907 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3908 MachineFunction &MF = DAG.getMachineFunction();
3909 MachineFrameInfo *MFI = MF.getFrameInfo();
3910 MFI->setReturnAddressIsTaken(true);
3912 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3915 EVT VT = Op.getValueType();
3917 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3919 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3920 SDValue Offset = DAG.getConstant(4, MVT::i32);
3921 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3922 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3923 MachinePointerInfo(), false, false, false, 0);
3926 // Return LR, which contains the return address. Mark it an implicit live-in.
3927 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3928 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3931 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3932 const ARMBaseRegisterInfo &ARI =
3933 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3934 MachineFunction &MF = DAG.getMachineFunction();
3935 MachineFrameInfo *MFI = MF.getFrameInfo();
3936 MFI->setFrameAddressIsTaken(true);
3938 EVT VT = Op.getValueType();
3939 SDLoc dl(Op); // FIXME probably not meaningful
3940 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3941 unsigned FrameReg = ARI.getFrameRegister(MF);
3942 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3944 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3945 MachinePointerInfo(),
3946 false, false, false, 0);
3950 // FIXME? Maybe this could be a TableGen attribute on some registers and
3951 // this table could be generated automatically from RegInfo.
3952 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3954 unsigned Reg = StringSwitch<unsigned>(RegName)
3955 .Case("sp", ARM::SP)
3959 report_fatal_error("Invalid register name global variable");
3962 /// ExpandBITCAST - If the target supports VFP, this function is called to
3963 /// expand a bit convert where either the source or destination type is i64 to
3964 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3965 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3966 /// vectors), since the legalizer won't know what to do with that.
3967 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3968 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3970 SDValue Op = N->getOperand(0);
3972 // This function is only supposed to be called for i64 types, either as the
3973 // source or destination of the bit convert.
3974 EVT SrcVT = Op.getValueType();
3975 EVT DstVT = N->getValueType(0);
3976 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3977 "ExpandBITCAST called for non-i64 type");
3979 // Turn i64->f64 into VMOVDRR.
3980 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3981 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3982 DAG.getConstant(0, MVT::i32));
3983 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3984 DAG.getConstant(1, MVT::i32));
3985 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3986 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3989 // Turn f64->i64 into VMOVRRD.
3990 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3992 if (TLI.isBigEndian() && SrcVT.isVector() &&
3993 SrcVT.getVectorNumElements() > 1)
3994 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3995 DAG.getVTList(MVT::i32, MVT::i32),
3996 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3998 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3999 DAG.getVTList(MVT::i32, MVT::i32), Op);
4000 // Merge the pieces into a single i64 value.
4001 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4007 /// getZeroVector - Returns a vector of specified type with all zero elements.
4008 /// Zero vectors are used to represent vector negation and in those cases
4009 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4010 /// not support i64 elements, so sometimes the zero vectors will need to be
4011 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4013 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4014 assert(VT.isVector() && "Expected a vector type");
4015 // The canonical modified immediate encoding of a zero vector is....0!
4016 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4017 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4018 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4019 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4022 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4023 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4024 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4025 SelectionDAG &DAG) const {
4026 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4027 EVT VT = Op.getValueType();
4028 unsigned VTBits = VT.getSizeInBits();
4030 SDValue ShOpLo = Op.getOperand(0);
4031 SDValue ShOpHi = Op.getOperand(1);
4032 SDValue ShAmt = Op.getOperand(2);
4034 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4036 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4038 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4039 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4040 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4041 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4042 DAG.getConstant(VTBits, MVT::i32));
4043 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4044 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4045 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4047 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4048 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4050 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4051 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4054 SDValue Ops[2] = { Lo, Hi };
4055 return DAG.getMergeValues(Ops, dl);
4058 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4059 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4060 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4061 SelectionDAG &DAG) const {
4062 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4063 EVT VT = Op.getValueType();
4064 unsigned VTBits = VT.getSizeInBits();
4066 SDValue ShOpLo = Op.getOperand(0);
4067 SDValue ShOpHi = Op.getOperand(1);
4068 SDValue ShAmt = Op.getOperand(2);
4071 assert(Op.getOpcode() == ISD::SHL_PARTS);
4072 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4073 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4074 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4075 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4076 DAG.getConstant(VTBits, MVT::i32));
4077 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4078 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4080 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4081 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4082 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4084 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4085 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4088 SDValue Ops[2] = { Lo, Hi };
4089 return DAG.getMergeValues(Ops, dl);
4092 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4093 SelectionDAG &DAG) const {
4094 // The rounding mode is in bits 23:22 of the FPSCR.
4095 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4096 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4097 // so that the shift + and get folded into a bitfield extract.
4099 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4100 DAG.getConstant(Intrinsic::arm_get_fpscr,
4102 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4103 DAG.getConstant(1U << 22, MVT::i32));
4104 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4105 DAG.getConstant(22, MVT::i32));
4106 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4107 DAG.getConstant(3, MVT::i32));
4110 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4111 const ARMSubtarget *ST) {
4112 EVT VT = N->getValueType(0);
4115 if (!ST->hasV6T2Ops())
4118 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4119 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4122 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4123 /// for each 16-bit element from operand, repeated. The basic idea is to
4124 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4126 /// Trace for v4i16:
4127 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4128 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4129 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4130 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4131 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4132 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4133 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4134 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4135 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4136 EVT VT = N->getValueType(0);
4139 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4140 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4141 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4142 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4143 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4144 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4147 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4148 /// bit-count for each 16-bit element from the operand. We need slightly
4149 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4150 /// 64/128-bit registers.
4152 /// Trace for v4i16:
4153 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4154 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4155 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4156 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4157 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4158 EVT VT = N->getValueType(0);
4161 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4162 if (VT.is64BitVector()) {
4163 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4164 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4165 DAG.getIntPtrConstant(0));
4167 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4168 BitCounts, DAG.getIntPtrConstant(0));
4169 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4173 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4174 /// bit-count for each 32-bit element from the operand. The idea here is
4175 /// to split the vector into 16-bit elements, leverage the 16-bit count
4176 /// routine, and then combine the results.
4178 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4179 /// input = [v0 v1 ] (vi: 32-bit elements)
4180 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4181 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4182 /// vrev: N0 = [k1 k0 k3 k2 ]
4184 /// N1 =+[k1 k0 k3 k2 ]
4186 /// N2 =+[k1 k3 k0 k2 ]
4188 /// Extended =+[k1 k3 k0 k2 ]
4190 /// Extracted=+[k1 k3 ]
4192 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4193 EVT VT = N->getValueType(0);
4196 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4198 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4199 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4200 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4201 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4202 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4204 if (VT.is64BitVector()) {
4205 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4206 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4207 DAG.getIntPtrConstant(0));
4209 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4210 DAG.getIntPtrConstant(0));
4211 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4215 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4216 const ARMSubtarget *ST) {
4217 EVT VT = N->getValueType(0);
4219 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4220 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4221 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4222 "Unexpected type for custom ctpop lowering");
4224 if (VT.getVectorElementType() == MVT::i32)
4225 return lowerCTPOP32BitElements(N, DAG);
4227 return lowerCTPOP16BitElements(N, DAG);
4230 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4231 const ARMSubtarget *ST) {
4232 EVT VT = N->getValueType(0);
4238 // Lower vector shifts on NEON to use VSHL.
4239 assert(ST->hasNEON() && "unexpected vector shift");
4241 // Left shifts translate directly to the vshiftu intrinsic.
4242 if (N->getOpcode() == ISD::SHL)
4243 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4244 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4245 N->getOperand(0), N->getOperand(1));
4247 assert((N->getOpcode() == ISD::SRA ||
4248 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4250 // NEON uses the same intrinsics for both left and right shifts. For
4251 // right shifts, the shift amounts are negative, so negate the vector of
4253 EVT ShiftVT = N->getOperand(1).getValueType();
4254 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4255 getZeroVector(ShiftVT, DAG, dl),
4257 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4258 Intrinsic::arm_neon_vshifts :
4259 Intrinsic::arm_neon_vshiftu);
4260 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4261 DAG.getConstant(vshiftInt, MVT::i32),
4262 N->getOperand(0), NegatedCount);
4265 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4266 const ARMSubtarget *ST) {
4267 EVT VT = N->getValueType(0);
4270 // We can get here for a node like i32 = ISD::SHL i32, i64
4274 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4275 "Unknown shift to lower!");
4277 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4278 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4279 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4282 // If we are in thumb mode, we don't have RRX.
4283 if (ST->isThumb1Only()) return SDValue();
4285 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4286 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4287 DAG.getConstant(0, MVT::i32));
4288 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4289 DAG.getConstant(1, MVT::i32));
4291 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4292 // captures the result into a carry flag.
4293 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4294 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4296 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4297 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4299 // Merge the pieces into a single i64 value.
4300 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4303 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4304 SDValue TmpOp0, TmpOp1;
4305 bool Invert = false;
4309 SDValue Op0 = Op.getOperand(0);
4310 SDValue Op1 = Op.getOperand(1);
4311 SDValue CC = Op.getOperand(2);
4312 EVT VT = Op.getValueType();
4313 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4316 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4317 switch (SetCCOpcode) {
4318 default: llvm_unreachable("Illegal FP comparison");
4320 case ISD::SETNE: Invert = true; // Fallthrough
4322 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4324 case ISD::SETLT: Swap = true; // Fallthrough
4326 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4328 case ISD::SETLE: Swap = true; // Fallthrough
4330 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4331 case ISD::SETUGE: Swap = true; // Fallthrough
4332 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4333 case ISD::SETUGT: Swap = true; // Fallthrough
4334 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4335 case ISD::SETUEQ: Invert = true; // Fallthrough
4337 // Expand this to (OLT | OGT).
4341 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4342 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4344 case ISD::SETUO: Invert = true; // Fallthrough
4346 // Expand this to (OLT | OGE).
4350 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4351 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4355 // Integer comparisons.
4356 switch (SetCCOpcode) {
4357 default: llvm_unreachable("Illegal integer comparison");
4358 case ISD::SETNE: Invert = true;
4359 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4360 case ISD::SETLT: Swap = true;
4361 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4362 case ISD::SETLE: Swap = true;
4363 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4364 case ISD::SETULT: Swap = true;
4365 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4366 case ISD::SETULE: Swap = true;
4367 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4370 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4371 if (Opc == ARMISD::VCEQ) {
4374 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4376 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4379 // Ignore bitconvert.
4380 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4381 AndOp = AndOp.getOperand(0);
4383 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4385 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4386 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4393 std::swap(Op0, Op1);
4395 // If one of the operands is a constant vector zero, attempt to fold the
4396 // comparison to a specialized compare-against-zero form.
4398 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4400 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4401 if (Opc == ARMISD::VCGE)
4402 Opc = ARMISD::VCLEZ;
4403 else if (Opc == ARMISD::VCGT)
4404 Opc = ARMISD::VCLTZ;
4409 if (SingleOp.getNode()) {
4412 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4414 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4416 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4418 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4420 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4422 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4425 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4429 Result = DAG.getNOT(dl, Result, VT);
4434 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4435 /// valid vector constant for a NEON instruction with a "modified immediate"
4436 /// operand (e.g., VMOV). If so, return the encoded value.
4437 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4438 unsigned SplatBitSize, SelectionDAG &DAG,
4439 EVT &VT, bool is128Bits, NEONModImmType type) {
4440 unsigned OpCmode, Imm;
4442 // SplatBitSize is set to the smallest size that splats the vector, so a
4443 // zero vector will always have SplatBitSize == 8. However, NEON modified
4444 // immediate instructions others than VMOV do not support the 8-bit encoding
4445 // of a zero vector, and the default encoding of zero is supposed to be the
4450 switch (SplatBitSize) {
4452 if (type != VMOVModImm)
4454 // Any 1-byte value is OK. Op=0, Cmode=1110.
4455 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4458 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4462 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4463 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4464 if ((SplatBits & ~0xff) == 0) {
4465 // Value = 0x00nn: Op=x, Cmode=100x.
4470 if ((SplatBits & ~0xff00) == 0) {
4471 // Value = 0xnn00: Op=x, Cmode=101x.
4473 Imm = SplatBits >> 8;
4479 // NEON's 32-bit VMOV supports splat values where:
4480 // * only one byte is nonzero, or
4481 // * the least significant byte is 0xff and the second byte is nonzero, or
4482 // * the least significant 2 bytes are 0xff and the third is nonzero.
4483 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4484 if ((SplatBits & ~0xff) == 0) {
4485 // Value = 0x000000nn: Op=x, Cmode=000x.
4490 if ((SplatBits & ~0xff00) == 0) {
4491 // Value = 0x0000nn00: Op=x, Cmode=001x.
4493 Imm = SplatBits >> 8;
4496 if ((SplatBits & ~0xff0000) == 0) {
4497 // Value = 0x00nn0000: Op=x, Cmode=010x.
4499 Imm = SplatBits >> 16;
4502 if ((SplatBits & ~0xff000000) == 0) {
4503 // Value = 0xnn000000: Op=x, Cmode=011x.
4505 Imm = SplatBits >> 24;
4509 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4510 if (type == OtherModImm) return SDValue();
4512 if ((SplatBits & ~0xffff) == 0 &&
4513 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4514 // Value = 0x0000nnff: Op=x, Cmode=1100.
4516 Imm = SplatBits >> 8;
4520 if ((SplatBits & ~0xffffff) == 0 &&
4521 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4522 // Value = 0x00nnffff: Op=x, Cmode=1101.
4524 Imm = SplatBits >> 16;
4528 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4529 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4530 // VMOV.I32. A (very) minor optimization would be to replicate the value
4531 // and fall through here to test for a valid 64-bit splat. But, then the
4532 // caller would also need to check and handle the change in size.
4536 if (type != VMOVModImm)
4538 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4539 uint64_t BitMask = 0xff;
4541 unsigned ImmMask = 1;
4543 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4544 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4547 } else if ((SplatBits & BitMask) != 0) {
4554 if (DAG.getTargetLoweringInfo().isBigEndian())
4555 // swap higher and lower 32 bit word
4556 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4558 // Op=1, Cmode=1110.
4560 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4565 llvm_unreachable("unexpected size for isNEONModifiedImm");
4568 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4569 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4572 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4573 const ARMSubtarget *ST) const {
4577 bool IsDouble = Op.getValueType() == MVT::f64;
4578 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4580 // Try splatting with a VMOV.f32...
4581 APFloat FPVal = CFP->getValueAPF();
4582 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4585 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4586 // We have code in place to select a valid ConstantFP already, no need to
4591 // It's a float and we are trying to use NEON operations where
4592 // possible. Lower it to a splat followed by an extract.
4594 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4595 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4597 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4598 DAG.getConstant(0, MVT::i32));
4601 // The rest of our options are NEON only, make sure that's allowed before
4603 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4607 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4609 // It wouldn't really be worth bothering for doubles except for one very
4610 // important value, which does happen to match: 0.0. So make sure we don't do
4612 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4615 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4616 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4618 if (NewVal != SDValue()) {
4620 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4623 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4625 // It's a float: cast and extract a vector element.
4626 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4628 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4629 DAG.getConstant(0, MVT::i32));
4632 // Finally, try a VMVN.i32
4633 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4635 if (NewVal != SDValue()) {
4637 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4640 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4642 // It's a float: cast and extract a vector element.
4643 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4645 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4646 DAG.getConstant(0, MVT::i32));
4652 // check if an VEXT instruction can handle the shuffle mask when the
4653 // vector sources of the shuffle are the same.
4654 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4655 unsigned NumElts = VT.getVectorNumElements();
4657 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4663 // If this is a VEXT shuffle, the immediate value is the index of the first
4664 // element. The other shuffle indices must be the successive elements after
4666 unsigned ExpectedElt = Imm;
4667 for (unsigned i = 1; i < NumElts; ++i) {
4668 // Increment the expected index. If it wraps around, just follow it
4669 // back to index zero and keep going.
4671 if (ExpectedElt == NumElts)
4674 if (M[i] < 0) continue; // ignore UNDEF indices
4675 if (ExpectedElt != static_cast<unsigned>(M[i]))
4683 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4684 bool &ReverseVEXT, unsigned &Imm) {
4685 unsigned NumElts = VT.getVectorNumElements();
4686 ReverseVEXT = false;
4688 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4694 // If this is a VEXT shuffle, the immediate value is the index of the first
4695 // element. The other shuffle indices must be the successive elements after
4697 unsigned ExpectedElt = Imm;
4698 for (unsigned i = 1; i < NumElts; ++i) {
4699 // Increment the expected index. If it wraps around, it may still be
4700 // a VEXT but the source vectors must be swapped.
4702 if (ExpectedElt == NumElts * 2) {
4707 if (M[i] < 0) continue; // ignore UNDEF indices
4708 if (ExpectedElt != static_cast<unsigned>(M[i]))
4712 // Adjust the index value if the source operands will be swapped.
4719 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4720 /// instruction with the specified blocksize. (The order of the elements
4721 /// within each block of the vector is reversed.)
4722 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4723 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4724 "Only possible block sizes for VREV are: 16, 32, 64");
4726 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4730 unsigned NumElts = VT.getVectorNumElements();
4731 unsigned BlockElts = M[0] + 1;
4732 // If the first shuffle index is UNDEF, be optimistic.
4734 BlockElts = BlockSize / EltSz;
4736 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4739 for (unsigned i = 0; i < NumElts; ++i) {
4740 if (M[i] < 0) continue; // ignore UNDEF indices
4741 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4748 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4749 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4750 // range, then 0 is placed into the resulting vector. So pretty much any mask
4751 // of 8 elements can work here.
4752 return VT == MVT::v8i8 && M.size() == 8;
4755 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4756 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4760 unsigned NumElts = VT.getVectorNumElements();
4761 WhichResult = (M[0] == 0 ? 0 : 1);
4762 for (unsigned i = 0; i < NumElts; i += 2) {
4763 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4764 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4770 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4771 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4772 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4773 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4774 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4778 unsigned NumElts = VT.getVectorNumElements();
4779 WhichResult = (M[0] == 0 ? 0 : 1);
4780 for (unsigned i = 0; i < NumElts; i += 2) {
4781 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4782 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4788 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4789 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4793 unsigned NumElts = VT.getVectorNumElements();
4794 WhichResult = (M[0] == 0 ? 0 : 1);
4795 for (unsigned i = 0; i != NumElts; ++i) {
4796 if (M[i] < 0) continue; // ignore UNDEF indices
4797 if ((unsigned) M[i] != 2 * i + WhichResult)
4801 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4802 if (VT.is64BitVector() && EltSz == 32)
4808 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4809 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4810 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4811 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4812 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4816 unsigned Half = VT.getVectorNumElements() / 2;
4817 WhichResult = (M[0] == 0 ? 0 : 1);
4818 for (unsigned j = 0; j != 2; ++j) {
4819 unsigned Idx = WhichResult;
4820 for (unsigned i = 0; i != Half; ++i) {
4821 int MIdx = M[i + j * Half];
4822 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4828 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4829 if (VT.is64BitVector() && EltSz == 32)
4835 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4836 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4840 unsigned NumElts = VT.getVectorNumElements();
4841 WhichResult = (M[0] == 0 ? 0 : 1);
4842 unsigned Idx = WhichResult * NumElts / 2;
4843 for (unsigned i = 0; i != NumElts; i += 2) {
4844 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4845 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4850 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4851 if (VT.is64BitVector() && EltSz == 32)
4857 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4858 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4859 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4860 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4861 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4865 unsigned NumElts = VT.getVectorNumElements();
4866 WhichResult = (M[0] == 0 ? 0 : 1);
4867 unsigned Idx = WhichResult * NumElts / 2;
4868 for (unsigned i = 0; i != NumElts; i += 2) {
4869 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4870 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4875 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4876 if (VT.is64BitVector() && EltSz == 32)
4882 /// \return true if this is a reverse operation on an vector.
4883 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4884 unsigned NumElts = VT.getVectorNumElements();
4885 // Make sure the mask has the right size.
4886 if (NumElts != M.size())
4889 // Look for <15, ..., 3, -1, 1, 0>.
4890 for (unsigned i = 0; i != NumElts; ++i)
4891 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4897 // If N is an integer constant that can be moved into a register in one
4898 // instruction, return an SDValue of such a constant (will become a MOV
4899 // instruction). Otherwise return null.
4900 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4901 const ARMSubtarget *ST, SDLoc dl) {
4903 if (!isa<ConstantSDNode>(N))
4905 Val = cast<ConstantSDNode>(N)->getZExtValue();
4907 if (ST->isThumb1Only()) {
4908 if (Val <= 255 || ~Val <= 255)
4909 return DAG.getConstant(Val, MVT::i32);
4911 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4912 return DAG.getConstant(Val, MVT::i32);
4917 // If this is a case we can't handle, return null and let the default
4918 // expansion code take care of it.
4919 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4920 const ARMSubtarget *ST) const {
4921 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4923 EVT VT = Op.getValueType();
4925 APInt SplatBits, SplatUndef;
4926 unsigned SplatBitSize;
4928 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4929 if (SplatBitSize <= 64) {
4930 // Check if an immediate VMOV works.
4932 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4933 SplatUndef.getZExtValue(), SplatBitSize,
4934 DAG, VmovVT, VT.is128BitVector(),
4936 if (Val.getNode()) {
4937 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4938 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4941 // Try an immediate VMVN.
4942 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4943 Val = isNEONModifiedImm(NegatedImm,
4944 SplatUndef.getZExtValue(), SplatBitSize,
4945 DAG, VmovVT, VT.is128BitVector(),
4947 if (Val.getNode()) {
4948 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4949 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4952 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4953 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4954 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4956 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4957 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4963 // Scan through the operands to see if only one value is used.
4965 // As an optimisation, even if more than one value is used it may be more
4966 // profitable to splat with one value then change some lanes.
4968 // Heuristically we decide to do this if the vector has a "dominant" value,
4969 // defined as splatted to more than half of the lanes.
4970 unsigned NumElts = VT.getVectorNumElements();
4971 bool isOnlyLowElement = true;
4972 bool usesOnlyOneValue = true;
4973 bool hasDominantValue = false;
4974 bool isConstant = true;
4976 // Map of the number of times a particular SDValue appears in the
4978 DenseMap<SDValue, unsigned> ValueCounts;
4980 for (unsigned i = 0; i < NumElts; ++i) {
4981 SDValue V = Op.getOperand(i);
4982 if (V.getOpcode() == ISD::UNDEF)
4985 isOnlyLowElement = false;
4986 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4989 ValueCounts.insert(std::make_pair(V, 0));
4990 unsigned &Count = ValueCounts[V];
4992 // Is this value dominant? (takes up more than half of the lanes)
4993 if (++Count > (NumElts / 2)) {
4994 hasDominantValue = true;
4998 if (ValueCounts.size() != 1)
4999 usesOnlyOneValue = false;
5000 if (!Value.getNode() && ValueCounts.size() > 0)
5001 Value = ValueCounts.begin()->first;
5003 if (ValueCounts.size() == 0)
5004 return DAG.getUNDEF(VT);
5006 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5007 // Keep going if we are hitting this case.
5008 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5009 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5011 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5013 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5014 // i32 and try again.
5015 if (hasDominantValue && EltSize <= 32) {
5019 // If we are VDUPing a value that comes directly from a vector, that will
5020 // cause an unnecessary move to and from a GPR, where instead we could
5021 // just use VDUPLANE. We can only do this if the lane being extracted
5022 // is at a constant index, as the VDUP from lane instructions only have
5023 // constant-index forms.
5024 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5025 isa<ConstantSDNode>(Value->getOperand(1))) {
5026 // We need to create a new undef vector to use for the VDUPLANE if the
5027 // size of the vector from which we get the value is different than the
5028 // size of the vector that we need to create. We will insert the element
5029 // such that the register coalescer will remove unnecessary copies.
5030 if (VT != Value->getOperand(0).getValueType()) {
5031 ConstantSDNode *constIndex;
5032 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5033 assert(constIndex && "The index is not a constant!");
5034 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5035 VT.getVectorNumElements();
5036 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5037 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5038 Value, DAG.getConstant(index, MVT::i32)),
5039 DAG.getConstant(index, MVT::i32));
5041 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5042 Value->getOperand(0), Value->getOperand(1));
5044 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5046 if (!usesOnlyOneValue) {
5047 // The dominant value was splatted as 'N', but we now have to insert
5048 // all differing elements.
5049 for (unsigned I = 0; I < NumElts; ++I) {
5050 if (Op.getOperand(I) == Value)
5052 SmallVector<SDValue, 3> Ops;
5054 Ops.push_back(Op.getOperand(I));
5055 Ops.push_back(DAG.getConstant(I, MVT::i32));
5056 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5061 if (VT.getVectorElementType().isFloatingPoint()) {
5062 SmallVector<SDValue, 8> Ops;
5063 for (unsigned i = 0; i < NumElts; ++i)
5064 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5066 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5067 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5068 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5070 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5072 if (usesOnlyOneValue) {
5073 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5074 if (isConstant && Val.getNode())
5075 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5079 // If all elements are constants and the case above didn't get hit, fall back
5080 // to the default expansion, which will generate a load from the constant
5085 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5087 SDValue shuffle = ReconstructShuffle(Op, DAG);
5088 if (shuffle != SDValue())
5092 // Vectors with 32- or 64-bit elements can be built by directly assigning
5093 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5094 // will be legalized.
5095 if (EltSize >= 32) {
5096 // Do the expansion with floating-point types, since that is what the VFP
5097 // registers are defined to use, and since i64 is not legal.
5098 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5099 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5100 SmallVector<SDValue, 8> Ops;
5101 for (unsigned i = 0; i < NumElts; ++i)
5102 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5103 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5104 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5107 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5108 // know the default expansion would otherwise fall back on something even
5109 // worse. For a vector with one or two non-undef values, that's
5110 // scalar_to_vector for the elements followed by a shuffle (provided the
5111 // shuffle is valid for the target) and materialization element by element
5112 // on the stack followed by a load for everything else.
5113 if (!isConstant && !usesOnlyOneValue) {
5114 SDValue Vec = DAG.getUNDEF(VT);
5115 for (unsigned i = 0 ; i < NumElts; ++i) {
5116 SDValue V = Op.getOperand(i);
5117 if (V.getOpcode() == ISD::UNDEF)
5119 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5120 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5128 // Gather data to see if the operation can be modelled as a
5129 // shuffle in combination with VEXTs.
5130 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5131 SelectionDAG &DAG) const {
5133 EVT VT = Op.getValueType();
5134 unsigned NumElts = VT.getVectorNumElements();
5136 SmallVector<SDValue, 2> SourceVecs;
5137 SmallVector<unsigned, 2> MinElts;
5138 SmallVector<unsigned, 2> MaxElts;
5140 for (unsigned i = 0; i < NumElts; ++i) {
5141 SDValue V = Op.getOperand(i);
5142 if (V.getOpcode() == ISD::UNDEF)
5144 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5145 // A shuffle can only come from building a vector from various
5146 // elements of other vectors.
5148 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5149 VT.getVectorElementType()) {
5150 // This code doesn't know how to handle shuffles where the vector
5151 // element types do not match (this happens because type legalization
5152 // promotes the return type of EXTRACT_VECTOR_ELT).
5153 // FIXME: It might be appropriate to extend this code to handle
5154 // mismatched types.
5158 // Record this extraction against the appropriate vector if possible...
5159 SDValue SourceVec = V.getOperand(0);
5160 // If the element number isn't a constant, we can't effectively
5161 // analyze what's going on.
5162 if (!isa<ConstantSDNode>(V.getOperand(1)))
5164 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5165 bool FoundSource = false;
5166 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5167 if (SourceVecs[j] == SourceVec) {
5168 if (MinElts[j] > EltNo)
5170 if (MaxElts[j] < EltNo)
5177 // Or record a new source if not...
5179 SourceVecs.push_back(SourceVec);
5180 MinElts.push_back(EltNo);
5181 MaxElts.push_back(EltNo);
5185 // Currently only do something sane when at most two source vectors
5187 if (SourceVecs.size() > 2)
5190 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5191 int VEXTOffsets[2] = {0, 0};
5193 // This loop extracts the usage patterns of the source vectors
5194 // and prepares appropriate SDValues for a shuffle if possible.
5195 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5196 if (SourceVecs[i].getValueType() == VT) {
5197 // No VEXT necessary
5198 ShuffleSrcs[i] = SourceVecs[i];
5201 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5202 // It probably isn't worth padding out a smaller vector just to
5203 // break it down again in a shuffle.
5207 // Since only 64-bit and 128-bit vectors are legal on ARM and
5208 // we've eliminated the other cases...
5209 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5210 "unexpected vector sizes in ReconstructShuffle");
5212 if (MaxElts[i] - MinElts[i] >= NumElts) {
5213 // Span too large for a VEXT to cope
5217 if (MinElts[i] >= NumElts) {
5218 // The extraction can just take the second half
5219 VEXTOffsets[i] = NumElts;
5220 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5222 DAG.getIntPtrConstant(NumElts));
5223 } else if (MaxElts[i] < NumElts) {
5224 // The extraction can just take the first half
5226 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5228 DAG.getIntPtrConstant(0));
5230 // An actual VEXT is needed
5231 VEXTOffsets[i] = MinElts[i];
5232 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5234 DAG.getIntPtrConstant(0));
5235 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5237 DAG.getIntPtrConstant(NumElts));
5238 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5239 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5243 SmallVector<int, 8> Mask;
5245 for (unsigned i = 0; i < NumElts; ++i) {
5246 SDValue Entry = Op.getOperand(i);
5247 if (Entry.getOpcode() == ISD::UNDEF) {
5252 SDValue ExtractVec = Entry.getOperand(0);
5253 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5254 .getOperand(1))->getSExtValue();
5255 if (ExtractVec == SourceVecs[0]) {
5256 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5258 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5262 // Final check before we try to produce nonsense...
5263 if (isShuffleMaskLegal(Mask, VT))
5264 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5270 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5271 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5272 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5273 /// are assumed to be legal.
5275 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5277 if (VT.getVectorNumElements() == 4 &&
5278 (VT.is128BitVector() || VT.is64BitVector())) {
5279 unsigned PFIndexes[4];
5280 for (unsigned i = 0; i != 4; ++i) {
5284 PFIndexes[i] = M[i];
5287 // Compute the index in the perfect shuffle table.
5288 unsigned PFTableIndex =
5289 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5290 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5291 unsigned Cost = (PFEntry >> 30);
5298 unsigned Imm, WhichResult;
5300 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5301 return (EltSize >= 32 ||
5302 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5303 isVREVMask(M, VT, 64) ||
5304 isVREVMask(M, VT, 32) ||
5305 isVREVMask(M, VT, 16) ||
5306 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5307 isVTBLMask(M, VT) ||
5308 isVTRNMask(M, VT, WhichResult) ||
5309 isVUZPMask(M, VT, WhichResult) ||
5310 isVZIPMask(M, VT, WhichResult) ||
5311 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5312 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5313 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5314 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5317 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5318 /// the specified operations to build the shuffle.
5319 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5320 SDValue RHS, SelectionDAG &DAG,
5322 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5323 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5324 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5327 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5336 OP_VUZPL, // VUZP, left result
5337 OP_VUZPR, // VUZP, right result
5338 OP_VZIPL, // VZIP, left result
5339 OP_VZIPR, // VZIP, right result
5340 OP_VTRNL, // VTRN, left result
5341 OP_VTRNR // VTRN, right result
5344 if (OpNum == OP_COPY) {
5345 if (LHSID == (1*9+2)*9+3) return LHS;
5346 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5350 SDValue OpLHS, OpRHS;
5351 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5352 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5353 EVT VT = OpLHS.getValueType();
5356 default: llvm_unreachable("Unknown shuffle opcode!");
5358 // VREV divides the vector in half and swaps within the half.
5359 if (VT.getVectorElementType() == MVT::i32 ||
5360 VT.getVectorElementType() == MVT::f32)
5361 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5362 // vrev <4 x i16> -> VREV32
5363 if (VT.getVectorElementType() == MVT::i16)
5364 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5365 // vrev <4 x i8> -> VREV16
5366 assert(VT.getVectorElementType() == MVT::i8);
5367 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5372 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5373 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5377 return DAG.getNode(ARMISD::VEXT, dl, VT,
5379 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5382 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5383 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5386 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5387 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5390 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5391 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5395 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5396 ArrayRef<int> ShuffleMask,
5397 SelectionDAG &DAG) {
5398 // Check to see if we can use the VTBL instruction.
5399 SDValue V1 = Op.getOperand(0);
5400 SDValue V2 = Op.getOperand(1);
5403 SmallVector<SDValue, 8> VTBLMask;
5404 for (ArrayRef<int>::iterator
5405 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5406 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5408 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5409 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5410 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5412 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5413 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5416 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5417 SelectionDAG &DAG) {
5419 SDValue OpLHS = Op.getOperand(0);
5420 EVT VT = OpLHS.getValueType();
5422 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5423 "Expect an v8i16/v16i8 type");
5424 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5425 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5426 // extract the first 8 bytes into the top double word and the last 8 bytes
5427 // into the bottom double word. The v8i16 case is similar.
5428 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5429 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5430 DAG.getConstant(ExtractNum, MVT::i32));
5433 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5434 SDValue V1 = Op.getOperand(0);
5435 SDValue V2 = Op.getOperand(1);
5437 EVT VT = Op.getValueType();
5438 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5440 // Convert shuffles that are directly supported on NEON to target-specific
5441 // DAG nodes, instead of keeping them as shuffles and matching them again
5442 // during code selection. This is more efficient and avoids the possibility
5443 // of inconsistencies between legalization and selection.
5444 // FIXME: floating-point vectors should be canonicalized to integer vectors
5445 // of the same time so that they get CSEd properly.
5446 ArrayRef<int> ShuffleMask = SVN->getMask();
5448 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5449 if (EltSize <= 32) {
5450 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5451 int Lane = SVN->getSplatIndex();
5452 // If this is undef splat, generate it via "just" vdup, if possible.
5453 if (Lane == -1) Lane = 0;
5455 // Test if V1 is a SCALAR_TO_VECTOR.
5456 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5457 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5459 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5460 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5462 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5463 !isa<ConstantSDNode>(V1.getOperand(0))) {
5464 bool IsScalarToVector = true;
5465 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5466 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5467 IsScalarToVector = false;
5470 if (IsScalarToVector)
5471 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5473 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5474 DAG.getConstant(Lane, MVT::i32));
5479 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5482 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5483 DAG.getConstant(Imm, MVT::i32));
5486 if (isVREVMask(ShuffleMask, VT, 64))
5487 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5488 if (isVREVMask(ShuffleMask, VT, 32))
5489 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5490 if (isVREVMask(ShuffleMask, VT, 16))
5491 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5493 if (V2->getOpcode() == ISD::UNDEF &&
5494 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5495 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5496 DAG.getConstant(Imm, MVT::i32));
5499 // Check for Neon shuffles that modify both input vectors in place.
5500 // If both results are used, i.e., if there are two shuffles with the same
5501 // source operands and with masks corresponding to both results of one of
5502 // these operations, DAG memoization will ensure that a single node is
5503 // used for both shuffles.
5504 unsigned WhichResult;
5505 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5506 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5507 V1, V2).getValue(WhichResult);
5508 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5509 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5510 V1, V2).getValue(WhichResult);
5511 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5512 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5513 V1, V2).getValue(WhichResult);
5515 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5516 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5517 V1, V1).getValue(WhichResult);
5518 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5519 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5520 V1, V1).getValue(WhichResult);
5521 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5522 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5523 V1, V1).getValue(WhichResult);
5526 // If the shuffle is not directly supported and it has 4 elements, use
5527 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5528 unsigned NumElts = VT.getVectorNumElements();
5530 unsigned PFIndexes[4];
5531 for (unsigned i = 0; i != 4; ++i) {
5532 if (ShuffleMask[i] < 0)
5535 PFIndexes[i] = ShuffleMask[i];
5538 // Compute the index in the perfect shuffle table.
5539 unsigned PFTableIndex =
5540 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5541 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5542 unsigned Cost = (PFEntry >> 30);
5545 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5548 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5549 if (EltSize >= 32) {
5550 // Do the expansion with floating-point types, since that is what the VFP
5551 // registers are defined to use, and since i64 is not legal.
5552 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5553 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5554 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5555 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5556 SmallVector<SDValue, 8> Ops;
5557 for (unsigned i = 0; i < NumElts; ++i) {
5558 if (ShuffleMask[i] < 0)
5559 Ops.push_back(DAG.getUNDEF(EltVT));
5561 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5562 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5563 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5566 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5567 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5570 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5571 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5573 if (VT == MVT::v8i8) {
5574 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5575 if (NewOp.getNode())
5582 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5583 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5584 SDValue Lane = Op.getOperand(2);
5585 if (!isa<ConstantSDNode>(Lane))
5591 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5592 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5593 SDValue Lane = Op.getOperand(1);
5594 if (!isa<ConstantSDNode>(Lane))
5597 SDValue Vec = Op.getOperand(0);
5598 if (Op.getValueType() == MVT::i32 &&
5599 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5601 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5607 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5608 // The only time a CONCAT_VECTORS operation can have legal types is when
5609 // two 64-bit vectors are concatenated to a 128-bit vector.
5610 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5611 "unexpected CONCAT_VECTORS");
5613 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5614 SDValue Op0 = Op.getOperand(0);
5615 SDValue Op1 = Op.getOperand(1);
5616 if (Op0.getOpcode() != ISD::UNDEF)
5617 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5618 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5619 DAG.getIntPtrConstant(0));
5620 if (Op1.getOpcode() != ISD::UNDEF)
5621 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5622 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5623 DAG.getIntPtrConstant(1));
5624 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5627 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5628 /// element has been zero/sign-extended, depending on the isSigned parameter,
5629 /// from an integer type half its size.
5630 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5632 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5633 EVT VT = N->getValueType(0);
5634 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5635 SDNode *BVN = N->getOperand(0).getNode();
5636 if (BVN->getValueType(0) != MVT::v4i32 ||
5637 BVN->getOpcode() != ISD::BUILD_VECTOR)
5639 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5640 unsigned HiElt = 1 - LoElt;
5641 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5642 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5643 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5644 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5645 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5648 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5649 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5652 if (Hi0->isNullValue() && Hi1->isNullValue())
5658 if (N->getOpcode() != ISD::BUILD_VECTOR)
5661 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5662 SDNode *Elt = N->getOperand(i).getNode();
5663 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5664 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5665 unsigned HalfSize = EltSize / 2;
5667 if (!isIntN(HalfSize, C->getSExtValue()))
5670 if (!isUIntN(HalfSize, C->getZExtValue()))
5681 /// isSignExtended - Check if a node is a vector value that is sign-extended
5682 /// or a constant BUILD_VECTOR with sign-extended elements.
5683 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5684 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5686 if (isExtendedBUILD_VECTOR(N, DAG, true))
5691 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5692 /// or a constant BUILD_VECTOR with zero-extended elements.
5693 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5694 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5696 if (isExtendedBUILD_VECTOR(N, DAG, false))
5701 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5702 if (OrigVT.getSizeInBits() >= 64)
5705 assert(OrigVT.isSimple() && "Expecting a simple value type");
5707 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5708 switch (OrigSimpleTy) {
5709 default: llvm_unreachable("Unexpected Vector Type");
5718 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5719 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5720 /// We insert the required extension here to get the vector to fill a D register.
5721 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5724 unsigned ExtOpcode) {
5725 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5726 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5727 // 64-bits we need to insert a new extension so that it will be 64-bits.
5728 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5729 if (OrigTy.getSizeInBits() >= 64)
5732 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5733 EVT NewVT = getExtensionTo64Bits(OrigTy);
5735 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5738 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5739 /// does not do any sign/zero extension. If the original vector is less
5740 /// than 64 bits, an appropriate extension will be added after the load to
5741 /// reach a total size of 64 bits. We have to add the extension separately
5742 /// because ARM does not have a sign/zero extending load for vectors.
5743 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5744 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5746 // The load already has the right type.
5747 if (ExtendedTy == LD->getMemoryVT())
5748 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5749 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5750 LD->isNonTemporal(), LD->isInvariant(),
5751 LD->getAlignment());
5753 // We need to create a zextload/sextload. We cannot just create a load
5754 // followed by a zext/zext node because LowerMUL is also run during normal
5755 // operation legalization where we can't create illegal types.
5756 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5757 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5758 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5759 LD->isNonTemporal(), LD->getAlignment());
5762 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5763 /// extending load, or BUILD_VECTOR with extended elements, return the
5764 /// unextended value. The unextended vector should be 64 bits so that it can
5765 /// be used as an operand to a VMULL instruction. If the original vector size
5766 /// before extension is less than 64 bits we add a an extension to resize
5767 /// the vector to 64 bits.
5768 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5769 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5770 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5771 N->getOperand(0)->getValueType(0),
5775 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5776 return SkipLoadExtensionForVMULL(LD, DAG);
5778 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5779 // have been legalized as a BITCAST from v4i32.
5780 if (N->getOpcode() == ISD::BITCAST) {
5781 SDNode *BVN = N->getOperand(0).getNode();
5782 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5783 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5784 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5785 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5786 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5788 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5789 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5790 EVT VT = N->getValueType(0);
5791 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5792 unsigned NumElts = VT.getVectorNumElements();
5793 MVT TruncVT = MVT::getIntegerVT(EltSize);
5794 SmallVector<SDValue, 8> Ops;
5795 for (unsigned i = 0; i != NumElts; ++i) {
5796 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5797 const APInt &CInt = C->getAPIntValue();
5798 // Element types smaller than 32 bits are not legal, so use i32 elements.
5799 // The values are implicitly truncated so sext vs. zext doesn't matter.
5800 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5802 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5803 MVT::getVectorVT(TruncVT, NumElts), Ops);
5806 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5807 unsigned Opcode = N->getOpcode();
5808 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5809 SDNode *N0 = N->getOperand(0).getNode();
5810 SDNode *N1 = N->getOperand(1).getNode();
5811 return N0->hasOneUse() && N1->hasOneUse() &&
5812 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5817 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5818 unsigned Opcode = N->getOpcode();
5819 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5820 SDNode *N0 = N->getOperand(0).getNode();
5821 SDNode *N1 = N->getOperand(1).getNode();
5822 return N0->hasOneUse() && N1->hasOneUse() &&
5823 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5828 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5829 // Multiplications are only custom-lowered for 128-bit vectors so that
5830 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5831 EVT VT = Op.getValueType();
5832 assert(VT.is128BitVector() && VT.isInteger() &&
5833 "unexpected type for custom-lowering ISD::MUL");
5834 SDNode *N0 = Op.getOperand(0).getNode();
5835 SDNode *N1 = Op.getOperand(1).getNode();
5836 unsigned NewOpc = 0;
5838 bool isN0SExt = isSignExtended(N0, DAG);
5839 bool isN1SExt = isSignExtended(N1, DAG);
5840 if (isN0SExt && isN1SExt)
5841 NewOpc = ARMISD::VMULLs;
5843 bool isN0ZExt = isZeroExtended(N0, DAG);
5844 bool isN1ZExt = isZeroExtended(N1, DAG);
5845 if (isN0ZExt && isN1ZExt)
5846 NewOpc = ARMISD::VMULLu;
5847 else if (isN1SExt || isN1ZExt) {
5848 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5849 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5850 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5851 NewOpc = ARMISD::VMULLs;
5853 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5854 NewOpc = ARMISD::VMULLu;
5856 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5858 NewOpc = ARMISD::VMULLu;
5864 if (VT == MVT::v2i64)
5865 // Fall through to expand this. It is not legal.
5868 // Other vector multiplications are legal.
5873 // Legalize to a VMULL instruction.
5876 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5878 Op0 = SkipExtensionForVMULL(N0, DAG);
5879 assert(Op0.getValueType().is64BitVector() &&
5880 Op1.getValueType().is64BitVector() &&
5881 "unexpected types for extended operands to VMULL");
5882 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5885 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5886 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5893 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5894 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5895 EVT Op1VT = Op1.getValueType();
5896 return DAG.getNode(N0->getOpcode(), DL, VT,
5897 DAG.getNode(NewOpc, DL, VT,
5898 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5899 DAG.getNode(NewOpc, DL, VT,
5900 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5904 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5906 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5907 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5908 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5909 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5910 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5911 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5912 // Get reciprocal estimate.
5913 // float4 recip = vrecpeq_f32(yf);
5914 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5915 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5916 // Because char has a smaller range than uchar, we can actually get away
5917 // without any newton steps. This requires that we use a weird bias
5918 // of 0xb000, however (again, this has been exhaustively tested).
5919 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5920 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5921 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5922 Y = DAG.getConstant(0xb000, MVT::i32);
5923 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5924 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5925 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5926 // Convert back to short.
5927 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5928 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5933 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5935 // Convert to float.
5936 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5937 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5938 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5939 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5940 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5941 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5943 // Use reciprocal estimate and one refinement step.
5944 // float4 recip = vrecpeq_f32(yf);
5945 // recip *= vrecpsq_f32(yf, recip);
5946 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5947 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5948 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5949 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5951 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5952 // Because short has a smaller range than ushort, we can actually get away
5953 // with only a single newton step. This requires that we use a weird bias
5954 // of 89, however (again, this has been exhaustively tested).
5955 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5956 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5957 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5958 N1 = DAG.getConstant(0x89, MVT::i32);
5959 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5960 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5961 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5962 // Convert back to integer and return.
5963 // return vmovn_s32(vcvt_s32_f32(result));
5964 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5965 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5969 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5970 EVT VT = Op.getValueType();
5971 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5972 "unexpected type for custom-lowering ISD::SDIV");
5975 SDValue N0 = Op.getOperand(0);
5976 SDValue N1 = Op.getOperand(1);
5979 if (VT == MVT::v8i8) {
5980 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5981 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5983 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5984 DAG.getIntPtrConstant(4));
5985 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5986 DAG.getIntPtrConstant(4));
5987 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5988 DAG.getIntPtrConstant(0));
5989 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5990 DAG.getIntPtrConstant(0));
5992 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5993 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5995 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5996 N0 = LowerCONCAT_VECTORS(N0, DAG);
5998 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6001 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6004 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6005 EVT VT = Op.getValueType();
6006 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6007 "unexpected type for custom-lowering ISD::UDIV");
6010 SDValue N0 = Op.getOperand(0);
6011 SDValue N1 = Op.getOperand(1);
6014 if (VT == MVT::v8i8) {
6015 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6016 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6018 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6019 DAG.getIntPtrConstant(4));
6020 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6021 DAG.getIntPtrConstant(4));
6022 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6023 DAG.getIntPtrConstant(0));
6024 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6025 DAG.getIntPtrConstant(0));
6027 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6028 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6030 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6031 N0 = LowerCONCAT_VECTORS(N0, DAG);
6033 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6034 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6039 // v4i16 sdiv ... Convert to float.
6040 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6041 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6042 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6043 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6044 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6045 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6047 // Use reciprocal estimate and two refinement steps.
6048 // float4 recip = vrecpeq_f32(yf);
6049 // recip *= vrecpsq_f32(yf, recip);
6050 // recip *= vrecpsq_f32(yf, recip);
6051 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6052 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6053 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6054 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6056 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6057 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6058 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6060 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6061 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6062 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6063 // and that it will never cause us to return an answer too large).
6064 // float4 result = as_float4(as_int4(xf*recip) + 2);
6065 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6066 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6067 N1 = DAG.getConstant(2, MVT::i32);
6068 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6069 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6070 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6071 // Convert back to integer and return.
6072 // return vmovn_u32(vcvt_s32_f32(result));
6073 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6074 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6078 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6079 EVT VT = Op.getNode()->getValueType(0);
6080 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6083 bool ExtraOp = false;
6084 switch (Op.getOpcode()) {
6085 default: llvm_unreachable("Invalid code");
6086 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6087 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6088 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6089 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6093 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6095 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6096 Op.getOperand(1), Op.getOperand(2));
6099 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6100 assert(Subtarget->isTargetDarwin());
6102 // For iOS, we want to call an alternative entry point: __sincos_stret,
6103 // return values are passed via sret.
6105 SDValue Arg = Op.getOperand(0);
6106 EVT ArgVT = Arg.getValueType();
6107 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6109 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6110 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6112 // Pair of floats / doubles used to pass the result.
6113 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6115 // Create stack object for sret.
6116 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6117 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6118 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6119 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6125 Entry.Ty = RetTy->getPointerTo();
6126 Entry.isSExt = false;
6127 Entry.isZExt = false;
6128 Entry.isSRet = true;
6129 Args.push_back(Entry);
6133 Entry.isSExt = false;
6134 Entry.isZExt = false;
6135 Args.push_back(Entry);
6137 const char *LibcallName = (ArgVT == MVT::f64)
6138 ? "__sincos_stret" : "__sincosf_stret";
6139 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6141 TargetLowering::CallLoweringInfo CLI(DAG);
6142 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6143 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6145 .setDiscardResult();
6147 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6149 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6150 MachinePointerInfo(), false, false, false, 0);
6152 // Address of cos field.
6153 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6154 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6155 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6156 MachinePointerInfo(), false, false, false, 0);
6158 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6159 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6160 LoadSin.getValue(0), LoadCos.getValue(0));
6163 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6164 // Monotonic load/store is legal for all targets
6165 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6168 // Acquire/Release load/store is not legal for targets without a
6169 // dmb or equivalent available.
6173 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6174 SmallVectorImpl<SDValue> &Results,
6176 const ARMSubtarget *Subtarget) {
6178 SDValue Cycles32, OutChain;
6180 if (Subtarget->hasPerfMon()) {
6181 // Under Power Management extensions, the cycle-count is:
6182 // mrc p15, #0, <Rt>, c9, c13, #0
6183 SDValue Ops[] = { N->getOperand(0), // Chain
6184 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6185 DAG.getConstant(15, MVT::i32),
6186 DAG.getConstant(0, MVT::i32),
6187 DAG.getConstant(9, MVT::i32),
6188 DAG.getConstant(13, MVT::i32),
6189 DAG.getConstant(0, MVT::i32)
6192 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6193 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6194 OutChain = Cycles32.getValue(1);
6196 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6197 // there are older ARM CPUs that have implementation-specific ways of
6198 // obtaining this information (FIXME!).
6199 Cycles32 = DAG.getConstant(0, MVT::i32);
6200 OutChain = DAG.getEntryNode();
6204 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6205 Cycles32, DAG.getConstant(0, MVT::i32));
6206 Results.push_back(Cycles64);
6207 Results.push_back(OutChain);
6210 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6211 switch (Op.getOpcode()) {
6212 default: llvm_unreachable("Don't know how to custom lower this!");
6213 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6214 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6215 case ISD::GlobalAddress:
6216 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6217 default: llvm_unreachable("unknown object format");
6219 return LowerGlobalAddressWindows(Op, DAG);
6221 return LowerGlobalAddressELF(Op, DAG);
6223 return LowerGlobalAddressDarwin(Op, DAG);
6225 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6226 case ISD::SELECT: return LowerSELECT(Op, DAG);
6227 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6228 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6229 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6230 case ISD::VASTART: return LowerVASTART(Op, DAG);
6231 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6232 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6233 case ISD::SINT_TO_FP:
6234 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6235 case ISD::FP_TO_SINT:
6236 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6237 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6238 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6239 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6240 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6241 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6242 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6243 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6245 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6248 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6249 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6250 case ISD::SRL_PARTS:
6251 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6252 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6253 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6254 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6255 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6256 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6257 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6258 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6259 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6260 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6261 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6262 case ISD::MUL: return LowerMUL(Op, DAG);
6263 case ISD::SDIV: return LowerSDIV(Op, DAG);
6264 case ISD::UDIV: return LowerUDIV(Op, DAG);
6268 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6273 return LowerXALUO(Op, DAG);
6274 case ISD::ATOMIC_LOAD:
6275 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6276 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6278 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6279 case ISD::DYNAMIC_STACKALLOC:
6280 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6281 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6282 llvm_unreachable("Don't know how to custom lower this!");
6286 /// ReplaceNodeResults - Replace the results of node with an illegal result
6287 /// type with new values built out of custom code.
6288 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6289 SmallVectorImpl<SDValue>&Results,
6290 SelectionDAG &DAG) const {
6292 switch (N->getOpcode()) {
6294 llvm_unreachable("Don't know how to custom expand this!");
6296 Res = ExpandBITCAST(N, DAG);
6300 Res = Expand64BitShift(N, DAG, Subtarget);
6302 case ISD::READCYCLECOUNTER:
6303 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6307 Results.push_back(Res);
6310 //===----------------------------------------------------------------------===//
6311 // ARM Scheduler Hooks
6312 //===----------------------------------------------------------------------===//
6314 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6315 /// registers the function context.
6316 void ARMTargetLowering::
6317 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6318 MachineBasicBlock *DispatchBB, int FI) const {
6319 const TargetInstrInfo *TII =
6320 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6321 DebugLoc dl = MI->getDebugLoc();
6322 MachineFunction *MF = MBB->getParent();
6323 MachineRegisterInfo *MRI = &MF->getRegInfo();
6324 MachineConstantPool *MCP = MF->getConstantPool();
6325 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6326 const Function *F = MF->getFunction();
6328 bool isThumb = Subtarget->isThumb();
6329 bool isThumb2 = Subtarget->isThumb2();
6331 unsigned PCLabelId = AFI->createPICLabelUId();
6332 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6333 ARMConstantPoolValue *CPV =
6334 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6335 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6337 const TargetRegisterClass *TRC = isThumb ?
6338 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6339 (const TargetRegisterClass*)&ARM::GPRRegClass;
6341 // Grab constant pool and fixed stack memory operands.
6342 MachineMemOperand *CPMMO =
6343 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6344 MachineMemOperand::MOLoad, 4, 4);
6346 MachineMemOperand *FIMMOSt =
6347 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6348 MachineMemOperand::MOStore, 4, 4);
6350 // Load the address of the dispatch MBB into the jump buffer.
6352 // Incoming value: jbuf
6353 // ldr.n r5, LCPI1_1
6356 // str r5, [$jbuf, #+4] ; &jbuf[1]
6357 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6358 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6359 .addConstantPoolIndex(CPI)
6360 .addMemOperand(CPMMO));
6361 // Set the low bit because of thumb mode.
6362 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6364 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6365 .addReg(NewVReg1, RegState::Kill)
6367 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6368 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6369 .addReg(NewVReg2, RegState::Kill)
6371 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6372 .addReg(NewVReg3, RegState::Kill)
6374 .addImm(36) // &jbuf[1] :: pc
6375 .addMemOperand(FIMMOSt));
6376 } else if (isThumb) {
6377 // Incoming value: jbuf
6378 // ldr.n r1, LCPI1_4
6382 // add r2, $jbuf, #+4 ; &jbuf[1]
6384 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6385 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6386 .addConstantPoolIndex(CPI)
6387 .addMemOperand(CPMMO));
6388 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6389 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6390 .addReg(NewVReg1, RegState::Kill)
6392 // Set the low bit because of thumb mode.
6393 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6394 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6395 .addReg(ARM::CPSR, RegState::Define)
6397 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6398 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6399 .addReg(ARM::CPSR, RegState::Define)
6400 .addReg(NewVReg2, RegState::Kill)
6401 .addReg(NewVReg3, RegState::Kill));
6402 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6403 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6405 .addImm(36)); // &jbuf[1] :: pc
6406 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6407 .addReg(NewVReg4, RegState::Kill)
6408 .addReg(NewVReg5, RegState::Kill)
6410 .addMemOperand(FIMMOSt));
6412 // Incoming value: jbuf
6415 // str r1, [$jbuf, #+4] ; &jbuf[1]
6416 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6417 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6418 .addConstantPoolIndex(CPI)
6420 .addMemOperand(CPMMO));
6421 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6422 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6423 .addReg(NewVReg1, RegState::Kill)
6424 .addImm(PCLabelId));
6425 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6426 .addReg(NewVReg2, RegState::Kill)
6428 .addImm(36) // &jbuf[1] :: pc
6429 .addMemOperand(FIMMOSt));
6433 MachineBasicBlock *ARMTargetLowering::
6434 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6435 const TargetInstrInfo *TII =
6436 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6437 DebugLoc dl = MI->getDebugLoc();
6438 MachineFunction *MF = MBB->getParent();
6439 MachineRegisterInfo *MRI = &MF->getRegInfo();
6440 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6441 MachineFrameInfo *MFI = MF->getFrameInfo();
6442 int FI = MFI->getFunctionContextIndex();
6444 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6445 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6446 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6448 // Get a mapping of the call site numbers to all of the landing pads they're
6450 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6451 unsigned MaxCSNum = 0;
6452 MachineModuleInfo &MMI = MF->getMMI();
6453 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6455 if (!BB->isLandingPad()) continue;
6457 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6459 for (MachineBasicBlock::iterator
6460 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6461 if (!II->isEHLabel()) continue;
6463 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6464 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6466 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6467 for (SmallVectorImpl<unsigned>::iterator
6468 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6469 CSI != CSE; ++CSI) {
6470 CallSiteNumToLPad[*CSI].push_back(BB);
6471 MaxCSNum = std::max(MaxCSNum, *CSI);
6477 // Get an ordered list of the machine basic blocks for the jump table.
6478 std::vector<MachineBasicBlock*> LPadList;
6479 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6480 LPadList.reserve(CallSiteNumToLPad.size());
6481 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6482 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6483 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6484 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6485 LPadList.push_back(*II);
6486 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6490 assert(!LPadList.empty() &&
6491 "No landing pad destinations for the dispatch jump table!");
6493 // Create the jump table and associated information.
6494 MachineJumpTableInfo *JTI =
6495 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6496 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6497 unsigned UId = AFI->createJumpTableUId();
6498 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6500 // Create the MBBs for the dispatch code.
6502 // Shove the dispatch's address into the return slot in the function context.
6503 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6504 DispatchBB->setIsLandingPad();
6506 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6507 unsigned trap_opcode;
6508 if (Subtarget->isThumb())
6509 trap_opcode = ARM::tTRAP;
6511 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6513 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6514 DispatchBB->addSuccessor(TrapBB);
6516 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6517 DispatchBB->addSuccessor(DispContBB);
6520 MF->insert(MF->end(), DispatchBB);
6521 MF->insert(MF->end(), DispContBB);
6522 MF->insert(MF->end(), TrapBB);
6524 // Insert code into the entry block that creates and registers the function
6526 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6528 MachineMemOperand *FIMMOLd =
6529 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6530 MachineMemOperand::MOLoad |
6531 MachineMemOperand::MOVolatile, 4, 4);
6533 MachineInstrBuilder MIB;
6534 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6536 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6537 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6539 // Add a register mask with no preserved registers. This results in all
6540 // registers being marked as clobbered.
6541 MIB.addRegMask(RI.getNoPreservedMask());
6543 unsigned NumLPads = LPadList.size();
6544 if (Subtarget->isThumb2()) {
6545 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6546 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6549 .addMemOperand(FIMMOLd));
6551 if (NumLPads < 256) {
6552 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6554 .addImm(LPadList.size()));
6556 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6557 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6558 .addImm(NumLPads & 0xFFFF));
6560 unsigned VReg2 = VReg1;
6561 if ((NumLPads & 0xFFFF0000) != 0) {
6562 VReg2 = MRI->createVirtualRegister(TRC);
6563 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6565 .addImm(NumLPads >> 16));
6568 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6573 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6578 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6579 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6580 .addJumpTableIndex(MJTI)
6583 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6586 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6587 .addReg(NewVReg3, RegState::Kill)
6589 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6591 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6592 .addReg(NewVReg4, RegState::Kill)
6594 .addJumpTableIndex(MJTI)
6596 } else if (Subtarget->isThumb()) {
6597 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6598 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6601 .addMemOperand(FIMMOLd));
6603 if (NumLPads < 256) {
6604 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6608 MachineConstantPool *ConstantPool = MF->getConstantPool();
6609 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6610 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6612 // MachineConstantPool wants an explicit alignment.
6613 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6615 Align = getDataLayout()->getTypeAllocSize(C->getType());
6616 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6618 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6619 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6620 .addReg(VReg1, RegState::Define)
6621 .addConstantPoolIndex(Idx));
6622 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6627 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6632 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6633 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6634 .addReg(ARM::CPSR, RegState::Define)
6638 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6639 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6640 .addJumpTableIndex(MJTI)
6643 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6644 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6645 .addReg(ARM::CPSR, RegState::Define)
6646 .addReg(NewVReg2, RegState::Kill)
6649 MachineMemOperand *JTMMOLd =
6650 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6651 MachineMemOperand::MOLoad, 4, 4);
6653 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6654 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6655 .addReg(NewVReg4, RegState::Kill)
6657 .addMemOperand(JTMMOLd));
6659 unsigned NewVReg6 = NewVReg5;
6660 if (RelocM == Reloc::PIC_) {
6661 NewVReg6 = MRI->createVirtualRegister(TRC);
6662 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6663 .addReg(ARM::CPSR, RegState::Define)
6664 .addReg(NewVReg5, RegState::Kill)
6668 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6669 .addReg(NewVReg6, RegState::Kill)
6670 .addJumpTableIndex(MJTI)
6673 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6674 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6677 .addMemOperand(FIMMOLd));
6679 if (NumLPads < 256) {
6680 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6683 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6684 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6685 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6686 .addImm(NumLPads & 0xFFFF));
6688 unsigned VReg2 = VReg1;
6689 if ((NumLPads & 0xFFFF0000) != 0) {
6690 VReg2 = MRI->createVirtualRegister(TRC);
6691 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6693 .addImm(NumLPads >> 16));
6696 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6700 MachineConstantPool *ConstantPool = MF->getConstantPool();
6701 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6702 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6704 // MachineConstantPool wants an explicit alignment.
6705 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6707 Align = getDataLayout()->getTypeAllocSize(C->getType());
6708 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6710 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6711 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6712 .addReg(VReg1, RegState::Define)
6713 .addConstantPoolIndex(Idx)
6715 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6717 .addReg(VReg1, RegState::Kill));
6720 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6725 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6727 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6729 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6730 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6731 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6732 .addJumpTableIndex(MJTI)
6735 MachineMemOperand *JTMMOLd =
6736 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6737 MachineMemOperand::MOLoad, 4, 4);
6738 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6740 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6741 .addReg(NewVReg3, RegState::Kill)
6744 .addMemOperand(JTMMOLd));
6746 if (RelocM == Reloc::PIC_) {
6747 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6748 .addReg(NewVReg5, RegState::Kill)
6750 .addJumpTableIndex(MJTI)
6753 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6754 .addReg(NewVReg5, RegState::Kill)
6755 .addJumpTableIndex(MJTI)
6760 // Add the jump table entries as successors to the MBB.
6761 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6762 for (std::vector<MachineBasicBlock*>::iterator
6763 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6764 MachineBasicBlock *CurMBB = *I;
6765 if (SeenMBBs.insert(CurMBB))
6766 DispContBB->addSuccessor(CurMBB);
6769 // N.B. the order the invoke BBs are processed in doesn't matter here.
6770 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6771 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6772 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6773 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6774 MachineBasicBlock *BB = *I;
6776 // Remove the landing pad successor from the invoke block and replace it
6777 // with the new dispatch block.
6778 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6780 while (!Successors.empty()) {
6781 MachineBasicBlock *SMBB = Successors.pop_back_val();
6782 if (SMBB->isLandingPad()) {
6783 BB->removeSuccessor(SMBB);
6784 MBBLPads.push_back(SMBB);
6788 BB->addSuccessor(DispatchBB);
6790 // Find the invoke call and mark all of the callee-saved registers as
6791 // 'implicit defined' so that they're spilled. This prevents code from
6792 // moving instructions to before the EH block, where they will never be
6794 for (MachineBasicBlock::reverse_iterator
6795 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6796 if (!II->isCall()) continue;
6798 DenseMap<unsigned, bool> DefRegs;
6799 for (MachineInstr::mop_iterator
6800 OI = II->operands_begin(), OE = II->operands_end();
6802 if (!OI->isReg()) continue;
6803 DefRegs[OI->getReg()] = true;
6806 MachineInstrBuilder MIB(*MF, &*II);
6808 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6809 unsigned Reg = SavedRegs[i];
6810 if (Subtarget->isThumb2() &&
6811 !ARM::tGPRRegClass.contains(Reg) &&
6812 !ARM::hGPRRegClass.contains(Reg))
6814 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6816 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6819 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6826 // Mark all former landing pads as non-landing pads. The dispatch is the only
6828 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6829 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6830 (*I)->setIsLandingPad(false);
6832 // The instruction is gone now.
6833 MI->eraseFromParent();
6839 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6840 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6841 E = MBB->succ_end(); I != E; ++I)
6844 llvm_unreachable("Expecting a BB with two successors!");
6847 /// Return the load opcode for a given load size. If load size >= 8,
6848 /// neon opcode will be returned.
6849 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6851 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6852 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6854 return LdSize == 4 ? ARM::tLDRi
6855 : LdSize == 2 ? ARM::tLDRHi
6856 : LdSize == 1 ? ARM::tLDRBi : 0;
6858 return LdSize == 4 ? ARM::t2LDR_POST
6859 : LdSize == 2 ? ARM::t2LDRH_POST
6860 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6861 return LdSize == 4 ? ARM::LDR_POST_IMM
6862 : LdSize == 2 ? ARM::LDRH_POST
6863 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6866 /// Return the store opcode for a given store size. If store size >= 8,
6867 /// neon opcode will be returned.
6868 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6870 return StSize == 16 ? ARM::VST1q32wb_fixed
6871 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6873 return StSize == 4 ? ARM::tSTRi
6874 : StSize == 2 ? ARM::tSTRHi
6875 : StSize == 1 ? ARM::tSTRBi : 0;
6877 return StSize == 4 ? ARM::t2STR_POST
6878 : StSize == 2 ? ARM::t2STRH_POST
6879 : StSize == 1 ? ARM::t2STRB_POST : 0;
6880 return StSize == 4 ? ARM::STR_POST_IMM
6881 : StSize == 2 ? ARM::STRH_POST
6882 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6885 /// Emit a post-increment load operation with given size. The instructions
6886 /// will be added to BB at Pos.
6887 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6888 const TargetInstrInfo *TII, DebugLoc dl,
6889 unsigned LdSize, unsigned Data, unsigned AddrIn,
6890 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6891 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6892 assert(LdOpc != 0 && "Should have a load opcode");
6894 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6895 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6897 } else if (IsThumb1) {
6898 // load + update AddrIn
6899 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6900 .addReg(AddrIn).addImm(0));
6901 MachineInstrBuilder MIB =
6902 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6903 MIB = AddDefaultT1CC(MIB);
6904 MIB.addReg(AddrIn).addImm(LdSize);
6905 AddDefaultPred(MIB);
6906 } else if (IsThumb2) {
6907 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6908 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6911 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6912 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6913 .addReg(0).addImm(LdSize));
6917 /// Emit a post-increment store operation with given size. The instructions
6918 /// will be added to BB at Pos.
6919 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6920 const TargetInstrInfo *TII, DebugLoc dl,
6921 unsigned StSize, unsigned Data, unsigned AddrIn,
6922 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6923 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6924 assert(StOpc != 0 && "Should have a store opcode");
6926 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6927 .addReg(AddrIn).addImm(0).addReg(Data));
6928 } else if (IsThumb1) {
6929 // store + update AddrIn
6930 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6931 .addReg(AddrIn).addImm(0));
6932 MachineInstrBuilder MIB =
6933 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6934 MIB = AddDefaultT1CC(MIB);
6935 MIB.addReg(AddrIn).addImm(StSize);
6936 AddDefaultPred(MIB);
6937 } else if (IsThumb2) {
6938 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6939 .addReg(Data).addReg(AddrIn).addImm(StSize));
6941 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6942 .addReg(Data).addReg(AddrIn).addReg(0)
6948 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6949 MachineBasicBlock *BB) const {
6950 // This pseudo instruction has 3 operands: dst, src, size
6951 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6952 // Otherwise, we will generate unrolled scalar copies.
6953 const TargetInstrInfo *TII =
6954 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6955 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6956 MachineFunction::iterator It = BB;
6959 unsigned dest = MI->getOperand(0).getReg();
6960 unsigned src = MI->getOperand(1).getReg();
6961 unsigned SizeVal = MI->getOperand(2).getImm();
6962 unsigned Align = MI->getOperand(3).getImm();
6963 DebugLoc dl = MI->getDebugLoc();
6965 MachineFunction *MF = BB->getParent();
6966 MachineRegisterInfo &MRI = MF->getRegInfo();
6967 unsigned UnitSize = 0;
6968 const TargetRegisterClass *TRC = nullptr;
6969 const TargetRegisterClass *VecTRC = nullptr;
6971 bool IsThumb1 = Subtarget->isThumb1Only();
6972 bool IsThumb2 = Subtarget->isThumb2();
6976 } else if (Align & 2) {
6979 // Check whether we can use NEON instructions.
6980 if (!MF->getFunction()->getAttributes().
6981 hasAttribute(AttributeSet::FunctionIndex,
6982 Attribute::NoImplicitFloat) &&
6983 Subtarget->hasNEON()) {
6984 if ((Align % 16 == 0) && SizeVal >= 16)
6986 else if ((Align % 8 == 0) && SizeVal >= 8)
6989 // Can't use NEON instructions.
6994 // Select the correct opcode and register class for unit size load/store
6995 bool IsNeon = UnitSize >= 8;
6996 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6997 : (const TargetRegisterClass *)&ARM::GPRRegClass;
6999 VecTRC = UnitSize == 16
7000 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7002 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7005 unsigned BytesLeft = SizeVal % UnitSize;
7006 unsigned LoopSize = SizeVal - BytesLeft;
7008 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7009 // Use LDR and STR to copy.
7010 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7011 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7012 unsigned srcIn = src;
7013 unsigned destIn = dest;
7014 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7015 unsigned srcOut = MRI.createVirtualRegister(TRC);
7016 unsigned destOut = MRI.createVirtualRegister(TRC);
7017 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7018 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7019 IsThumb1, IsThumb2);
7020 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7021 IsThumb1, IsThumb2);
7026 // Handle the leftover bytes with LDRB and STRB.
7027 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7028 // [destOut] = STRB_POST(scratch, destIn, 1)
7029 for (unsigned i = 0; i < BytesLeft; i++) {
7030 unsigned srcOut = MRI.createVirtualRegister(TRC);
7031 unsigned destOut = MRI.createVirtualRegister(TRC);
7032 unsigned scratch = MRI.createVirtualRegister(TRC);
7033 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7034 IsThumb1, IsThumb2);
7035 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7036 IsThumb1, IsThumb2);
7040 MI->eraseFromParent(); // The instruction is gone now.
7044 // Expand the pseudo op to a loop.
7047 // movw varEnd, # --> with thumb2
7049 // ldrcp varEnd, idx --> without thumb2
7050 // fallthrough --> loopMBB
7052 // PHI varPhi, varEnd, varLoop
7053 // PHI srcPhi, src, srcLoop
7054 // PHI destPhi, dst, destLoop
7055 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7056 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7057 // subs varLoop, varPhi, #UnitSize
7059 // fallthrough --> exitMBB
7061 // epilogue to handle left-over bytes
7062 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7063 // [destOut] = STRB_POST(scratch, destLoop, 1)
7064 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7065 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7066 MF->insert(It, loopMBB);
7067 MF->insert(It, exitMBB);
7069 // Transfer the remainder of BB and its successor edges to exitMBB.
7070 exitMBB->splice(exitMBB->begin(), BB,
7071 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7072 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7074 // Load an immediate to varEnd.
7075 unsigned varEnd = MRI.createVirtualRegister(TRC);
7077 unsigned Vtmp = varEnd;
7078 if ((LoopSize & 0xFFFF0000) != 0)
7079 Vtmp = MRI.createVirtualRegister(TRC);
7080 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7081 .addImm(LoopSize & 0xFFFF));
7083 if ((LoopSize & 0xFFFF0000) != 0)
7084 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7085 .addReg(Vtmp).addImm(LoopSize >> 16));
7087 MachineConstantPool *ConstantPool = MF->getConstantPool();
7088 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7089 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7091 // MachineConstantPool wants an explicit alignment.
7092 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7094 Align = getDataLayout()->getTypeAllocSize(C->getType());
7095 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7098 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7099 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7101 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7102 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7104 BB->addSuccessor(loopMBB);
7106 // Generate the loop body:
7107 // varPhi = PHI(varLoop, varEnd)
7108 // srcPhi = PHI(srcLoop, src)
7109 // destPhi = PHI(destLoop, dst)
7110 MachineBasicBlock *entryBB = BB;
7112 unsigned varLoop = MRI.createVirtualRegister(TRC);
7113 unsigned varPhi = MRI.createVirtualRegister(TRC);
7114 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7115 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7116 unsigned destLoop = MRI.createVirtualRegister(TRC);
7117 unsigned destPhi = MRI.createVirtualRegister(TRC);
7119 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7120 .addReg(varLoop).addMBB(loopMBB)
7121 .addReg(varEnd).addMBB(entryBB);
7122 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7123 .addReg(srcLoop).addMBB(loopMBB)
7124 .addReg(src).addMBB(entryBB);
7125 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7126 .addReg(destLoop).addMBB(loopMBB)
7127 .addReg(dest).addMBB(entryBB);
7129 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7130 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7131 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7132 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7133 IsThumb1, IsThumb2);
7134 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7135 IsThumb1, IsThumb2);
7137 // Decrement loop variable by UnitSize.
7139 MachineInstrBuilder MIB =
7140 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7141 MIB = AddDefaultT1CC(MIB);
7142 MIB.addReg(varPhi).addImm(UnitSize);
7143 AddDefaultPred(MIB);
7145 MachineInstrBuilder MIB =
7146 BuildMI(*BB, BB->end(), dl,
7147 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7148 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7149 MIB->getOperand(5).setReg(ARM::CPSR);
7150 MIB->getOperand(5).setIsDef(true);
7152 BuildMI(*BB, BB->end(), dl,
7153 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7154 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7156 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7157 BB->addSuccessor(loopMBB);
7158 BB->addSuccessor(exitMBB);
7160 // Add epilogue to handle BytesLeft.
7162 MachineInstr *StartOfExit = exitMBB->begin();
7164 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7165 // [destOut] = STRB_POST(scratch, destLoop, 1)
7166 unsigned srcIn = srcLoop;
7167 unsigned destIn = destLoop;
7168 for (unsigned i = 0; i < BytesLeft; i++) {
7169 unsigned srcOut = MRI.createVirtualRegister(TRC);
7170 unsigned destOut = MRI.createVirtualRegister(TRC);
7171 unsigned scratch = MRI.createVirtualRegister(TRC);
7172 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7173 IsThumb1, IsThumb2);
7174 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7175 IsThumb1, IsThumb2);
7180 MI->eraseFromParent(); // The instruction is gone now.
7185 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7186 MachineBasicBlock *MBB) const {
7187 const TargetMachine &TM = getTargetMachine();
7188 const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7189 DebugLoc DL = MI->getDebugLoc();
7191 assert(Subtarget->isTargetWindows() &&
7192 "__chkstk is only supported on Windows");
7193 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7195 // __chkstk takes the number of words to allocate on the stack in R4, and
7196 // returns the stack adjustment in number of bytes in R4. This will not
7197 // clober any other registers (other than the obvious lr).
7199 // Although, technically, IP should be considered a register which may be
7200 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7201 // thumb-2 environment, so there is no interworking required. As a result, we
7202 // do not expect a veneer to be emitted by the linker, clobbering IP.
7204 // Each module receives its own copy of __chkstk, so no import thunk is
7205 // required, again, ensuring that IP is not clobbered.
7207 // Finally, although some linkers may theoretically provide a trampoline for
7208 // out of range calls (which is quite common due to a 32M range limitation of
7209 // branches for Thumb), we can generate the long-call version via
7210 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7213 switch (TM.getCodeModel()) {
7214 case CodeModel::Small:
7215 case CodeModel::Medium:
7216 case CodeModel::Default:
7217 case CodeModel::Kernel:
7218 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7219 .addImm((unsigned)ARMCC::AL).addReg(0)
7220 .addExternalSymbol("__chkstk")
7221 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7222 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7223 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7225 case CodeModel::Large:
7226 case CodeModel::JITDefault: {
7227 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7228 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7230 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7231 .addExternalSymbol("__chkstk");
7232 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7233 .addImm((unsigned)ARMCC::AL).addReg(0)
7234 .addReg(Reg, RegState::Kill)
7235 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7236 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7237 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7242 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7244 .addReg(ARM::SP).addReg(ARM::R4)));
7246 MI->eraseFromParent();
7251 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7252 MachineBasicBlock *BB) const {
7253 const TargetInstrInfo *TII =
7254 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7255 DebugLoc dl = MI->getDebugLoc();
7256 bool isThumb2 = Subtarget->isThumb2();
7257 switch (MI->getOpcode()) {
7260 llvm_unreachable("Unexpected instr type to insert");
7262 // The Thumb2 pre-indexed stores have the same MI operands, they just
7263 // define them differently in the .td files from the isel patterns, so
7264 // they need pseudos.
7265 case ARM::t2STR_preidx:
7266 MI->setDesc(TII->get(ARM::t2STR_PRE));
7268 case ARM::t2STRB_preidx:
7269 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7271 case ARM::t2STRH_preidx:
7272 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7275 case ARM::STRi_preidx:
7276 case ARM::STRBi_preidx: {
7277 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7278 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7279 // Decode the offset.
7280 unsigned Offset = MI->getOperand(4).getImm();
7281 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7282 Offset = ARM_AM::getAM2Offset(Offset);
7286 MachineMemOperand *MMO = *MI->memoperands_begin();
7287 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7288 .addOperand(MI->getOperand(0)) // Rn_wb
7289 .addOperand(MI->getOperand(1)) // Rt
7290 .addOperand(MI->getOperand(2)) // Rn
7291 .addImm(Offset) // offset (skip GPR==zero_reg)
7292 .addOperand(MI->getOperand(5)) // pred
7293 .addOperand(MI->getOperand(6))
7294 .addMemOperand(MMO);
7295 MI->eraseFromParent();
7298 case ARM::STRr_preidx:
7299 case ARM::STRBr_preidx:
7300 case ARM::STRH_preidx: {
7302 switch (MI->getOpcode()) {
7303 default: llvm_unreachable("unexpected opcode!");
7304 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7305 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7306 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7308 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7309 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7310 MIB.addOperand(MI->getOperand(i));
7311 MI->eraseFromParent();
7315 case ARM::tMOVCCr_pseudo: {
7316 // To "insert" a SELECT_CC instruction, we actually have to insert the
7317 // diamond control-flow pattern. The incoming instruction knows the
7318 // destination vreg to set, the condition code register to branch on, the
7319 // true/false values to select between, and a branch opcode to use.
7320 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7321 MachineFunction::iterator It = BB;
7327 // cmpTY ccX, r1, r2
7329 // fallthrough --> copy0MBB
7330 MachineBasicBlock *thisMBB = BB;
7331 MachineFunction *F = BB->getParent();
7332 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7333 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7334 F->insert(It, copy0MBB);
7335 F->insert(It, sinkMBB);
7337 // Transfer the remainder of BB and its successor edges to sinkMBB.
7338 sinkMBB->splice(sinkMBB->begin(), BB,
7339 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7340 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7342 BB->addSuccessor(copy0MBB);
7343 BB->addSuccessor(sinkMBB);
7345 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7346 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7349 // %FalseValue = ...
7350 // # fallthrough to sinkMBB
7353 // Update machine-CFG edges
7354 BB->addSuccessor(sinkMBB);
7357 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7360 BuildMI(*BB, BB->begin(), dl,
7361 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7362 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7363 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7365 MI->eraseFromParent(); // The pseudo instruction is gone now.
7370 case ARM::BCCZi64: {
7371 // If there is an unconditional branch to the other successor, remove it.
7372 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7374 // Compare both parts that make up the double comparison separately for
7376 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7378 unsigned LHS1 = MI->getOperand(1).getReg();
7379 unsigned LHS2 = MI->getOperand(2).getReg();
7381 AddDefaultPred(BuildMI(BB, dl,
7382 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7383 .addReg(LHS1).addImm(0));
7384 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7385 .addReg(LHS2).addImm(0)
7386 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7388 unsigned RHS1 = MI->getOperand(3).getReg();
7389 unsigned RHS2 = MI->getOperand(4).getReg();
7390 AddDefaultPred(BuildMI(BB, dl,
7391 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7392 .addReg(LHS1).addReg(RHS1));
7393 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7394 .addReg(LHS2).addReg(RHS2)
7395 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7398 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7399 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7400 if (MI->getOperand(0).getImm() == ARMCC::NE)
7401 std::swap(destMBB, exitMBB);
7403 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7404 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7406 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7408 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7410 MI->eraseFromParent(); // The pseudo instruction is gone now.
7414 case ARM::Int_eh_sjlj_setjmp:
7415 case ARM::Int_eh_sjlj_setjmp_nofp:
7416 case ARM::tInt_eh_sjlj_setjmp:
7417 case ARM::t2Int_eh_sjlj_setjmp:
7418 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7419 EmitSjLjDispatchBlock(MI, BB);
7424 // To insert an ABS instruction, we have to insert the
7425 // diamond control-flow pattern. The incoming instruction knows the
7426 // source vreg to test against 0, the destination vreg to set,
7427 // the condition code register to branch on, the
7428 // true/false values to select between, and a branch opcode to use.
7433 // BCC (branch to SinkBB if V0 >= 0)
7434 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7435 // SinkBB: V1 = PHI(V2, V3)
7436 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7437 MachineFunction::iterator BBI = BB;
7439 MachineFunction *Fn = BB->getParent();
7440 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7441 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7442 Fn->insert(BBI, RSBBB);
7443 Fn->insert(BBI, SinkBB);
7445 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7446 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7447 bool isThumb2 = Subtarget->isThumb2();
7448 MachineRegisterInfo &MRI = Fn->getRegInfo();
7449 // In Thumb mode S must not be specified if source register is the SP or
7450 // PC and if destination register is the SP, so restrict register class
7451 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7452 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7453 (const TargetRegisterClass*)&ARM::GPRRegClass);
7455 // Transfer the remainder of BB and its successor edges to sinkMBB.
7456 SinkBB->splice(SinkBB->begin(), BB,
7457 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7458 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7460 BB->addSuccessor(RSBBB);
7461 BB->addSuccessor(SinkBB);
7463 // fall through to SinkMBB
7464 RSBBB->addSuccessor(SinkBB);
7466 // insert a cmp at the end of BB
7467 AddDefaultPred(BuildMI(BB, dl,
7468 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7469 .addReg(ABSSrcReg).addImm(0));
7471 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7473 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7474 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7476 // insert rsbri in RSBBB
7477 // Note: BCC and rsbri will be converted into predicated rsbmi
7478 // by if-conversion pass
7479 BuildMI(*RSBBB, RSBBB->begin(), dl,
7480 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7481 .addReg(ABSSrcReg, RegState::Kill)
7482 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7484 // insert PHI in SinkBB,
7485 // reuse ABSDstReg to not change uses of ABS instruction
7486 BuildMI(*SinkBB, SinkBB->begin(), dl,
7487 TII->get(ARM::PHI), ABSDstReg)
7488 .addReg(NewRsbDstReg).addMBB(RSBBB)
7489 .addReg(ABSSrcReg).addMBB(BB);
7491 // remove ABS instruction
7492 MI->eraseFromParent();
7494 // return last added BB
7497 case ARM::COPY_STRUCT_BYVAL_I32:
7499 return EmitStructByval(MI, BB);
7500 case ARM::WIN__CHKSTK:
7501 return EmitLowered__chkstk(MI, BB);
7505 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7506 SDNode *Node) const {
7507 if (!MI->hasPostISelHook()) {
7508 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7509 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7513 const MCInstrDesc *MCID = &MI->getDesc();
7514 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7515 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7516 // operand is still set to noreg. If needed, set the optional operand's
7517 // register to CPSR, and remove the redundant implicit def.
7519 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7521 // Rename pseudo opcodes.
7522 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7524 const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7525 getTargetMachine().getSubtargetImpl()->getInstrInfo());
7526 MCID = &TII->get(NewOpc);
7528 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7529 "converted opcode should be the same except for cc_out");
7533 // Add the optional cc_out operand
7534 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7536 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7538 // Any ARM instruction that sets the 's' bit should specify an optional
7539 // "cc_out" operand in the last operand position.
7540 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7541 assert(!NewOpc && "Optional cc_out operand required");
7544 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7545 // since we already have an optional CPSR def.
7546 bool definesCPSR = false;
7547 bool deadCPSR = false;
7548 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7550 const MachineOperand &MO = MI->getOperand(i);
7551 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7555 MI->RemoveOperand(i);
7560 assert(!NewOpc && "Optional cc_out operand required");
7563 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7565 assert(!MI->getOperand(ccOutIdx).getReg() &&
7566 "expect uninitialized optional cc_out operand");
7570 // If this instruction was defined with an optional CPSR def and its dag node
7571 // had a live implicit CPSR def, then activate the optional CPSR def.
7572 MachineOperand &MO = MI->getOperand(ccOutIdx);
7573 MO.setReg(ARM::CPSR);
7577 //===----------------------------------------------------------------------===//
7578 // ARM Optimization Hooks
7579 //===----------------------------------------------------------------------===//
7581 // Helper function that checks if N is a null or all ones constant.
7582 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7583 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7586 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7589 // Return true if N is conditionally 0 or all ones.
7590 // Detects these expressions where cc is an i1 value:
7592 // (select cc 0, y) [AllOnes=0]
7593 // (select cc y, 0) [AllOnes=0]
7594 // (zext cc) [AllOnes=0]
7595 // (sext cc) [AllOnes=0/1]
7596 // (select cc -1, y) [AllOnes=1]
7597 // (select cc y, -1) [AllOnes=1]
7599 // Invert is set when N is the null/all ones constant when CC is false.
7600 // OtherOp is set to the alternative value of N.
7601 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7602 SDValue &CC, bool &Invert,
7604 SelectionDAG &DAG) {
7605 switch (N->getOpcode()) {
7606 default: return false;
7608 CC = N->getOperand(0);
7609 SDValue N1 = N->getOperand(1);
7610 SDValue N2 = N->getOperand(2);
7611 if (isZeroOrAllOnes(N1, AllOnes)) {
7616 if (isZeroOrAllOnes(N2, AllOnes)) {
7623 case ISD::ZERO_EXTEND:
7624 // (zext cc) can never be the all ones value.
7628 case ISD::SIGN_EXTEND: {
7629 EVT VT = N->getValueType(0);
7630 CC = N->getOperand(0);
7631 if (CC.getValueType() != MVT::i1)
7635 // When looking for an AllOnes constant, N is an sext, and the 'other'
7637 OtherOp = DAG.getConstant(0, VT);
7638 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7639 // When looking for a 0 constant, N can be zext or sext.
7640 OtherOp = DAG.getConstant(1, VT);
7642 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7648 // Combine a constant select operand into its use:
7650 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7651 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7652 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7653 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7654 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7656 // The transform is rejected if the select doesn't have a constant operand that
7657 // is null, or all ones when AllOnes is set.
7659 // Also recognize sext/zext from i1:
7661 // (add (zext cc), x) -> (select cc (add x, 1), x)
7662 // (add (sext cc), x) -> (select cc (add x, -1), x)
7664 // These transformations eventually create predicated instructions.
7666 // @param N The node to transform.
7667 // @param Slct The N operand that is a select.
7668 // @param OtherOp The other N operand (x above).
7669 // @param DCI Context.
7670 // @param AllOnes Require the select constant to be all ones instead of null.
7671 // @returns The new node, or SDValue() on failure.
7673 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7674 TargetLowering::DAGCombinerInfo &DCI,
7675 bool AllOnes = false) {
7676 SelectionDAG &DAG = DCI.DAG;
7677 EVT VT = N->getValueType(0);
7678 SDValue NonConstantVal;
7681 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7682 NonConstantVal, DAG))
7685 // Slct is now know to be the desired identity constant when CC is true.
7686 SDValue TrueVal = OtherOp;
7687 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7688 OtherOp, NonConstantVal);
7689 // Unless SwapSelectOps says CC should be false.
7691 std::swap(TrueVal, FalseVal);
7693 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7694 CCOp, TrueVal, FalseVal);
7697 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7699 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7700 TargetLowering::DAGCombinerInfo &DCI) {
7701 SDValue N0 = N->getOperand(0);
7702 SDValue N1 = N->getOperand(1);
7703 if (N0.getNode()->hasOneUse()) {
7704 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7705 if (Result.getNode())
7708 if (N1.getNode()->hasOneUse()) {
7709 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7710 if (Result.getNode())
7716 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7717 // (only after legalization).
7718 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7719 TargetLowering::DAGCombinerInfo &DCI,
7720 const ARMSubtarget *Subtarget) {
7722 // Only perform optimization if after legalize, and if NEON is available. We
7723 // also expected both operands to be BUILD_VECTORs.
7724 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7725 || N0.getOpcode() != ISD::BUILD_VECTOR
7726 || N1.getOpcode() != ISD::BUILD_VECTOR)
7729 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7730 EVT VT = N->getValueType(0);
7731 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7734 // Check that the vector operands are of the right form.
7735 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7736 // operands, where N is the size of the formed vector.
7737 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7738 // index such that we have a pair wise add pattern.
7740 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7741 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7743 SDValue Vec = N0->getOperand(0)->getOperand(0);
7744 SDNode *V = Vec.getNode();
7745 unsigned nextIndex = 0;
7747 // For each operands to the ADD which are BUILD_VECTORs,
7748 // check to see if each of their operands are an EXTRACT_VECTOR with
7749 // the same vector and appropriate index.
7750 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7751 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7752 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7754 SDValue ExtVec0 = N0->getOperand(i);
7755 SDValue ExtVec1 = N1->getOperand(i);
7757 // First operand is the vector, verify its the same.
7758 if (V != ExtVec0->getOperand(0).getNode() ||
7759 V != ExtVec1->getOperand(0).getNode())
7762 // Second is the constant, verify its correct.
7763 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7764 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7766 // For the constant, we want to see all the even or all the odd.
7767 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7768 || C1->getZExtValue() != nextIndex+1)
7777 // Create VPADDL node.
7778 SelectionDAG &DAG = DCI.DAG;
7779 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7781 // Build operand list.
7782 SmallVector<SDValue, 8> Ops;
7783 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7784 TLI.getPointerTy()));
7786 // Input is the vector.
7789 // Get widened type and narrowed type.
7791 unsigned numElem = VT.getVectorNumElements();
7793 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7794 switch (inputLaneType.getSimpleVT().SimpleTy) {
7795 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7796 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7797 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7799 llvm_unreachable("Invalid vector element type for padd optimization.");
7802 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7803 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7804 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7807 static SDValue findMUL_LOHI(SDValue V) {
7808 if (V->getOpcode() == ISD::UMUL_LOHI ||
7809 V->getOpcode() == ISD::SMUL_LOHI)
7814 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7815 TargetLowering::DAGCombinerInfo &DCI,
7816 const ARMSubtarget *Subtarget) {
7818 if (Subtarget->isThumb1Only()) return SDValue();
7820 // Only perform the checks after legalize when the pattern is available.
7821 if (DCI.isBeforeLegalize()) return SDValue();
7823 // Look for multiply add opportunities.
7824 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7825 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7826 // a glue link from the first add to the second add.
7827 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7828 // a S/UMLAL instruction.
7831 // \ / \ [no multiline comment]
7837 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7838 SDValue AddcOp0 = AddcNode->getOperand(0);
7839 SDValue AddcOp1 = AddcNode->getOperand(1);
7841 // Check if the two operands are from the same mul_lohi node.
7842 if (AddcOp0.getNode() == AddcOp1.getNode())
7845 assert(AddcNode->getNumValues() == 2 &&
7846 AddcNode->getValueType(0) == MVT::i32 &&
7847 "Expect ADDC with two result values. First: i32");
7849 // Check that we have a glued ADDC node.
7850 if (AddcNode->getValueType(1) != MVT::Glue)
7853 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7854 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7855 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7856 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7857 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7860 // Look for the glued ADDE.
7861 SDNode* AddeNode = AddcNode->getGluedUser();
7865 // Make sure it is really an ADDE.
7866 if (AddeNode->getOpcode() != ISD::ADDE)
7869 assert(AddeNode->getNumOperands() == 3 &&
7870 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7871 "ADDE node has the wrong inputs");
7873 // Check for the triangle shape.
7874 SDValue AddeOp0 = AddeNode->getOperand(0);
7875 SDValue AddeOp1 = AddeNode->getOperand(1);
7877 // Make sure that the ADDE operands are not coming from the same node.
7878 if (AddeOp0.getNode() == AddeOp1.getNode())
7881 // Find the MUL_LOHI node walking up ADDE's operands.
7882 bool IsLeftOperandMUL = false;
7883 SDValue MULOp = findMUL_LOHI(AddeOp0);
7884 if (MULOp == SDValue())
7885 MULOp = findMUL_LOHI(AddeOp1);
7887 IsLeftOperandMUL = true;
7888 if (MULOp == SDValue())
7891 // Figure out the right opcode.
7892 unsigned Opc = MULOp->getOpcode();
7893 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7895 // Figure out the high and low input values to the MLAL node.
7896 SDValue* HiMul = &MULOp;
7897 SDValue* HiAdd = nullptr;
7898 SDValue* LoMul = nullptr;
7899 SDValue* LowAdd = nullptr;
7901 if (IsLeftOperandMUL)
7907 if (AddcOp0->getOpcode() == Opc) {
7911 if (AddcOp1->getOpcode() == Opc) {
7919 if (LoMul->getNode() != HiMul->getNode())
7922 // Create the merged node.
7923 SelectionDAG &DAG = DCI.DAG;
7925 // Build operand list.
7926 SmallVector<SDValue, 8> Ops;
7927 Ops.push_back(LoMul->getOperand(0));
7928 Ops.push_back(LoMul->getOperand(1));
7929 Ops.push_back(*LowAdd);
7930 Ops.push_back(*HiAdd);
7932 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7933 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7935 // Replace the ADDs' nodes uses by the MLA node's values.
7936 SDValue HiMLALResult(MLALNode.getNode(), 1);
7937 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7939 SDValue LoMLALResult(MLALNode.getNode(), 0);
7940 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7942 // Return original node to notify the driver to stop replacing.
7943 SDValue resNode(AddcNode, 0);
7947 /// PerformADDCCombine - Target-specific dag combine transform from
7948 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7949 static SDValue PerformADDCCombine(SDNode *N,
7950 TargetLowering::DAGCombinerInfo &DCI,
7951 const ARMSubtarget *Subtarget) {
7953 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7957 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7958 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7959 /// called with the default operands, and if that fails, with commuted
7961 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7962 TargetLowering::DAGCombinerInfo &DCI,
7963 const ARMSubtarget *Subtarget){
7965 // Attempt to create vpaddl for this add.
7966 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7967 if (Result.getNode())
7970 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7971 if (N0.getNode()->hasOneUse()) {
7972 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7973 if (Result.getNode()) return Result;
7978 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7980 static SDValue PerformADDCombine(SDNode *N,
7981 TargetLowering::DAGCombinerInfo &DCI,
7982 const ARMSubtarget *Subtarget) {
7983 SDValue N0 = N->getOperand(0);
7984 SDValue N1 = N->getOperand(1);
7986 // First try with the default operand order.
7987 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7988 if (Result.getNode())
7991 // If that didn't work, try again with the operands commuted.
7992 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7995 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7997 static SDValue PerformSUBCombine(SDNode *N,
7998 TargetLowering::DAGCombinerInfo &DCI) {
7999 SDValue N0 = N->getOperand(0);
8000 SDValue N1 = N->getOperand(1);
8002 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8003 if (N1.getNode()->hasOneUse()) {
8004 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8005 if (Result.getNode()) return Result;
8011 /// PerformVMULCombine
8012 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8013 /// special multiplier accumulator forwarding.
8019 // However, for (A + B) * (A + B),
8026 static SDValue PerformVMULCombine(SDNode *N,
8027 TargetLowering::DAGCombinerInfo &DCI,
8028 const ARMSubtarget *Subtarget) {
8029 if (!Subtarget->hasVMLxForwarding())
8032 SelectionDAG &DAG = DCI.DAG;
8033 SDValue N0 = N->getOperand(0);
8034 SDValue N1 = N->getOperand(1);
8035 unsigned Opcode = N0.getOpcode();
8036 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8037 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8038 Opcode = N1.getOpcode();
8039 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8040 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8048 EVT VT = N->getValueType(0);
8050 SDValue N00 = N0->getOperand(0);
8051 SDValue N01 = N0->getOperand(1);
8052 return DAG.getNode(Opcode, DL, VT,
8053 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8054 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8057 static SDValue PerformMULCombine(SDNode *N,
8058 TargetLowering::DAGCombinerInfo &DCI,
8059 const ARMSubtarget *Subtarget) {
8060 SelectionDAG &DAG = DCI.DAG;
8062 if (Subtarget->isThumb1Only())
8065 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8068 EVT VT = N->getValueType(0);
8069 if (VT.is64BitVector() || VT.is128BitVector())
8070 return PerformVMULCombine(N, DCI, Subtarget);
8074 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8078 int64_t MulAmt = C->getSExtValue();
8079 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8081 ShiftAmt = ShiftAmt & (32 - 1);
8082 SDValue V = N->getOperand(0);
8086 MulAmt >>= ShiftAmt;
8089 if (isPowerOf2_32(MulAmt - 1)) {
8090 // (mul x, 2^N + 1) => (add (shl x, N), x)
8091 Res = DAG.getNode(ISD::ADD, DL, VT,
8093 DAG.getNode(ISD::SHL, DL, VT,
8095 DAG.getConstant(Log2_32(MulAmt - 1),
8097 } else if (isPowerOf2_32(MulAmt + 1)) {
8098 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8099 Res = DAG.getNode(ISD::SUB, DL, VT,
8100 DAG.getNode(ISD::SHL, DL, VT,
8102 DAG.getConstant(Log2_32(MulAmt + 1),
8108 uint64_t MulAmtAbs = -MulAmt;
8109 if (isPowerOf2_32(MulAmtAbs + 1)) {
8110 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8111 Res = DAG.getNode(ISD::SUB, DL, VT,
8113 DAG.getNode(ISD::SHL, DL, VT,
8115 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8117 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8118 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8119 Res = DAG.getNode(ISD::ADD, DL, VT,
8121 DAG.getNode(ISD::SHL, DL, VT,
8123 DAG.getConstant(Log2_32(MulAmtAbs-1),
8125 Res = DAG.getNode(ISD::SUB, DL, VT,
8126 DAG.getConstant(0, MVT::i32),Res);
8133 Res = DAG.getNode(ISD::SHL, DL, VT,
8134 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8136 // Do not add new nodes to DAG combiner worklist.
8137 DCI.CombineTo(N, Res, false);
8141 static SDValue PerformANDCombine(SDNode *N,
8142 TargetLowering::DAGCombinerInfo &DCI,
8143 const ARMSubtarget *Subtarget) {
8145 // Attempt to use immediate-form VBIC
8146 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8148 EVT VT = N->getValueType(0);
8149 SelectionDAG &DAG = DCI.DAG;
8151 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8154 APInt SplatBits, SplatUndef;
8155 unsigned SplatBitSize;
8158 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8159 if (SplatBitSize <= 64) {
8161 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8162 SplatUndef.getZExtValue(), SplatBitSize,
8163 DAG, VbicVT, VT.is128BitVector(),
8165 if (Val.getNode()) {
8167 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8168 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8169 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8174 if (!Subtarget->isThumb1Only()) {
8175 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8176 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8177 if (Result.getNode())
8184 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8185 static SDValue PerformORCombine(SDNode *N,
8186 TargetLowering::DAGCombinerInfo &DCI,
8187 const ARMSubtarget *Subtarget) {
8188 // Attempt to use immediate-form VORR
8189 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8191 EVT VT = N->getValueType(0);
8192 SelectionDAG &DAG = DCI.DAG;
8194 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8197 APInt SplatBits, SplatUndef;
8198 unsigned SplatBitSize;
8200 if (BVN && Subtarget->hasNEON() &&
8201 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8202 if (SplatBitSize <= 64) {
8204 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8205 SplatUndef.getZExtValue(), SplatBitSize,
8206 DAG, VorrVT, VT.is128BitVector(),
8208 if (Val.getNode()) {
8210 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8211 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8212 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8217 if (!Subtarget->isThumb1Only()) {
8218 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8219 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8220 if (Result.getNode())
8224 // The code below optimizes (or (and X, Y), Z).
8225 // The AND operand needs to have a single user to make these optimizations
8227 SDValue N0 = N->getOperand(0);
8228 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8230 SDValue N1 = N->getOperand(1);
8232 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8233 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8234 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8236 unsigned SplatBitSize;
8239 APInt SplatBits0, SplatBits1;
8240 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8241 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8242 // Ensure that the second operand of both ands are constants
8243 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8244 HasAnyUndefs) && !HasAnyUndefs) {
8245 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8246 HasAnyUndefs) && !HasAnyUndefs) {
8247 // Ensure that the bit width of the constants are the same and that
8248 // the splat arguments are logical inverses as per the pattern we
8249 // are trying to simplify.
8250 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8251 SplatBits0 == ~SplatBits1) {
8252 // Canonicalize the vector type to make instruction selection
8254 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8255 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8259 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8265 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8268 // BFI is only available on V6T2+
8269 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8273 // 1) or (and A, mask), val => ARMbfi A, val, mask
8274 // iff (val & mask) == val
8276 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8277 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8278 // && mask == ~mask2
8279 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8280 // && ~mask == mask2
8281 // (i.e., copy a bitfield value into another bitfield of the same width)
8286 SDValue N00 = N0.getOperand(0);
8288 // The value and the mask need to be constants so we can verify this is
8289 // actually a bitfield set. If the mask is 0xffff, we can do better
8290 // via a movt instruction, so don't use BFI in that case.
8291 SDValue MaskOp = N0.getOperand(1);
8292 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8295 unsigned Mask = MaskC->getZExtValue();
8299 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8300 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8302 unsigned Val = N1C->getZExtValue();
8303 if ((Val & ~Mask) != Val)
8306 if (ARM::isBitFieldInvertedMask(Mask)) {
8307 Val >>= countTrailingZeros(~Mask);
8309 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8310 DAG.getConstant(Val, MVT::i32),
8311 DAG.getConstant(Mask, MVT::i32));
8313 // Do not add new nodes to DAG combiner worklist.
8314 DCI.CombineTo(N, Res, false);
8317 } else if (N1.getOpcode() == ISD::AND) {
8318 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8319 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8322 unsigned Mask2 = N11C->getZExtValue();
8324 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8326 if (ARM::isBitFieldInvertedMask(Mask) &&
8328 // The pack halfword instruction works better for masks that fit it,
8329 // so use that when it's available.
8330 if (Subtarget->hasT2ExtractPack() &&
8331 (Mask == 0xffff || Mask == 0xffff0000))
8334 unsigned amt = countTrailingZeros(Mask2);
8335 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8336 DAG.getConstant(amt, MVT::i32));
8337 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8338 DAG.getConstant(Mask, MVT::i32));
8339 // Do not add new nodes to DAG combiner worklist.
8340 DCI.CombineTo(N, Res, false);
8342 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8344 // The pack halfword instruction works better for masks that fit it,
8345 // so use that when it's available.
8346 if (Subtarget->hasT2ExtractPack() &&
8347 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8350 unsigned lsb = countTrailingZeros(Mask);
8351 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8352 DAG.getConstant(lsb, MVT::i32));
8353 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8354 DAG.getConstant(Mask2, MVT::i32));
8355 // Do not add new nodes to DAG combiner worklist.
8356 DCI.CombineTo(N, Res, false);
8361 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8362 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8363 ARM::isBitFieldInvertedMask(~Mask)) {
8364 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8365 // where lsb(mask) == #shamt and masked bits of B are known zero.
8366 SDValue ShAmt = N00.getOperand(1);
8367 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8368 unsigned LSB = countTrailingZeros(Mask);
8372 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8373 DAG.getConstant(~Mask, MVT::i32));
8375 // Do not add new nodes to DAG combiner worklist.
8376 DCI.CombineTo(N, Res, false);
8382 static SDValue PerformXORCombine(SDNode *N,
8383 TargetLowering::DAGCombinerInfo &DCI,
8384 const ARMSubtarget *Subtarget) {
8385 EVT VT = N->getValueType(0);
8386 SelectionDAG &DAG = DCI.DAG;
8388 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8391 if (!Subtarget->isThumb1Only()) {
8392 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8393 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8394 if (Result.getNode())
8401 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8402 /// the bits being cleared by the AND are not demanded by the BFI.
8403 static SDValue PerformBFICombine(SDNode *N,
8404 TargetLowering::DAGCombinerInfo &DCI) {
8405 SDValue N1 = N->getOperand(1);
8406 if (N1.getOpcode() == ISD::AND) {
8407 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8410 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8411 unsigned LSB = countTrailingZeros(~InvMask);
8412 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8413 unsigned Mask = (1 << Width)-1;
8414 unsigned Mask2 = N11C->getZExtValue();
8415 if ((Mask & (~Mask2)) == 0)
8416 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8417 N->getOperand(0), N1.getOperand(0),
8423 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8424 /// ARMISD::VMOVRRD.
8425 static SDValue PerformVMOVRRDCombine(SDNode *N,
8426 TargetLowering::DAGCombinerInfo &DCI) {
8427 // vmovrrd(vmovdrr x, y) -> x,y
8428 SDValue InDouble = N->getOperand(0);
8429 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8430 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8432 // vmovrrd(load f64) -> (load i32), (load i32)
8433 SDNode *InNode = InDouble.getNode();
8434 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8435 InNode->getValueType(0) == MVT::f64 &&
8436 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8437 !cast<LoadSDNode>(InNode)->isVolatile()) {
8438 // TODO: Should this be done for non-FrameIndex operands?
8439 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8441 SelectionDAG &DAG = DCI.DAG;
8443 SDValue BasePtr = LD->getBasePtr();
8444 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8445 LD->getPointerInfo(), LD->isVolatile(),
8446 LD->isNonTemporal(), LD->isInvariant(),
8447 LD->getAlignment());
8449 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8450 DAG.getConstant(4, MVT::i32));
8451 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8452 LD->getPointerInfo(), LD->isVolatile(),
8453 LD->isNonTemporal(), LD->isInvariant(),
8454 std::min(4U, LD->getAlignment() / 2));
8456 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8457 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8458 std::swap (NewLD1, NewLD2);
8459 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8466 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8467 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8468 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8469 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8470 SDValue Op0 = N->getOperand(0);
8471 SDValue Op1 = N->getOperand(1);
8472 if (Op0.getOpcode() == ISD::BITCAST)
8473 Op0 = Op0.getOperand(0);
8474 if (Op1.getOpcode() == ISD::BITCAST)
8475 Op1 = Op1.getOperand(0);
8476 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8477 Op0.getNode() == Op1.getNode() &&
8478 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8479 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8480 N->getValueType(0), Op0.getOperand(0));
8484 /// PerformSTORECombine - Target-specific dag combine xforms for
8486 static SDValue PerformSTORECombine(SDNode *N,
8487 TargetLowering::DAGCombinerInfo &DCI) {
8488 StoreSDNode *St = cast<StoreSDNode>(N);
8489 if (St->isVolatile())
8492 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8493 // pack all of the elements in one place. Next, store to memory in fewer
8495 SDValue StVal = St->getValue();
8496 EVT VT = StVal.getValueType();
8497 if (St->isTruncatingStore() && VT.isVector()) {
8498 SelectionDAG &DAG = DCI.DAG;
8499 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8500 EVT StVT = St->getMemoryVT();
8501 unsigned NumElems = VT.getVectorNumElements();
8502 assert(StVT != VT && "Cannot truncate to the same type");
8503 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8504 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8506 // From, To sizes and ElemCount must be pow of two
8507 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8509 // We are going to use the original vector elt for storing.
8510 // Accumulated smaller vector elements must be a multiple of the store size.
8511 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8513 unsigned SizeRatio = FromEltSz / ToEltSz;
8514 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8516 // Create a type on which we perform the shuffle.
8517 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8518 NumElems*SizeRatio);
8519 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8522 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8523 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8524 for (unsigned i = 0; i < NumElems; ++i)
8525 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8527 // Can't shuffle using an illegal type.
8528 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8530 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8531 DAG.getUNDEF(WideVec.getValueType()),
8533 // At this point all of the data is stored at the bottom of the
8534 // register. We now need to save it to mem.
8536 // Find the largest store unit
8537 MVT StoreType = MVT::i8;
8538 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8539 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8540 MVT Tp = (MVT::SimpleValueType)tp;
8541 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8544 // Didn't find a legal store type.
8545 if (!TLI.isTypeLegal(StoreType))
8548 // Bitcast the original vector into a vector of store-size units
8549 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8550 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8551 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8552 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8553 SmallVector<SDValue, 8> Chains;
8554 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8555 TLI.getPointerTy());
8556 SDValue BasePtr = St->getBasePtr();
8558 // Perform one or more big stores into memory.
8559 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8560 for (unsigned I = 0; I < E; I++) {
8561 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8562 StoreType, ShuffWide,
8563 DAG.getIntPtrConstant(I));
8564 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8565 St->getPointerInfo(), St->isVolatile(),
8566 St->isNonTemporal(), St->getAlignment());
8567 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8569 Chains.push_back(Ch);
8571 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8574 if (!ISD::isNormalStore(St))
8577 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8578 // ARM stores of arguments in the same cache line.
8579 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8580 StVal.getNode()->hasOneUse()) {
8581 SelectionDAG &DAG = DCI.DAG;
8582 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8584 SDValue BasePtr = St->getBasePtr();
8585 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8586 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8587 BasePtr, St->getPointerInfo(), St->isVolatile(),
8588 St->isNonTemporal(), St->getAlignment());
8590 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8591 DAG.getConstant(4, MVT::i32));
8592 return DAG.getStore(NewST1.getValue(0), DL,
8593 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8594 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8595 St->isNonTemporal(),
8596 std::min(4U, St->getAlignment() / 2));
8599 if (StVal.getValueType() != MVT::i64 ||
8600 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8603 // Bitcast an i64 store extracted from a vector to f64.
8604 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8605 SelectionDAG &DAG = DCI.DAG;
8607 SDValue IntVec = StVal.getOperand(0);
8608 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8609 IntVec.getValueType().getVectorNumElements());
8610 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8611 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8612 Vec, StVal.getOperand(1));
8614 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8615 // Make the DAGCombiner fold the bitcasts.
8616 DCI.AddToWorklist(Vec.getNode());
8617 DCI.AddToWorklist(ExtElt.getNode());
8618 DCI.AddToWorklist(V.getNode());
8619 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8620 St->getPointerInfo(), St->isVolatile(),
8621 St->isNonTemporal(), St->getAlignment(),
8625 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8626 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8627 /// i64 vector to have f64 elements, since the value can then be loaded
8628 /// directly into a VFP register.
8629 static bool hasNormalLoadOperand(SDNode *N) {
8630 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8631 for (unsigned i = 0; i < NumElts; ++i) {
8632 SDNode *Elt = N->getOperand(i).getNode();
8633 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8639 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8640 /// ISD::BUILD_VECTOR.
8641 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8642 TargetLowering::DAGCombinerInfo &DCI){
8643 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8644 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8645 // into a pair of GPRs, which is fine when the value is used as a scalar,
8646 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8647 SelectionDAG &DAG = DCI.DAG;
8648 if (N->getNumOperands() == 2) {
8649 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8654 // Load i64 elements as f64 values so that type legalization does not split
8655 // them up into i32 values.
8656 EVT VT = N->getValueType(0);
8657 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8660 SmallVector<SDValue, 8> Ops;
8661 unsigned NumElts = VT.getVectorNumElements();
8662 for (unsigned i = 0; i < NumElts; ++i) {
8663 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8665 // Make the DAGCombiner fold the bitcast.
8666 DCI.AddToWorklist(V.getNode());
8668 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8669 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8670 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8673 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8675 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8676 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8677 // At that time, we may have inserted bitcasts from integer to float.
8678 // If these bitcasts have survived DAGCombine, change the lowering of this
8679 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8680 // force to use floating point types.
8682 // Make sure we can change the type of the vector.
8683 // This is possible iff:
8684 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8685 // 1.1. Vector is used only once.
8686 // 1.2. Use is a bit convert to an integer type.
8687 // 2. The size of its operands are 32-bits (64-bits are not legal).
8688 EVT VT = N->getValueType(0);
8689 EVT EltVT = VT.getVectorElementType();
8691 // Check 1.1. and 2.
8692 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8695 // By construction, the input type must be float.
8696 assert(EltVT == MVT::f32 && "Unexpected type!");
8699 SDNode *Use = *N->use_begin();
8700 if (Use->getOpcode() != ISD::BITCAST ||
8701 Use->getValueType(0).isFloatingPoint())
8704 // Check profitability.
8705 // Model is, if more than half of the relevant operands are bitcast from
8706 // i32, turn the build_vector into a sequence of insert_vector_elt.
8707 // Relevant operands are everything that is not statically
8708 // (i.e., at compile time) bitcasted.
8709 unsigned NumOfBitCastedElts = 0;
8710 unsigned NumElts = VT.getVectorNumElements();
8711 unsigned NumOfRelevantElts = NumElts;
8712 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8713 SDValue Elt = N->getOperand(Idx);
8714 if (Elt->getOpcode() == ISD::BITCAST) {
8715 // Assume only bit cast to i32 will go away.
8716 if (Elt->getOperand(0).getValueType() == MVT::i32)
8717 ++NumOfBitCastedElts;
8718 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8719 // Constants are statically casted, thus do not count them as
8720 // relevant operands.
8721 --NumOfRelevantElts;
8724 // Check if more than half of the elements require a non-free bitcast.
8725 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8728 SelectionDAG &DAG = DCI.DAG;
8729 // Create the new vector type.
8730 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8731 // Check if the type is legal.
8732 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8733 if (!TLI.isTypeLegal(VecVT))
8737 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8738 // => BITCAST INSERT_VECTOR_ELT
8739 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8741 SDValue Vec = DAG.getUNDEF(VecVT);
8743 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8744 SDValue V = N->getOperand(Idx);
8745 if (V.getOpcode() == ISD::UNDEF)
8747 if (V.getOpcode() == ISD::BITCAST &&
8748 V->getOperand(0).getValueType() == MVT::i32)
8749 // Fold obvious case.
8750 V = V.getOperand(0);
8752 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8753 // Make the DAGCombiner fold the bitcasts.
8754 DCI.AddToWorklist(V.getNode());
8756 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8757 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8759 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8760 // Make the DAGCombiner fold the bitcasts.
8761 DCI.AddToWorklist(Vec.getNode());
8765 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8766 /// ISD::INSERT_VECTOR_ELT.
8767 static SDValue PerformInsertEltCombine(SDNode *N,
8768 TargetLowering::DAGCombinerInfo &DCI) {
8769 // Bitcast an i64 load inserted into a vector to f64.
8770 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8771 EVT VT = N->getValueType(0);
8772 SDNode *Elt = N->getOperand(1).getNode();
8773 if (VT.getVectorElementType() != MVT::i64 ||
8774 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8777 SelectionDAG &DAG = DCI.DAG;
8779 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8780 VT.getVectorNumElements());
8781 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8782 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8783 // Make the DAGCombiner fold the bitcasts.
8784 DCI.AddToWorklist(Vec.getNode());
8785 DCI.AddToWorklist(V.getNode());
8786 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8787 Vec, V, N->getOperand(2));
8788 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8791 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8792 /// ISD::VECTOR_SHUFFLE.
8793 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8794 // The LLVM shufflevector instruction does not require the shuffle mask
8795 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8796 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8797 // operands do not match the mask length, they are extended by concatenating
8798 // them with undef vectors. That is probably the right thing for other
8799 // targets, but for NEON it is better to concatenate two double-register
8800 // size vector operands into a single quad-register size vector. Do that
8801 // transformation here:
8802 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8803 // shuffle(concat(v1, v2), undef)
8804 SDValue Op0 = N->getOperand(0);
8805 SDValue Op1 = N->getOperand(1);
8806 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8807 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8808 Op0.getNumOperands() != 2 ||
8809 Op1.getNumOperands() != 2)
8811 SDValue Concat0Op1 = Op0.getOperand(1);
8812 SDValue Concat1Op1 = Op1.getOperand(1);
8813 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8814 Concat1Op1.getOpcode() != ISD::UNDEF)
8816 // Skip the transformation if any of the types are illegal.
8817 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8818 EVT VT = N->getValueType(0);
8819 if (!TLI.isTypeLegal(VT) ||
8820 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8821 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8824 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8825 Op0.getOperand(0), Op1.getOperand(0));
8826 // Translate the shuffle mask.
8827 SmallVector<int, 16> NewMask;
8828 unsigned NumElts = VT.getVectorNumElements();
8829 unsigned HalfElts = NumElts/2;
8830 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8831 for (unsigned n = 0; n < NumElts; ++n) {
8832 int MaskElt = SVN->getMaskElt(n);
8834 if (MaskElt < (int)HalfElts)
8836 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8837 NewElt = HalfElts + MaskElt - NumElts;
8838 NewMask.push_back(NewElt);
8840 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8841 DAG.getUNDEF(VT), NewMask.data());
8844 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8845 /// NEON load/store intrinsics to merge base address updates.
8846 static SDValue CombineBaseUpdate(SDNode *N,
8847 TargetLowering::DAGCombinerInfo &DCI) {
8848 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8851 SelectionDAG &DAG = DCI.DAG;
8852 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8853 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8854 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8855 SDValue Addr = N->getOperand(AddrOpIdx);
8857 // Search for a use of the address operand that is an increment.
8858 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8859 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8861 if (User->getOpcode() != ISD::ADD ||
8862 UI.getUse().getResNo() != Addr.getResNo())
8865 // Check that the add is independent of the load/store. Otherwise, folding
8866 // it would create a cycle.
8867 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8870 // Find the new opcode for the updating load/store.
8872 bool isLaneOp = false;
8873 unsigned NewOpc = 0;
8874 unsigned NumVecs = 0;
8876 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8878 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8879 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8881 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8883 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8885 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8887 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8888 NumVecs = 2; isLaneOp = true; break;
8889 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8890 NumVecs = 3; isLaneOp = true; break;
8891 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8892 NumVecs = 4; isLaneOp = true; break;
8893 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8894 NumVecs = 1; isLoad = false; break;
8895 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8896 NumVecs = 2; isLoad = false; break;
8897 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8898 NumVecs = 3; isLoad = false; break;
8899 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8900 NumVecs = 4; isLoad = false; break;
8901 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8902 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8903 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8904 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8905 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8906 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8910 switch (N->getOpcode()) {
8911 default: llvm_unreachable("unexpected opcode for Neon base update");
8912 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8913 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8914 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8918 // Find the size of memory referenced by the load/store.
8921 VecTy = N->getValueType(0);
8923 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8924 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8926 NumBytes /= VecTy.getVectorNumElements();
8928 // If the increment is a constant, it must match the memory ref size.
8929 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8930 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8931 uint64_t IncVal = CInc->getZExtValue();
8932 if (IncVal != NumBytes)
8934 } else if (NumBytes >= 3 * 16) {
8935 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8936 // separate instructions that make it harder to use a non-constant update.
8940 // Create the new updating load/store node.
8942 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8944 for (n = 0; n < NumResultVecs; ++n)
8946 Tys[n++] = MVT::i32;
8947 Tys[n] = MVT::Other;
8948 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8949 SmallVector<SDValue, 8> Ops;
8950 Ops.push_back(N->getOperand(0)); // incoming chain
8951 Ops.push_back(N->getOperand(AddrOpIdx));
8953 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8954 Ops.push_back(N->getOperand(i));
8956 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8957 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8958 Ops, MemInt->getMemoryVT(),
8959 MemInt->getMemOperand());
8962 std::vector<SDValue> NewResults;
8963 for (unsigned i = 0; i < NumResultVecs; ++i) {
8964 NewResults.push_back(SDValue(UpdN.getNode(), i));
8966 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8967 DCI.CombineTo(N, NewResults);
8968 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8975 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8976 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8977 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8979 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8980 SelectionDAG &DAG = DCI.DAG;
8981 EVT VT = N->getValueType(0);
8982 // vldN-dup instructions only support 64-bit vectors for N > 1.
8983 if (!VT.is64BitVector())
8986 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8987 SDNode *VLD = N->getOperand(0).getNode();
8988 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8990 unsigned NumVecs = 0;
8991 unsigned NewOpc = 0;
8992 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8993 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8995 NewOpc = ARMISD::VLD2DUP;
8996 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8998 NewOpc = ARMISD::VLD3DUP;
8999 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9001 NewOpc = ARMISD::VLD4DUP;
9006 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9007 // numbers match the load.
9008 unsigned VLDLaneNo =
9009 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9010 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9012 // Ignore uses of the chain result.
9013 if (UI.getUse().getResNo() == NumVecs)
9016 if (User->getOpcode() != ARMISD::VDUPLANE ||
9017 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9021 // Create the vldN-dup node.
9024 for (n = 0; n < NumVecs; ++n)
9026 Tys[n] = MVT::Other;
9027 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9028 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9029 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9030 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9031 Ops, VLDMemInt->getMemoryVT(),
9032 VLDMemInt->getMemOperand());
9035 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9037 unsigned ResNo = UI.getUse().getResNo();
9038 // Ignore uses of the chain result.
9039 if (ResNo == NumVecs)
9042 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9045 // Now the vldN-lane intrinsic is dead except for its chain result.
9046 // Update uses of the chain.
9047 std::vector<SDValue> VLDDupResults;
9048 for (unsigned n = 0; n < NumVecs; ++n)
9049 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9050 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9051 DCI.CombineTo(VLD, VLDDupResults);
9056 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9057 /// ARMISD::VDUPLANE.
9058 static SDValue PerformVDUPLANECombine(SDNode *N,
9059 TargetLowering::DAGCombinerInfo &DCI) {
9060 SDValue Op = N->getOperand(0);
9062 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9063 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9064 if (CombineVLDDUP(N, DCI))
9065 return SDValue(N, 0);
9067 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9068 // redundant. Ignore bit_converts for now; element sizes are checked below.
9069 while (Op.getOpcode() == ISD::BITCAST)
9070 Op = Op.getOperand(0);
9071 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9074 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9075 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9076 // The canonical VMOV for a zero vector uses a 32-bit element size.
9077 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9079 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9081 EVT VT = N->getValueType(0);
9082 if (EltSize > VT.getVectorElementType().getSizeInBits())
9085 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9088 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9089 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9090 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9094 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9096 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9101 APFloat APF = C->getValueAPF();
9102 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9103 != APFloat::opOK || !isExact)
9106 c0 = (I == 0) ? cN : c0;
9107 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9114 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9115 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9116 /// when the VMUL has a constant operand that is a power of 2.
9118 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9119 /// vmul.f32 d16, d17, d16
9120 /// vcvt.s32.f32 d16, d16
9122 /// vcvt.s32.f32 d16, d16, #3
9123 static SDValue PerformVCVTCombine(SDNode *N,
9124 TargetLowering::DAGCombinerInfo &DCI,
9125 const ARMSubtarget *Subtarget) {
9126 SelectionDAG &DAG = DCI.DAG;
9127 SDValue Op = N->getOperand(0);
9129 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9130 Op.getOpcode() != ISD::FMUL)
9134 SDValue N0 = Op->getOperand(0);
9135 SDValue ConstVec = Op->getOperand(1);
9136 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9138 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9139 !isConstVecPow2(ConstVec, isSigned, C))
9142 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9143 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9144 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9145 // These instructions only exist converting from f32 to i32. We can handle
9146 // smaller integers by generating an extra truncate, but larger ones would
9151 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9152 Intrinsic::arm_neon_vcvtfp2fxu;
9153 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9154 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9155 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9156 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9157 DAG.getConstant(Log2_64(C), MVT::i32));
9159 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9160 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9165 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9166 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9167 /// when the VDIV has a constant operand that is a power of 2.
9169 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9170 /// vcvt.f32.s32 d16, d16
9171 /// vdiv.f32 d16, d17, d16
9173 /// vcvt.f32.s32 d16, d16, #3
9174 static SDValue PerformVDIVCombine(SDNode *N,
9175 TargetLowering::DAGCombinerInfo &DCI,
9176 const ARMSubtarget *Subtarget) {
9177 SelectionDAG &DAG = DCI.DAG;
9178 SDValue Op = N->getOperand(0);
9179 unsigned OpOpcode = Op.getNode()->getOpcode();
9181 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9182 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9186 SDValue ConstVec = N->getOperand(1);
9187 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9189 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9190 !isConstVecPow2(ConstVec, isSigned, C))
9193 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9194 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9195 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9196 // These instructions only exist converting from i32 to f32. We can handle
9197 // smaller integers by generating an extra extend, but larger ones would
9202 SDValue ConvInput = Op.getOperand(0);
9203 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9204 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9205 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9206 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9209 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9210 Intrinsic::arm_neon_vcvtfxu2fp;
9211 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9213 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9214 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9217 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9218 /// operand of a vector shift operation, where all the elements of the
9219 /// build_vector must have the same constant integer value.
9220 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9221 // Ignore bit_converts.
9222 while (Op.getOpcode() == ISD::BITCAST)
9223 Op = Op.getOperand(0);
9224 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9225 APInt SplatBits, SplatUndef;
9226 unsigned SplatBitSize;
9228 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9229 HasAnyUndefs, ElementBits) ||
9230 SplatBitSize > ElementBits)
9232 Cnt = SplatBits.getSExtValue();
9236 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9237 /// operand of a vector shift left operation. That value must be in the range:
9238 /// 0 <= Value < ElementBits for a left shift; or
9239 /// 0 <= Value <= ElementBits for a long left shift.
9240 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9241 assert(VT.isVector() && "vector shift count is not a vector type");
9242 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9243 if (! getVShiftImm(Op, ElementBits, Cnt))
9245 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9248 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9249 /// operand of a vector shift right operation. For a shift opcode, the value
9250 /// is positive, but for an intrinsic the value count must be negative. The
9251 /// absolute value must be in the range:
9252 /// 1 <= |Value| <= ElementBits for a right shift; or
9253 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9254 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9256 assert(VT.isVector() && "vector shift count is not a vector type");
9257 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9258 if (! getVShiftImm(Op, ElementBits, Cnt))
9262 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9265 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9266 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9267 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9270 // Don't do anything for most intrinsics.
9273 // Vector shifts: check for immediate versions and lower them.
9274 // Note: This is done during DAG combining instead of DAG legalizing because
9275 // the build_vectors for 64-bit vector element shift counts are generally
9276 // not legal, and it is hard to see their values after they get legalized to
9277 // loads from a constant pool.
9278 case Intrinsic::arm_neon_vshifts:
9279 case Intrinsic::arm_neon_vshiftu:
9280 case Intrinsic::arm_neon_vrshifts:
9281 case Intrinsic::arm_neon_vrshiftu:
9282 case Intrinsic::arm_neon_vrshiftn:
9283 case Intrinsic::arm_neon_vqshifts:
9284 case Intrinsic::arm_neon_vqshiftu:
9285 case Intrinsic::arm_neon_vqshiftsu:
9286 case Intrinsic::arm_neon_vqshiftns:
9287 case Intrinsic::arm_neon_vqshiftnu:
9288 case Intrinsic::arm_neon_vqshiftnsu:
9289 case Intrinsic::arm_neon_vqrshiftns:
9290 case Intrinsic::arm_neon_vqrshiftnu:
9291 case Intrinsic::arm_neon_vqrshiftnsu: {
9292 EVT VT = N->getOperand(1).getValueType();
9294 unsigned VShiftOpc = 0;
9297 case Intrinsic::arm_neon_vshifts:
9298 case Intrinsic::arm_neon_vshiftu:
9299 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9300 VShiftOpc = ARMISD::VSHL;
9303 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9304 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9305 ARMISD::VSHRs : ARMISD::VSHRu);
9310 case Intrinsic::arm_neon_vrshifts:
9311 case Intrinsic::arm_neon_vrshiftu:
9312 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9316 case Intrinsic::arm_neon_vqshifts:
9317 case Intrinsic::arm_neon_vqshiftu:
9318 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9322 case Intrinsic::arm_neon_vqshiftsu:
9323 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9325 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9327 case Intrinsic::arm_neon_vrshiftn:
9328 case Intrinsic::arm_neon_vqshiftns:
9329 case Intrinsic::arm_neon_vqshiftnu:
9330 case Intrinsic::arm_neon_vqshiftnsu:
9331 case Intrinsic::arm_neon_vqrshiftns:
9332 case Intrinsic::arm_neon_vqrshiftnu:
9333 case Intrinsic::arm_neon_vqrshiftnsu:
9334 // Narrowing shifts require an immediate right shift.
9335 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9337 llvm_unreachable("invalid shift count for narrowing vector shift "
9341 llvm_unreachable("unhandled vector shift");
9345 case Intrinsic::arm_neon_vshifts:
9346 case Intrinsic::arm_neon_vshiftu:
9347 // Opcode already set above.
9349 case Intrinsic::arm_neon_vrshifts:
9350 VShiftOpc = ARMISD::VRSHRs; break;
9351 case Intrinsic::arm_neon_vrshiftu:
9352 VShiftOpc = ARMISD::VRSHRu; break;
9353 case Intrinsic::arm_neon_vrshiftn:
9354 VShiftOpc = ARMISD::VRSHRN; break;
9355 case Intrinsic::arm_neon_vqshifts:
9356 VShiftOpc = ARMISD::VQSHLs; break;
9357 case Intrinsic::arm_neon_vqshiftu:
9358 VShiftOpc = ARMISD::VQSHLu; break;
9359 case Intrinsic::arm_neon_vqshiftsu:
9360 VShiftOpc = ARMISD::VQSHLsu; break;
9361 case Intrinsic::arm_neon_vqshiftns:
9362 VShiftOpc = ARMISD::VQSHRNs; break;
9363 case Intrinsic::arm_neon_vqshiftnu:
9364 VShiftOpc = ARMISD::VQSHRNu; break;
9365 case Intrinsic::arm_neon_vqshiftnsu:
9366 VShiftOpc = ARMISD::VQSHRNsu; break;
9367 case Intrinsic::arm_neon_vqrshiftns:
9368 VShiftOpc = ARMISD::VQRSHRNs; break;
9369 case Intrinsic::arm_neon_vqrshiftnu:
9370 VShiftOpc = ARMISD::VQRSHRNu; break;
9371 case Intrinsic::arm_neon_vqrshiftnsu:
9372 VShiftOpc = ARMISD::VQRSHRNsu; break;
9375 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9376 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9379 case Intrinsic::arm_neon_vshiftins: {
9380 EVT VT = N->getOperand(1).getValueType();
9382 unsigned VShiftOpc = 0;
9384 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9385 VShiftOpc = ARMISD::VSLI;
9386 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9387 VShiftOpc = ARMISD::VSRI;
9389 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9392 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9393 N->getOperand(1), N->getOperand(2),
9394 DAG.getConstant(Cnt, MVT::i32));
9397 case Intrinsic::arm_neon_vqrshifts:
9398 case Intrinsic::arm_neon_vqrshiftu:
9399 // No immediate versions of these to check for.
9406 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9407 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9408 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9409 /// vector element shift counts are generally not legal, and it is hard to see
9410 /// their values after they get legalized to loads from a constant pool.
9411 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9412 const ARMSubtarget *ST) {
9413 EVT VT = N->getValueType(0);
9414 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9415 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9416 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9417 SDValue N1 = N->getOperand(1);
9418 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9419 SDValue N0 = N->getOperand(0);
9420 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9421 DAG.MaskedValueIsZero(N0.getOperand(0),
9422 APInt::getHighBitsSet(32, 16)))
9423 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9427 // Nothing to be done for scalar shifts.
9428 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9429 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9432 assert(ST->hasNEON() && "unexpected vector shift");
9435 switch (N->getOpcode()) {
9436 default: llvm_unreachable("unexpected shift opcode");
9439 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9440 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9441 DAG.getConstant(Cnt, MVT::i32));
9446 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9447 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9448 ARMISD::VSHRs : ARMISD::VSHRu);
9449 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9450 DAG.getConstant(Cnt, MVT::i32));
9456 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9457 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9458 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9459 const ARMSubtarget *ST) {
9460 SDValue N0 = N->getOperand(0);
9462 // Check for sign- and zero-extensions of vector extract operations of 8-
9463 // and 16-bit vector elements. NEON supports these directly. They are
9464 // handled during DAG combining because type legalization will promote them
9465 // to 32-bit types and it is messy to recognize the operations after that.
9466 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9467 SDValue Vec = N0.getOperand(0);
9468 SDValue Lane = N0.getOperand(1);
9469 EVT VT = N->getValueType(0);
9470 EVT EltVT = N0.getValueType();
9471 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9473 if (VT == MVT::i32 &&
9474 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9475 TLI.isTypeLegal(Vec.getValueType()) &&
9476 isa<ConstantSDNode>(Lane)) {
9479 switch (N->getOpcode()) {
9480 default: llvm_unreachable("unexpected opcode");
9481 case ISD::SIGN_EXTEND:
9482 Opc = ARMISD::VGETLANEs;
9484 case ISD::ZERO_EXTEND:
9485 case ISD::ANY_EXTEND:
9486 Opc = ARMISD::VGETLANEu;
9489 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9496 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9497 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9498 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9499 const ARMSubtarget *ST) {
9500 // If the target supports NEON, try to use vmax/vmin instructions for f32
9501 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9502 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9503 // a NaN; only do the transformation when it matches that behavior.
9505 // For now only do this when using NEON for FP operations; if using VFP, it
9506 // is not obvious that the benefit outweighs the cost of switching to the
9508 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9509 N->getValueType(0) != MVT::f32)
9512 SDValue CondLHS = N->getOperand(0);
9513 SDValue CondRHS = N->getOperand(1);
9514 SDValue LHS = N->getOperand(2);
9515 SDValue RHS = N->getOperand(3);
9516 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9518 unsigned Opcode = 0;
9520 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9521 IsReversed = false; // x CC y ? x : y
9522 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9523 IsReversed = true ; // x CC y ? y : x
9537 // If LHS is NaN, an ordered comparison will be false and the result will
9538 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9539 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9540 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9541 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9543 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9544 // will return -0, so vmin can only be used for unsafe math or if one of
9545 // the operands is known to be nonzero.
9546 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9547 !DAG.getTarget().Options.UnsafeFPMath &&
9548 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9550 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9559 // If LHS is NaN, an ordered comparison will be false and the result will
9560 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9561 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9562 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9563 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9565 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9566 // will return +0, so vmax can only be used for unsafe math or if one of
9567 // the operands is known to be nonzero.
9568 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9569 !DAG.getTarget().Options.UnsafeFPMath &&
9570 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9572 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9578 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9581 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9583 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9584 SDValue Cmp = N->getOperand(4);
9585 if (Cmp.getOpcode() != ARMISD::CMPZ)
9586 // Only looking at EQ and NE cases.
9589 EVT VT = N->getValueType(0);
9591 SDValue LHS = Cmp.getOperand(0);
9592 SDValue RHS = Cmp.getOperand(1);
9593 SDValue FalseVal = N->getOperand(0);
9594 SDValue TrueVal = N->getOperand(1);
9595 SDValue ARMcc = N->getOperand(2);
9596 ARMCC::CondCodes CC =
9597 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9615 /// FIXME: Turn this into a target neutral optimization?
9617 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9618 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9619 N->getOperand(3), Cmp);
9620 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9622 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9623 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9624 N->getOperand(3), NewCmp);
9627 if (Res.getNode()) {
9628 APInt KnownZero, KnownOne;
9629 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9630 // Capture demanded bits information that would be otherwise lost.
9631 if (KnownZero == 0xfffffffe)
9632 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9633 DAG.getValueType(MVT::i1));
9634 else if (KnownZero == 0xffffff00)
9635 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9636 DAG.getValueType(MVT::i8));
9637 else if (KnownZero == 0xffff0000)
9638 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9639 DAG.getValueType(MVT::i16));
9645 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9646 DAGCombinerInfo &DCI) const {
9647 switch (N->getOpcode()) {
9649 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9650 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9651 case ISD::SUB: return PerformSUBCombine(N, DCI);
9652 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9653 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9654 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9655 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9656 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9657 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9658 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9659 case ISD::STORE: return PerformSTORECombine(N, DCI);
9660 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9661 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9662 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9663 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9664 case ISD::FP_TO_SINT:
9665 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9666 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9667 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9670 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9671 case ISD::SIGN_EXTEND:
9672 case ISD::ZERO_EXTEND:
9673 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9674 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9675 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9676 case ARMISD::VLD2DUP:
9677 case ARMISD::VLD3DUP:
9678 case ARMISD::VLD4DUP:
9679 return CombineBaseUpdate(N, DCI);
9680 case ARMISD::BUILD_VECTOR:
9681 return PerformARMBUILD_VECTORCombine(N, DCI);
9682 case ISD::INTRINSIC_VOID:
9683 case ISD::INTRINSIC_W_CHAIN:
9684 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9685 case Intrinsic::arm_neon_vld1:
9686 case Intrinsic::arm_neon_vld2:
9687 case Intrinsic::arm_neon_vld3:
9688 case Intrinsic::arm_neon_vld4:
9689 case Intrinsic::arm_neon_vld2lane:
9690 case Intrinsic::arm_neon_vld3lane:
9691 case Intrinsic::arm_neon_vld4lane:
9692 case Intrinsic::arm_neon_vst1:
9693 case Intrinsic::arm_neon_vst2:
9694 case Intrinsic::arm_neon_vst3:
9695 case Intrinsic::arm_neon_vst4:
9696 case Intrinsic::arm_neon_vst2lane:
9697 case Intrinsic::arm_neon_vst3lane:
9698 case Intrinsic::arm_neon_vst4lane:
9699 return CombineBaseUpdate(N, DCI);
9707 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9709 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9712 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9716 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9717 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9719 switch (VT.getSimpleVT().SimpleTy) {
9725 // Unaligned access can use (for example) LRDB, LRDH, LDR
9726 if (AllowsUnaligned) {
9728 *Fast = Subtarget->hasV7Ops();
9735 // For any little-endian targets with neon, we can support unaligned ld/st
9736 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9737 // A big-endian target may also explicitly support unaligned accesses
9738 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9748 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9749 unsigned AlignCheck) {
9750 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9751 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9754 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9755 unsigned DstAlign, unsigned SrcAlign,
9756 bool IsMemset, bool ZeroMemset,
9758 MachineFunction &MF) const {
9759 const Function *F = MF.getFunction();
9761 // See if we can use NEON instructions for this...
9762 if ((!IsMemset || ZeroMemset) &&
9763 Subtarget->hasNEON() &&
9764 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9765 Attribute::NoImplicitFloat)) {
9768 (memOpAlign(SrcAlign, DstAlign, 16) ||
9769 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9771 } else if (Size >= 8 &&
9772 (memOpAlign(SrcAlign, DstAlign, 8) ||
9773 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9779 // Lowering to i32/i16 if the size permits.
9785 // Let the target-independent logic figure it out.
9789 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9790 if (Val.getOpcode() != ISD::LOAD)
9793 EVT VT1 = Val.getValueType();
9794 if (!VT1.isSimple() || !VT1.isInteger() ||
9795 !VT2.isSimple() || !VT2.isInteger())
9798 switch (VT1.getSimpleVT().SimpleTy) {
9803 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9810 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9811 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9814 if (!isTypeLegal(EVT::getEVT(Ty1)))
9817 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9819 // Assuming the caller doesn't have a zeroext or signext return parameter,
9820 // truncation all the way down to i1 is valid.
9825 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9830 switch (VT.getSimpleVT().SimpleTy) {
9831 default: return false;
9846 if ((V & (Scale - 1)) != 0)
9849 return V == (V & ((1LL << 5) - 1));
9852 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9853 const ARMSubtarget *Subtarget) {
9860 switch (VT.getSimpleVT().SimpleTy) {
9861 default: return false;
9866 // + imm12 or - imm8
9868 return V == (V & ((1LL << 8) - 1));
9869 return V == (V & ((1LL << 12) - 1));
9872 // Same as ARM mode. FIXME: NEON?
9873 if (!Subtarget->hasVFP2())
9878 return V == (V & ((1LL << 8) - 1));
9882 /// isLegalAddressImmediate - Return true if the integer value can be used
9883 /// as the offset of the target addressing mode for load / store of the
9885 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9886 const ARMSubtarget *Subtarget) {
9893 if (Subtarget->isThumb1Only())
9894 return isLegalT1AddressImmediate(V, VT);
9895 else if (Subtarget->isThumb2())
9896 return isLegalT2AddressImmediate(V, VT, Subtarget);
9901 switch (VT.getSimpleVT().SimpleTy) {
9902 default: return false;
9907 return V == (V & ((1LL << 12) - 1));
9910 return V == (V & ((1LL << 8) - 1));
9913 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9918 return V == (V & ((1LL << 8) - 1));
9922 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9924 int Scale = AM.Scale;
9928 switch (VT.getSimpleVT().SimpleTy) {
9929 default: return false;
9938 return Scale == 2 || Scale == 4 || Scale == 8;
9941 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9945 // Note, we allow "void" uses (basically, uses that aren't loads or
9946 // stores), because arm allows folding a scale into many arithmetic
9947 // operations. This should be made more precise and revisited later.
9949 // Allow r << imm, but the imm has to be a multiple of two.
9950 if (Scale & 1) return false;
9951 return isPowerOf2_32(Scale);
9955 /// isLegalAddressingMode - Return true if the addressing mode represented
9956 /// by AM is legal for this target, for a load/store of the specified type.
9957 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9959 EVT VT = getValueType(Ty, true);
9960 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9963 // Can never fold addr of global into load/store.
9968 case 0: // no scale reg, must be "r+i" or "r", or "i".
9971 if (Subtarget->isThumb1Only())
9975 // ARM doesn't support any R+R*scale+imm addr modes.
9982 if (Subtarget->isThumb2())
9983 return isLegalT2ScaledAddressingMode(AM, VT);
9985 int Scale = AM.Scale;
9986 switch (VT.getSimpleVT().SimpleTy) {
9987 default: return false;
9991 if (Scale < 0) Scale = -Scale;
9995 return isPowerOf2_32(Scale & ~1);
9999 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10004 // Note, we allow "void" uses (basically, uses that aren't loads or
10005 // stores), because arm allows folding a scale into many arithmetic
10006 // operations. This should be made more precise and revisited later.
10008 // Allow r << imm, but the imm has to be a multiple of two.
10009 if (Scale & 1) return false;
10010 return isPowerOf2_32(Scale);
10016 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10017 /// icmp immediate, that is the target has icmp instructions which can compare
10018 /// a register against the immediate without having to materialize the
10019 /// immediate into a register.
10020 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10021 // Thumb2 and ARM modes can use cmn for negative immediates.
10022 if (!Subtarget->isThumb())
10023 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10024 if (Subtarget->isThumb2())
10025 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10026 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10027 return Imm >= 0 && Imm <= 255;
10030 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10031 /// *or sub* immediate, that is the target has add or sub instructions which can
10032 /// add a register with the immediate without having to materialize the
10033 /// immediate into a register.
10034 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10035 // Same encoding for add/sub, just flip the sign.
10036 int64_t AbsImm = llvm::abs64(Imm);
10037 if (!Subtarget->isThumb())
10038 return ARM_AM::getSOImmVal(AbsImm) != -1;
10039 if (Subtarget->isThumb2())
10040 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10041 // Thumb1 only has 8-bit unsigned immediate.
10042 return AbsImm >= 0 && AbsImm <= 255;
10045 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10046 bool isSEXTLoad, SDValue &Base,
10047 SDValue &Offset, bool &isInc,
10048 SelectionDAG &DAG) {
10049 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10052 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10053 // AddressingMode 3
10054 Base = Ptr->getOperand(0);
10055 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10056 int RHSC = (int)RHS->getZExtValue();
10057 if (RHSC < 0 && RHSC > -256) {
10058 assert(Ptr->getOpcode() == ISD::ADD);
10060 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10064 isInc = (Ptr->getOpcode() == ISD::ADD);
10065 Offset = Ptr->getOperand(1);
10067 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10068 // AddressingMode 2
10069 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10070 int RHSC = (int)RHS->getZExtValue();
10071 if (RHSC < 0 && RHSC > -0x1000) {
10072 assert(Ptr->getOpcode() == ISD::ADD);
10074 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10075 Base = Ptr->getOperand(0);
10080 if (Ptr->getOpcode() == ISD::ADD) {
10082 ARM_AM::ShiftOpc ShOpcVal=
10083 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10084 if (ShOpcVal != ARM_AM::no_shift) {
10085 Base = Ptr->getOperand(1);
10086 Offset = Ptr->getOperand(0);
10088 Base = Ptr->getOperand(0);
10089 Offset = Ptr->getOperand(1);
10094 isInc = (Ptr->getOpcode() == ISD::ADD);
10095 Base = Ptr->getOperand(0);
10096 Offset = Ptr->getOperand(1);
10100 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10104 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10105 bool isSEXTLoad, SDValue &Base,
10106 SDValue &Offset, bool &isInc,
10107 SelectionDAG &DAG) {
10108 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10111 Base = Ptr->getOperand(0);
10112 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10113 int RHSC = (int)RHS->getZExtValue();
10114 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10115 assert(Ptr->getOpcode() == ISD::ADD);
10117 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10119 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10120 isInc = Ptr->getOpcode() == ISD::ADD;
10121 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10129 /// getPreIndexedAddressParts - returns true by value, base pointer and
10130 /// offset pointer and addressing mode by reference if the node's address
10131 /// can be legally represented as pre-indexed load / store address.
10133 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10135 ISD::MemIndexedMode &AM,
10136 SelectionDAG &DAG) const {
10137 if (Subtarget->isThumb1Only())
10142 bool isSEXTLoad = false;
10143 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10144 Ptr = LD->getBasePtr();
10145 VT = LD->getMemoryVT();
10146 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10147 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10148 Ptr = ST->getBasePtr();
10149 VT = ST->getMemoryVT();
10154 bool isLegal = false;
10155 if (Subtarget->isThumb2())
10156 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10157 Offset, isInc, DAG);
10159 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10160 Offset, isInc, DAG);
10164 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10168 /// getPostIndexedAddressParts - returns true by value, base pointer and
10169 /// offset pointer and addressing mode by reference if this node can be
10170 /// combined with a load / store to form a post-indexed load / store.
10171 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10174 ISD::MemIndexedMode &AM,
10175 SelectionDAG &DAG) const {
10176 if (Subtarget->isThumb1Only())
10181 bool isSEXTLoad = false;
10182 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10183 VT = LD->getMemoryVT();
10184 Ptr = LD->getBasePtr();
10185 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10186 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10187 VT = ST->getMemoryVT();
10188 Ptr = ST->getBasePtr();
10193 bool isLegal = false;
10194 if (Subtarget->isThumb2())
10195 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10198 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10204 // Swap base ptr and offset to catch more post-index load / store when
10205 // it's legal. In Thumb2 mode, offset must be an immediate.
10206 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10207 !Subtarget->isThumb2())
10208 std::swap(Base, Offset);
10210 // Post-indexed load / store update the base pointer.
10215 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10219 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10222 const SelectionDAG &DAG,
10223 unsigned Depth) const {
10224 unsigned BitWidth = KnownOne.getBitWidth();
10225 KnownZero = KnownOne = APInt(BitWidth, 0);
10226 switch (Op.getOpcode()) {
10232 // These nodes' second result is a boolean
10233 if (Op.getResNo() == 0)
10235 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10237 case ARMISD::CMOV: {
10238 // Bits are known zero/one if known on the LHS and RHS.
10239 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10240 if (KnownZero == 0 && KnownOne == 0) return;
10242 APInt KnownZeroRHS, KnownOneRHS;
10243 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10244 KnownZero &= KnownZeroRHS;
10245 KnownOne &= KnownOneRHS;
10248 case ISD::INTRINSIC_W_CHAIN: {
10249 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10250 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10253 case Intrinsic::arm_ldaex:
10254 case Intrinsic::arm_ldrex: {
10255 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10256 unsigned MemBits = VT.getScalarType().getSizeInBits();
10257 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10265 //===----------------------------------------------------------------------===//
10266 // ARM Inline Assembly Support
10267 //===----------------------------------------------------------------------===//
10269 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10270 // Looking for "rev" which is V6+.
10271 if (!Subtarget->hasV6Ops())
10274 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10275 std::string AsmStr = IA->getAsmString();
10276 SmallVector<StringRef, 4> AsmPieces;
10277 SplitString(AsmStr, AsmPieces, ";\n");
10279 switch (AsmPieces.size()) {
10280 default: return false;
10282 AsmStr = AsmPieces[0];
10284 SplitString(AsmStr, AsmPieces, " \t,");
10287 if (AsmPieces.size() == 3 &&
10288 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10289 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10290 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10291 if (Ty && Ty->getBitWidth() == 32)
10292 return IntrinsicLowering::LowerToByteSwap(CI);
10300 /// getConstraintType - Given a constraint letter, return the type of
10301 /// constraint it is for this target.
10302 ARMTargetLowering::ConstraintType
10303 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10304 if (Constraint.size() == 1) {
10305 switch (Constraint[0]) {
10307 case 'l': return C_RegisterClass;
10308 case 'w': return C_RegisterClass;
10309 case 'h': return C_RegisterClass;
10310 case 'x': return C_RegisterClass;
10311 case 't': return C_RegisterClass;
10312 case 'j': return C_Other; // Constant for movw.
10313 // An address with a single base register. Due to the way we
10314 // currently handle addresses it is the same as an 'r' memory constraint.
10315 case 'Q': return C_Memory;
10317 } else if (Constraint.size() == 2) {
10318 switch (Constraint[0]) {
10320 // All 'U+' constraints are addresses.
10321 case 'U': return C_Memory;
10324 return TargetLowering::getConstraintType(Constraint);
10327 /// Examine constraint type and operand type and determine a weight value.
10328 /// This object must already have been set up with the operand type
10329 /// and the current alternative constraint selected.
10330 TargetLowering::ConstraintWeight
10331 ARMTargetLowering::getSingleConstraintMatchWeight(
10332 AsmOperandInfo &info, const char *constraint) const {
10333 ConstraintWeight weight = CW_Invalid;
10334 Value *CallOperandVal = info.CallOperandVal;
10335 // If we don't have a value, we can't do a match,
10336 // but allow it at the lowest weight.
10337 if (!CallOperandVal)
10339 Type *type = CallOperandVal->getType();
10340 // Look at the constraint type.
10341 switch (*constraint) {
10343 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10346 if (type->isIntegerTy()) {
10347 if (Subtarget->isThumb())
10348 weight = CW_SpecificReg;
10350 weight = CW_Register;
10354 if (type->isFloatingPointTy())
10355 weight = CW_Register;
10361 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10363 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10365 if (Constraint.size() == 1) {
10366 // GCC ARM Constraint Letters
10367 switch (Constraint[0]) {
10368 case 'l': // Low regs or general regs.
10369 if (Subtarget->isThumb())
10370 return RCPair(0U, &ARM::tGPRRegClass);
10371 return RCPair(0U, &ARM::GPRRegClass);
10372 case 'h': // High regs or no regs.
10373 if (Subtarget->isThumb())
10374 return RCPair(0U, &ARM::hGPRRegClass);
10377 return RCPair(0U, &ARM::GPRRegClass);
10379 if (VT == MVT::Other)
10381 if (VT == MVT::f32)
10382 return RCPair(0U, &ARM::SPRRegClass);
10383 if (VT.getSizeInBits() == 64)
10384 return RCPair(0U, &ARM::DPRRegClass);
10385 if (VT.getSizeInBits() == 128)
10386 return RCPair(0U, &ARM::QPRRegClass);
10389 if (VT == MVT::Other)
10391 if (VT == MVT::f32)
10392 return RCPair(0U, &ARM::SPR_8RegClass);
10393 if (VT.getSizeInBits() == 64)
10394 return RCPair(0U, &ARM::DPR_8RegClass);
10395 if (VT.getSizeInBits() == 128)
10396 return RCPair(0U, &ARM::QPR_8RegClass);
10399 if (VT == MVT::f32)
10400 return RCPair(0U, &ARM::SPRRegClass);
10404 if (StringRef("{cc}").equals_lower(Constraint))
10405 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10407 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10410 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10411 /// vector. If it is invalid, don't add anything to Ops.
10412 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10413 std::string &Constraint,
10414 std::vector<SDValue>&Ops,
10415 SelectionDAG &DAG) const {
10418 // Currently only support length 1 constraints.
10419 if (Constraint.length() != 1) return;
10421 char ConstraintLetter = Constraint[0];
10422 switch (ConstraintLetter) {
10425 case 'I': case 'J': case 'K': case 'L':
10426 case 'M': case 'N': case 'O':
10427 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10431 int64_t CVal64 = C->getSExtValue();
10432 int CVal = (int) CVal64;
10433 // None of these constraints allow values larger than 32 bits. Check
10434 // that the value fits in an int.
10435 if (CVal != CVal64)
10438 switch (ConstraintLetter) {
10440 // Constant suitable for movw, must be between 0 and
10442 if (Subtarget->hasV6T2Ops())
10443 if (CVal >= 0 && CVal <= 65535)
10447 if (Subtarget->isThumb1Only()) {
10448 // This must be a constant between 0 and 255, for ADD
10450 if (CVal >= 0 && CVal <= 255)
10452 } else if (Subtarget->isThumb2()) {
10453 // A constant that can be used as an immediate value in a
10454 // data-processing instruction.
10455 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10458 // A constant that can be used as an immediate value in a
10459 // data-processing instruction.
10460 if (ARM_AM::getSOImmVal(CVal) != -1)
10466 if (Subtarget->isThumb()) { // FIXME thumb2
10467 // This must be a constant between -255 and -1, for negated ADD
10468 // immediates. This can be used in GCC with an "n" modifier that
10469 // prints the negated value, for use with SUB instructions. It is
10470 // not useful otherwise but is implemented for compatibility.
10471 if (CVal >= -255 && CVal <= -1)
10474 // This must be a constant between -4095 and 4095. It is not clear
10475 // what this constraint is intended for. Implemented for
10476 // compatibility with GCC.
10477 if (CVal >= -4095 && CVal <= 4095)
10483 if (Subtarget->isThumb1Only()) {
10484 // A 32-bit value where only one byte has a nonzero value. Exclude
10485 // zero to match GCC. This constraint is used by GCC internally for
10486 // constants that can be loaded with a move/shift combination.
10487 // It is not useful otherwise but is implemented for compatibility.
10488 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10490 } else if (Subtarget->isThumb2()) {
10491 // A constant whose bitwise inverse can be used as an immediate
10492 // value in a data-processing instruction. This can be used in GCC
10493 // with a "B" modifier that prints the inverted value, for use with
10494 // BIC and MVN instructions. It is not useful otherwise but is
10495 // implemented for compatibility.
10496 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10499 // A constant whose bitwise inverse can be used as an immediate
10500 // value in a data-processing instruction. This can be used in GCC
10501 // with a "B" modifier that prints the inverted value, for use with
10502 // BIC and MVN instructions. It is not useful otherwise but is
10503 // implemented for compatibility.
10504 if (ARM_AM::getSOImmVal(~CVal) != -1)
10510 if (Subtarget->isThumb1Only()) {
10511 // This must be a constant between -7 and 7,
10512 // for 3-operand ADD/SUB immediate instructions.
10513 if (CVal >= -7 && CVal < 7)
10515 } else if (Subtarget->isThumb2()) {
10516 // A constant whose negation can be used as an immediate value in a
10517 // data-processing instruction. This can be used in GCC with an "n"
10518 // modifier that prints the negated value, for use with SUB
10519 // instructions. It is not useful otherwise but is implemented for
10521 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10524 // A constant whose negation can be used as an immediate value in a
10525 // data-processing instruction. This can be used in GCC with an "n"
10526 // modifier that prints the negated value, for use with SUB
10527 // instructions. It is not useful otherwise but is implemented for
10529 if (ARM_AM::getSOImmVal(-CVal) != -1)
10535 if (Subtarget->isThumb()) { // FIXME thumb2
10536 // This must be a multiple of 4 between 0 and 1020, for
10537 // ADD sp + immediate.
10538 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10541 // A power of two or a constant between 0 and 32. This is used in
10542 // GCC for the shift amount on shifted register operands, but it is
10543 // useful in general for any shift amounts.
10544 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10550 if (Subtarget->isThumb()) { // FIXME thumb2
10551 // This must be a constant between 0 and 31, for shift amounts.
10552 if (CVal >= 0 && CVal <= 31)
10558 if (Subtarget->isThumb()) { // FIXME thumb2
10559 // This must be a multiple of 4 between -508 and 508, for
10560 // ADD/SUB sp = sp + immediate.
10561 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10566 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10570 if (Result.getNode()) {
10571 Ops.push_back(Result);
10574 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10577 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10578 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10579 unsigned Opcode = Op->getOpcode();
10580 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10581 "Invalid opcode for Div/Rem lowering");
10582 bool isSigned = (Opcode == ISD::SDIVREM);
10583 EVT VT = Op->getValueType(0);
10584 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10587 switch (VT.getSimpleVT().SimpleTy) {
10588 default: llvm_unreachable("Unexpected request for libcall!");
10589 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10590 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10591 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10592 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10595 SDValue InChain = DAG.getEntryNode();
10597 TargetLowering::ArgListTy Args;
10598 TargetLowering::ArgListEntry Entry;
10599 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10600 EVT ArgVT = Op->getOperand(i).getValueType();
10601 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10602 Entry.Node = Op->getOperand(i);
10604 Entry.isSExt = isSigned;
10605 Entry.isZExt = !isSigned;
10606 Args.push_back(Entry);
10609 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10612 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10615 TargetLowering::CallLoweringInfo CLI(DAG);
10616 CLI.setDebugLoc(dl).setChain(InChain)
10617 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10618 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10620 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10621 return CallInfo.first;
10625 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10626 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10630 SDValue Chain = Op.getOperand(0);
10631 SDValue Size = Op.getOperand(1);
10633 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10634 DAG.getConstant(2, MVT::i32));
10637 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10638 Flag = Chain.getValue(1);
10640 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10641 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10643 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10644 Chain = NewSP.getValue(1);
10646 SDValue Ops[2] = { NewSP, Chain };
10647 return DAG.getMergeValues(Ops, DL);
10651 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10652 // The ARM target isn't yet aware of offsets.
10656 bool ARM::isBitFieldInvertedMask(unsigned v) {
10657 if (v == 0xffffffff)
10660 // there can be 1's on either or both "outsides", all the "inside"
10661 // bits must be 0's
10662 unsigned TO = CountTrailingOnes_32(v);
10663 unsigned LO = CountLeadingOnes_32(v);
10664 v = (v >> TO) << TO;
10665 v = (v << LO) >> LO;
10669 /// isFPImmLegal - Returns true if the target can instruction select the
10670 /// specified FP immediate natively. If false, the legalizer will
10671 /// materialize the FP immediate as a load from a constant pool.
10672 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10673 if (!Subtarget->hasVFP3())
10675 if (VT == MVT::f32)
10676 return ARM_AM::getFP32Imm(Imm) != -1;
10677 if (VT == MVT::f64)
10678 return ARM_AM::getFP64Imm(Imm) != -1;
10682 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10683 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10684 /// specified in the intrinsic calls.
10685 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10687 unsigned Intrinsic) const {
10688 switch (Intrinsic) {
10689 case Intrinsic::arm_neon_vld1:
10690 case Intrinsic::arm_neon_vld2:
10691 case Intrinsic::arm_neon_vld3:
10692 case Intrinsic::arm_neon_vld4:
10693 case Intrinsic::arm_neon_vld2lane:
10694 case Intrinsic::arm_neon_vld3lane:
10695 case Intrinsic::arm_neon_vld4lane: {
10696 Info.opc = ISD::INTRINSIC_W_CHAIN;
10697 // Conservatively set memVT to the entire set of vectors loaded.
10698 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10699 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10700 Info.ptrVal = I.getArgOperand(0);
10702 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10703 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10704 Info.vol = false; // volatile loads with NEON intrinsics not supported
10705 Info.readMem = true;
10706 Info.writeMem = false;
10709 case Intrinsic::arm_neon_vst1:
10710 case Intrinsic::arm_neon_vst2:
10711 case Intrinsic::arm_neon_vst3:
10712 case Intrinsic::arm_neon_vst4:
10713 case Intrinsic::arm_neon_vst2lane:
10714 case Intrinsic::arm_neon_vst3lane:
10715 case Intrinsic::arm_neon_vst4lane: {
10716 Info.opc = ISD::INTRINSIC_VOID;
10717 // Conservatively set memVT to the entire set of vectors stored.
10718 unsigned NumElts = 0;
10719 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10720 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10721 if (!ArgTy->isVectorTy())
10723 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10725 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10726 Info.ptrVal = I.getArgOperand(0);
10728 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10729 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10730 Info.vol = false; // volatile stores with NEON intrinsics not supported
10731 Info.readMem = false;
10732 Info.writeMem = true;
10735 case Intrinsic::arm_ldaex:
10736 case Intrinsic::arm_ldrex: {
10737 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10738 Info.opc = ISD::INTRINSIC_W_CHAIN;
10739 Info.memVT = MVT::getVT(PtrTy->getElementType());
10740 Info.ptrVal = I.getArgOperand(0);
10742 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10744 Info.readMem = true;
10745 Info.writeMem = false;
10748 case Intrinsic::arm_stlex:
10749 case Intrinsic::arm_strex: {
10750 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10751 Info.opc = ISD::INTRINSIC_W_CHAIN;
10752 Info.memVT = MVT::getVT(PtrTy->getElementType());
10753 Info.ptrVal = I.getArgOperand(1);
10755 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10757 Info.readMem = false;
10758 Info.writeMem = true;
10761 case Intrinsic::arm_stlexd:
10762 case Intrinsic::arm_strexd: {
10763 Info.opc = ISD::INTRINSIC_W_CHAIN;
10764 Info.memVT = MVT::i64;
10765 Info.ptrVal = I.getArgOperand(2);
10769 Info.readMem = false;
10770 Info.writeMem = true;
10773 case Intrinsic::arm_ldaexd:
10774 case Intrinsic::arm_ldrexd: {
10775 Info.opc = ISD::INTRINSIC_W_CHAIN;
10776 Info.memVT = MVT::i64;
10777 Info.ptrVal = I.getArgOperand(0);
10781 Info.readMem = true;
10782 Info.writeMem = false;
10792 /// \brief Returns true if it is beneficial to convert a load of a constant
10793 /// to just the constant itself.
10794 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10796 assert(Ty->isIntegerTy());
10798 unsigned Bits = Ty->getPrimitiveSizeInBits();
10799 if (Bits == 0 || Bits > 32)
10804 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10805 // Loads and stores less than 64-bits are already atomic; ones above that
10806 // are doomed anyway, so defer to the default libcall and blame the OS when
10807 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10808 // anything for those.
10809 bool IsMClass = Subtarget->isMClass();
10810 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10811 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10812 return Size == 64 && !IsMClass;
10813 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10814 return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10817 // For the real atomic operations, we have ldrex/strex up to 32 bits,
10818 // and up to 64 bits on the non-M profiles
10819 unsigned AtomicLimit = IsMClass ? 32 : 64;
10820 return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10823 // This has so far only been implemented for MachO.
10824 bool ARMTargetLowering::useLoadStackGuardNode() const {
10825 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
10828 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10829 AtomicOrdering Ord) const {
10830 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10831 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10833 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10835 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10836 // intrinsic must return {i32, i32} and we have to recombine them into a
10837 // single i64 here.
10838 if (ValTy->getPrimitiveSizeInBits() == 64) {
10839 Intrinsic::ID Int =
10840 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10841 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10843 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10844 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10846 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10847 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10848 if (!Subtarget->isLittle())
10849 std::swap (Lo, Hi);
10850 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10851 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10852 return Builder.CreateOr(
10853 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10856 Type *Tys[] = { Addr->getType() };
10857 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10858 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10860 return Builder.CreateTruncOrBitCast(
10861 Builder.CreateCall(Ldrex, Addr),
10862 cast<PointerType>(Addr->getType())->getElementType());
10865 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10867 AtomicOrdering Ord) const {
10868 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10870 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10872 // Since the intrinsics must have legal type, the i64 intrinsics take two
10873 // parameters: "i32, i32". We must marshal Val into the appropriate form
10874 // before the call.
10875 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10876 Intrinsic::ID Int =
10877 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10878 Function *Strex = Intrinsic::getDeclaration(M, Int);
10879 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10881 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10882 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10883 if (!Subtarget->isLittle())
10884 std::swap (Lo, Hi);
10885 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10886 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10889 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10890 Type *Tys[] = { Addr->getType() };
10891 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10893 return Builder.CreateCall2(
10894 Strex, Builder.CreateZExtOrBitCast(
10895 Val, Strex->getFunctionType()->getParamType(0)),
10907 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10908 uint64_t &Members) {
10909 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10910 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10911 uint64_t SubMembers = 0;
10912 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10914 Members += SubMembers;
10916 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10917 uint64_t SubMembers = 0;
10918 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10920 Members += SubMembers * AT->getNumElements();
10921 } else if (Ty->isFloatTy()) {
10922 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10926 } else if (Ty->isDoubleTy()) {
10927 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10931 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10938 return VT->getBitWidth() == 64;
10940 return VT->getBitWidth() == 128;
10942 switch (VT->getBitWidth()) {
10955 return (Members > 0 && Members <= 4);
10958 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10959 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10960 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10961 if (getEffectiveCallingConv(CallConv, isVarArg) !=
10962 CallingConv::ARM_AAPCS_VFP)
10965 HABaseType Base = HA_UNKNOWN;
10966 uint64_t Members = 0;
10967 bool result = isHomogeneousAggregate(Ty, Base, Members);
10968 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");