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.getRegisterInfo();
170 Itins = TM.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::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 // Integer to floating-point conversions.
318 // RTABI chapter 4.1.2, Table 8
319 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 // Long long helper functions
329 // RTABI chapter 4.2, Table 9
330 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 // Integer division functions
336 // RTABI chapter 4.3.1
337 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 // RTABI chapter 4.3.4
348 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353 for (const auto &LC : LibraryCalls) {
354 setLibcallName(LC.Op, LC.Name);
355 setLibcallCallingConv(LC.Op, LC.CC);
356 if (LC.Cond != ISD::SETCC_INVALID)
357 setCmpLibcallCC(LC.Op, LC.Cond);
361 if (Subtarget->isTargetWindows()) {
362 static const struct {
363 const RTLIB::Libcall Op;
364 const char * const Name;
365 const CallingConv::ID CC;
367 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
371 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
372 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
373 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
374 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
377 for (const auto &LC : LibraryCalls) {
378 setLibcallName(LC.Op, LC.Name);
379 setLibcallCallingConv(LC.Op, LC.CC);
383 // Use divmod compiler-rt calls for iOS 5.0 and later.
384 if (Subtarget->getTargetTriple().isiOS() &&
385 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
386 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
387 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
390 if (Subtarget->isThumb1Only())
391 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
393 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
394 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
395 !Subtarget->isThumb1Only()) {
396 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
397 if (!Subtarget->isFPOnlySP())
398 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
400 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
403 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
405 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
406 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
407 setTruncStoreAction((MVT::SimpleValueType)VT,
408 (MVT::SimpleValueType)InnerVT, Expand);
409 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
410 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
411 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
413 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
414 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
415 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
416 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
418 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
421 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
422 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
424 if (Subtarget->hasNEON()) {
425 addDRTypeForNEON(MVT::v2f32);
426 addDRTypeForNEON(MVT::v8i8);
427 addDRTypeForNEON(MVT::v4i16);
428 addDRTypeForNEON(MVT::v2i32);
429 addDRTypeForNEON(MVT::v1i64);
431 addQRTypeForNEON(MVT::v4f32);
432 addQRTypeForNEON(MVT::v2f64);
433 addQRTypeForNEON(MVT::v16i8);
434 addQRTypeForNEON(MVT::v8i16);
435 addQRTypeForNEON(MVT::v4i32);
436 addQRTypeForNEON(MVT::v2i64);
438 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
439 // neither Neon nor VFP support any arithmetic operations on it.
440 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
441 // supported for v4f32.
442 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
443 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
444 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
445 // FIXME: Code duplication: FDIV and FREM are expanded always, see
446 // ARMTargetLowering::addTypeForNEON method for details.
447 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
448 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
449 // FIXME: Create unittest.
450 // In another words, find a way when "copysign" appears in DAG with vector
452 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
453 // FIXME: Code duplication: SETCC has custom operation action, see
454 // ARMTargetLowering::addTypeForNEON method for details.
455 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
456 // FIXME: Create unittest for FNEG and for FABS.
457 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
458 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
459 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
460 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
461 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
462 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
463 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
464 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
465 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
466 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
467 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
468 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
469 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
470 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
471 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
472 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
473 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
474 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
475 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
477 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
478 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
479 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
480 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
481 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
482 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
483 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
484 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
485 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
486 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
487 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
488 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
489 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
490 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
491 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
493 // Mark v2f32 intrinsics.
494 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
495 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
496 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
497 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
498 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
499 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
500 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
501 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
502 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
503 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
504 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
505 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
506 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
507 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
508 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
510 // Neon does not support some operations on v1i64 and v2i64 types.
511 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
512 // Custom handling for some quad-vector types to detect VMULL.
513 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
514 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
515 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
516 // Custom handling for some vector types to avoid expensive expansions
517 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
518 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
519 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
520 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
521 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
522 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
523 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
524 // a destination type that is wider than the source, and nor does
525 // it have a FP_TO_[SU]INT instruction with a narrower destination than
527 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
528 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
529 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
530 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
532 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
533 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
535 // NEON does not have single instruction CTPOP for vectors with element
536 // types wider than 8-bits. However, custom lowering can leverage the
537 // v8i8/v16i8 vcnt instruction.
538 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
539 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
540 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
541 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
543 // NEON only has FMA instructions as of VFP4.
544 if (!Subtarget->hasVFP4()) {
545 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
546 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
549 setTargetDAGCombine(ISD::INTRINSIC_VOID);
550 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
551 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
552 setTargetDAGCombine(ISD::SHL);
553 setTargetDAGCombine(ISD::SRL);
554 setTargetDAGCombine(ISD::SRA);
555 setTargetDAGCombine(ISD::SIGN_EXTEND);
556 setTargetDAGCombine(ISD::ZERO_EXTEND);
557 setTargetDAGCombine(ISD::ANY_EXTEND);
558 setTargetDAGCombine(ISD::SELECT_CC);
559 setTargetDAGCombine(ISD::BUILD_VECTOR);
560 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
561 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
562 setTargetDAGCombine(ISD::STORE);
563 setTargetDAGCombine(ISD::FP_TO_SINT);
564 setTargetDAGCombine(ISD::FP_TO_UINT);
565 setTargetDAGCombine(ISD::FDIV);
567 // It is legal to extload from v4i8 to v4i16 or v4i32.
568 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
569 MVT::v4i16, MVT::v2i16,
571 for (unsigned i = 0; i < 6; ++i) {
572 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
573 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
574 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
578 // ARM and Thumb2 support UMLAL/SMLAL.
579 if (!Subtarget->isThumb1Only())
580 setTargetDAGCombine(ISD::ADDC);
583 computeRegisterProperties();
585 // ARM does not have f32 extending load.
586 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
588 // ARM does not have i1 sign extending load.
589 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
591 // ARM supports all 4 flavors of integer indexed load / store.
592 if (!Subtarget->isThumb1Only()) {
593 for (unsigned im = (unsigned)ISD::PRE_INC;
594 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
595 setIndexedLoadAction(im, MVT::i1, Legal);
596 setIndexedLoadAction(im, MVT::i8, Legal);
597 setIndexedLoadAction(im, MVT::i16, Legal);
598 setIndexedLoadAction(im, MVT::i32, Legal);
599 setIndexedStoreAction(im, MVT::i1, Legal);
600 setIndexedStoreAction(im, MVT::i8, Legal);
601 setIndexedStoreAction(im, MVT::i16, Legal);
602 setIndexedStoreAction(im, MVT::i32, Legal);
606 setOperationAction(ISD::SADDO, MVT::i32, Custom);
607 setOperationAction(ISD::UADDO, MVT::i32, Custom);
608 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
609 setOperationAction(ISD::USUBO, MVT::i32, Custom);
611 // i64 operation support.
612 setOperationAction(ISD::MUL, MVT::i64, Expand);
613 setOperationAction(ISD::MULHU, MVT::i32, Expand);
614 if (Subtarget->isThumb1Only()) {
615 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
616 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
618 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
619 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
620 setOperationAction(ISD::MULHS, MVT::i32, Expand);
622 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
623 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
624 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
625 setOperationAction(ISD::SRL, MVT::i64, Custom);
626 setOperationAction(ISD::SRA, MVT::i64, Custom);
628 if (!Subtarget->isThumb1Only()) {
629 // FIXME: We should do this for Thumb1 as well.
630 setOperationAction(ISD::ADDC, MVT::i32, Custom);
631 setOperationAction(ISD::ADDE, MVT::i32, Custom);
632 setOperationAction(ISD::SUBC, MVT::i32, Custom);
633 setOperationAction(ISD::SUBE, MVT::i32, Custom);
636 // ARM does not have ROTL.
637 setOperationAction(ISD::ROTL, MVT::i32, Expand);
638 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
639 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
640 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
641 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
643 // These just redirect to CTTZ and CTLZ on ARM.
644 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
645 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
647 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
649 // Only ARMv6 has BSWAP.
650 if (!Subtarget->hasV6Ops())
651 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
653 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
654 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
655 // These are expanded into libcalls if the cpu doesn't have HW divider.
656 setOperationAction(ISD::SDIV, MVT::i32, Expand);
657 setOperationAction(ISD::UDIV, MVT::i32, Expand);
660 // FIXME: Also set divmod for SREM on EABI
661 setOperationAction(ISD::SREM, MVT::i32, Expand);
662 setOperationAction(ISD::UREM, MVT::i32, Expand);
663 // Register based DivRem for AEABI (RTABI 4.2)
664 if (Subtarget->isTargetAEABI()) {
665 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
666 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
667 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
668 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
669 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
670 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
671 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
672 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
674 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
675 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
676 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
677 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
678 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
679 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
680 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
681 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
683 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
684 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
686 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
687 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
690 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
691 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
692 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
693 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
694 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
696 setOperationAction(ISD::TRAP, MVT::Other, Legal);
698 // Use the default implementation.
699 setOperationAction(ISD::VASTART, MVT::Other, Custom);
700 setOperationAction(ISD::VAARG, MVT::Other, Expand);
701 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
702 setOperationAction(ISD::VAEND, MVT::Other, Expand);
703 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
704 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
706 if (!Subtarget->isTargetMachO()) {
707 // Non-MachO platforms may return values in these registers via the
708 // personality function.
709 setExceptionPointerRegister(ARM::R0);
710 setExceptionSelectorRegister(ARM::R1);
713 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
714 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
716 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
718 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
719 // the default expansion.
720 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
721 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
722 // to ldrex/strex loops already.
723 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
725 // On v8, we have particularly efficient implementations of atomic fences
726 // if they can be combined with nearby atomic loads and stores.
727 if (!Subtarget->hasV8Ops()) {
728 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
729 setInsertFencesForAtomic(true);
732 // If there's anything we can use as a barrier, go through custom lowering
734 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
735 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
737 // Set them all for expansion, which will force libcalls.
738 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
739 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
740 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
741 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
742 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
743 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
744 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
745 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
746 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
747 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
748 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
749 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
750 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
751 // Unordered/Monotonic case.
752 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
753 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
756 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
758 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
759 if (!Subtarget->hasV6Ops()) {
760 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
761 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
763 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
765 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
766 !Subtarget->isThumb1Only()) {
767 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
768 // iff target supports vfp2.
769 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
770 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
773 // We want to custom lower some of our intrinsics.
774 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
775 if (Subtarget->isTargetDarwin()) {
776 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
777 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
778 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
781 setOperationAction(ISD::SETCC, MVT::i32, Expand);
782 setOperationAction(ISD::SETCC, MVT::f32, Expand);
783 setOperationAction(ISD::SETCC, MVT::f64, Expand);
784 setOperationAction(ISD::SELECT, MVT::i32, Custom);
785 setOperationAction(ISD::SELECT, MVT::f32, Custom);
786 setOperationAction(ISD::SELECT, MVT::f64, Custom);
787 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
788 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
789 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
791 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
792 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
793 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
794 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
795 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
797 // We don't support sin/cos/fmod/copysign/pow
798 setOperationAction(ISD::FSIN, MVT::f64, Expand);
799 setOperationAction(ISD::FSIN, MVT::f32, Expand);
800 setOperationAction(ISD::FCOS, MVT::f32, Expand);
801 setOperationAction(ISD::FCOS, MVT::f64, Expand);
802 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
803 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
804 setOperationAction(ISD::FREM, MVT::f64, Expand);
805 setOperationAction(ISD::FREM, MVT::f32, Expand);
806 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
807 !Subtarget->isThumb1Only()) {
808 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
809 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
811 setOperationAction(ISD::FPOW, MVT::f64, Expand);
812 setOperationAction(ISD::FPOW, MVT::f32, Expand);
814 if (!Subtarget->hasVFP4()) {
815 setOperationAction(ISD::FMA, MVT::f64, Expand);
816 setOperationAction(ISD::FMA, MVT::f32, Expand);
819 // Various VFP goodness
820 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
821 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
822 if (Subtarget->hasVFP2()) {
823 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
824 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
825 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
826 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
828 // Special handling for half-precision FP.
829 if (!Subtarget->hasFP16()) {
830 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
831 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
835 // Combine sin / cos into one node or libcall if possible.
836 if (Subtarget->hasSinCos()) {
837 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
838 setLibcallName(RTLIB::SINCOS_F64, "sincos");
839 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
840 // For iOS, we don't want to the normal expansion of a libcall to
841 // sincos. We want to issue a libcall to __sincos_stret.
842 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
843 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
847 // We have target-specific dag combine patterns for the following nodes:
848 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
849 setTargetDAGCombine(ISD::ADD);
850 setTargetDAGCombine(ISD::SUB);
851 setTargetDAGCombine(ISD::MUL);
852 setTargetDAGCombine(ISD::AND);
853 setTargetDAGCombine(ISD::OR);
854 setTargetDAGCombine(ISD::XOR);
856 if (Subtarget->hasV6Ops())
857 setTargetDAGCombine(ISD::SRL);
859 setStackPointerRegisterToSaveRestore(ARM::SP);
861 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
862 !Subtarget->hasVFP2())
863 setSchedulingPreference(Sched::RegPressure);
865 setSchedulingPreference(Sched::Hybrid);
867 //// temporary - rewrite interface to use type
868 MaxStoresPerMemset = 8;
869 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
870 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
871 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
872 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
873 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
875 // On ARM arguments smaller than 4 bytes are extended, so all arguments
876 // are at least 4 bytes aligned.
877 setMinStackArgumentAlignment(4);
879 // Prefer likely predicted branches to selects on out-of-order cores.
880 PredictableSelectIsExpensive = Subtarget->isLikeA9();
882 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
885 // FIXME: It might make sense to define the representative register class as the
886 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
887 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
888 // SPR's representative would be DPR_VFP2. This should work well if register
889 // pressure tracking were modified such that a register use would increment the
890 // pressure of the register class's representative and all of it's super
891 // classes' representatives transitively. We have not implemented this because
892 // of the difficulty prior to coalescing of modeling operand register classes
893 // due to the common occurrence of cross class copies and subregister insertions
895 std::pair<const TargetRegisterClass*, uint8_t>
896 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
897 const TargetRegisterClass *RRC = nullptr;
899 switch (VT.SimpleTy) {
901 return TargetLowering::findRepresentativeClass(VT);
902 // Use DPR as representative register class for all floating point
903 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
904 // the cost is 1 for both f32 and f64.
905 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
906 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
907 RRC = &ARM::DPRRegClass;
908 // When NEON is used for SP, only half of the register file is available
909 // because operations that define both SP and DP results will be constrained
910 // to the VFP2 class (D0-D15). We currently model this constraint prior to
911 // coalescing by double-counting the SP regs. See the FIXME above.
912 if (Subtarget->useNEONForSinglePrecisionFP())
915 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
916 case MVT::v4f32: case MVT::v2f64:
917 RRC = &ARM::DPRRegClass;
921 RRC = &ARM::DPRRegClass;
925 RRC = &ARM::DPRRegClass;
929 return std::make_pair(RRC, Cost);
932 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
934 default: return nullptr;
935 case ARMISD::Wrapper: return "ARMISD::Wrapper";
936 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
937 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
938 case ARMISD::CALL: return "ARMISD::CALL";
939 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
940 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
941 case ARMISD::tCALL: return "ARMISD::tCALL";
942 case ARMISD::BRCOND: return "ARMISD::BRCOND";
943 case ARMISD::BR_JT: return "ARMISD::BR_JT";
944 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
945 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
946 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
947 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
948 case ARMISD::CMP: return "ARMISD::CMP";
949 case ARMISD::CMN: return "ARMISD::CMN";
950 case ARMISD::CMPZ: return "ARMISD::CMPZ";
951 case ARMISD::CMPFP: return "ARMISD::CMPFP";
952 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
953 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
954 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
956 case ARMISD::CMOV: return "ARMISD::CMOV";
958 case ARMISD::RBIT: return "ARMISD::RBIT";
960 case ARMISD::FTOSI: return "ARMISD::FTOSI";
961 case ARMISD::FTOUI: return "ARMISD::FTOUI";
962 case ARMISD::SITOF: return "ARMISD::SITOF";
963 case ARMISD::UITOF: return "ARMISD::UITOF";
965 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
966 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
967 case ARMISD::RRX: return "ARMISD::RRX";
969 case ARMISD::ADDC: return "ARMISD::ADDC";
970 case ARMISD::ADDE: return "ARMISD::ADDE";
971 case ARMISD::SUBC: return "ARMISD::SUBC";
972 case ARMISD::SUBE: return "ARMISD::SUBE";
974 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
975 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
977 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
978 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
980 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
982 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
984 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
986 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
988 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
990 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
992 case ARMISD::VCEQ: return "ARMISD::VCEQ";
993 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
994 case ARMISD::VCGE: return "ARMISD::VCGE";
995 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
996 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
997 case ARMISD::VCGEU: return "ARMISD::VCGEU";
998 case ARMISD::VCGT: return "ARMISD::VCGT";
999 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1000 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1001 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1002 case ARMISD::VTST: return "ARMISD::VTST";
1004 case ARMISD::VSHL: return "ARMISD::VSHL";
1005 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1006 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1007 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1008 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1009 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1010 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1011 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1012 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1013 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1014 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1015 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1016 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1017 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1018 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1019 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1020 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1021 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1022 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1023 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1024 case ARMISD::VDUP: return "ARMISD::VDUP";
1025 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1026 case ARMISD::VEXT: return "ARMISD::VEXT";
1027 case ARMISD::VREV64: return "ARMISD::VREV64";
1028 case ARMISD::VREV32: return "ARMISD::VREV32";
1029 case ARMISD::VREV16: return "ARMISD::VREV16";
1030 case ARMISD::VZIP: return "ARMISD::VZIP";
1031 case ARMISD::VUZP: return "ARMISD::VUZP";
1032 case ARMISD::VTRN: return "ARMISD::VTRN";
1033 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1034 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1035 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1036 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1037 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1038 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1039 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1040 case ARMISD::FMAX: return "ARMISD::FMAX";
1041 case ARMISD::FMIN: return "ARMISD::FMIN";
1042 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1043 case ARMISD::VMINNM: return "ARMISD::VMIN";
1044 case ARMISD::BFI: return "ARMISD::BFI";
1045 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1046 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1047 case ARMISD::VBSL: return "ARMISD::VBSL";
1048 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1049 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1050 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1051 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1052 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1053 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1054 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1055 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1056 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1057 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1058 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1059 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1060 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1061 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1062 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1063 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1064 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1065 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1066 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1067 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1071 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1072 if (!VT.isVector()) return getPointerTy();
1073 return VT.changeVectorElementTypeToInteger();
1076 /// getRegClassFor - Return the register class that should be used for the
1077 /// specified value type.
1078 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1079 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1080 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1081 // load / store 4 to 8 consecutive D registers.
1082 if (Subtarget->hasNEON()) {
1083 if (VT == MVT::v4i64)
1084 return &ARM::QQPRRegClass;
1085 if (VT == MVT::v8i64)
1086 return &ARM::QQQQPRRegClass;
1088 return TargetLowering::getRegClassFor(VT);
1091 // Create a fast isel object.
1093 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1094 const TargetLibraryInfo *libInfo) const {
1095 return ARM::createFastISel(funcInfo, libInfo);
1098 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1099 /// be used for loads / stores from the global.
1100 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1101 return (Subtarget->isThumb1Only() ? 127 : 4095);
1104 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1105 unsigned NumVals = N->getNumValues();
1107 return Sched::RegPressure;
1109 for (unsigned i = 0; i != NumVals; ++i) {
1110 EVT VT = N->getValueType(i);
1111 if (VT == MVT::Glue || VT == MVT::Other)
1113 if (VT.isFloatingPoint() || VT.isVector())
1117 if (!N->isMachineOpcode())
1118 return Sched::RegPressure;
1120 // Load are scheduled for latency even if there instruction itinerary
1121 // is not available.
1122 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1123 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1125 if (MCID.getNumDefs() == 0)
1126 return Sched::RegPressure;
1127 if (!Itins->isEmpty() &&
1128 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1131 return Sched::RegPressure;
1134 //===----------------------------------------------------------------------===//
1136 //===----------------------------------------------------------------------===//
1138 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1139 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1141 default: llvm_unreachable("Unknown condition code!");
1142 case ISD::SETNE: return ARMCC::NE;
1143 case ISD::SETEQ: return ARMCC::EQ;
1144 case ISD::SETGT: return ARMCC::GT;
1145 case ISD::SETGE: return ARMCC::GE;
1146 case ISD::SETLT: return ARMCC::LT;
1147 case ISD::SETLE: return ARMCC::LE;
1148 case ISD::SETUGT: return ARMCC::HI;
1149 case ISD::SETUGE: return ARMCC::HS;
1150 case ISD::SETULT: return ARMCC::LO;
1151 case ISD::SETULE: return ARMCC::LS;
1155 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1156 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1157 ARMCC::CondCodes &CondCode2) {
1158 CondCode2 = ARMCC::AL;
1160 default: llvm_unreachable("Unknown FP condition!");
1162 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1164 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1166 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1167 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1168 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1169 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1170 case ISD::SETO: CondCode = ARMCC::VC; break;
1171 case ISD::SETUO: CondCode = ARMCC::VS; break;
1172 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1173 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1174 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1176 case ISD::SETULT: CondCode = ARMCC::LT; break;
1178 case ISD::SETULE: CondCode = ARMCC::LE; break;
1180 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1184 //===----------------------------------------------------------------------===//
1185 // Calling Convention Implementation
1186 //===----------------------------------------------------------------------===//
1188 #include "ARMGenCallingConv.inc"
1190 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1191 /// account presence of floating point hardware and calling convention
1192 /// limitations, such as support for variadic functions.
1194 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1195 bool isVarArg) const {
1198 llvm_unreachable("Unsupported calling convention");
1199 case CallingConv::ARM_AAPCS:
1200 case CallingConv::ARM_APCS:
1201 case CallingConv::GHC:
1203 case CallingConv::ARM_AAPCS_VFP:
1204 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1205 case CallingConv::C:
1206 if (!Subtarget->isAAPCS_ABI())
1207 return CallingConv::ARM_APCS;
1208 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1209 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1211 return CallingConv::ARM_AAPCS_VFP;
1213 return CallingConv::ARM_AAPCS;
1214 case CallingConv::Fast:
1215 if (!Subtarget->isAAPCS_ABI()) {
1216 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1217 return CallingConv::Fast;
1218 return CallingConv::ARM_APCS;
1219 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1220 return CallingConv::ARM_AAPCS_VFP;
1222 return CallingConv::ARM_AAPCS;
1226 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1227 /// CallingConvention.
1228 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1230 bool isVarArg) const {
1231 switch (getEffectiveCallingConv(CC, isVarArg)) {
1233 llvm_unreachable("Unsupported calling convention");
1234 case CallingConv::ARM_APCS:
1235 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1236 case CallingConv::ARM_AAPCS:
1237 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1238 case CallingConv::ARM_AAPCS_VFP:
1239 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1240 case CallingConv::Fast:
1241 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1242 case CallingConv::GHC:
1243 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1247 /// LowerCallResult - Lower the result values of a call into the
1248 /// appropriate copies out of appropriate physical registers.
1250 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1251 CallingConv::ID CallConv, bool isVarArg,
1252 const SmallVectorImpl<ISD::InputArg> &Ins,
1253 SDLoc dl, SelectionDAG &DAG,
1254 SmallVectorImpl<SDValue> &InVals,
1255 bool isThisReturn, SDValue ThisVal) const {
1257 // Assign locations to each value returned by this call.
1258 SmallVector<CCValAssign, 16> RVLocs;
1259 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1260 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1261 CCInfo.AnalyzeCallResult(Ins,
1262 CCAssignFnForNode(CallConv, /* Return*/ true,
1265 // Copy all of the result registers out of their specified physreg.
1266 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1267 CCValAssign VA = RVLocs[i];
1269 // Pass 'this' value directly from the argument to return value, to avoid
1270 // reg unit interference
1271 if (i == 0 && isThisReturn) {
1272 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1273 "unexpected return calling convention register assignment");
1274 InVals.push_back(ThisVal);
1279 if (VA.needsCustom()) {
1280 // Handle f64 or half of a v2f64.
1281 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1283 Chain = Lo.getValue(1);
1284 InFlag = Lo.getValue(2);
1285 VA = RVLocs[++i]; // skip ahead to next loc
1286 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1288 Chain = Hi.getValue(1);
1289 InFlag = Hi.getValue(2);
1290 if (!Subtarget->isLittle())
1292 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1294 if (VA.getLocVT() == MVT::v2f64) {
1295 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1296 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1297 DAG.getConstant(0, MVT::i32));
1299 VA = RVLocs[++i]; // skip ahead to next loc
1300 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1301 Chain = Lo.getValue(1);
1302 InFlag = Lo.getValue(2);
1303 VA = RVLocs[++i]; // skip ahead to next loc
1304 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1305 Chain = Hi.getValue(1);
1306 InFlag = Hi.getValue(2);
1307 if (!Subtarget->isLittle())
1309 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1310 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1311 DAG.getConstant(1, MVT::i32));
1314 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1316 Chain = Val.getValue(1);
1317 InFlag = Val.getValue(2);
1320 switch (VA.getLocInfo()) {
1321 default: llvm_unreachable("Unknown loc info!");
1322 case CCValAssign::Full: break;
1323 case CCValAssign::BCvt:
1324 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1328 InVals.push_back(Val);
1334 /// LowerMemOpCallTo - Store the argument to the stack.
1336 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1337 SDValue StackPtr, SDValue Arg,
1338 SDLoc dl, SelectionDAG &DAG,
1339 const CCValAssign &VA,
1340 ISD::ArgFlagsTy Flags) const {
1341 unsigned LocMemOffset = VA.getLocMemOffset();
1342 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1343 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1344 return DAG.getStore(Chain, dl, Arg, PtrOff,
1345 MachinePointerInfo::getStack(LocMemOffset),
1349 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1350 SDValue Chain, SDValue &Arg,
1351 RegsToPassVector &RegsToPass,
1352 CCValAssign &VA, CCValAssign &NextVA,
1354 SmallVectorImpl<SDValue> &MemOpChains,
1355 ISD::ArgFlagsTy Flags) const {
1357 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1358 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1359 unsigned id = Subtarget->isLittle() ? 0 : 1;
1360 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1362 if (NextVA.isRegLoc())
1363 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1365 assert(NextVA.isMemLoc());
1366 if (!StackPtr.getNode())
1367 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1369 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1375 /// LowerCall - Lowering a call into a callseq_start <-
1376 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1379 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1380 SmallVectorImpl<SDValue> &InVals) const {
1381 SelectionDAG &DAG = CLI.DAG;
1383 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1384 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1385 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1386 SDValue Chain = CLI.Chain;
1387 SDValue Callee = CLI.Callee;
1388 bool &isTailCall = CLI.IsTailCall;
1389 CallingConv::ID CallConv = CLI.CallConv;
1390 bool doesNotRet = CLI.DoesNotReturn;
1391 bool isVarArg = CLI.IsVarArg;
1393 MachineFunction &MF = DAG.getMachineFunction();
1394 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1395 bool isThisReturn = false;
1396 bool isSibCall = false;
1398 // Disable tail calls if they're not supported.
1399 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1403 // Check if it's really possible to do a tail call.
1404 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1405 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1406 Outs, OutVals, Ins, DAG);
1407 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1408 report_fatal_error("failed to perform tail call elimination on a call "
1409 "site marked musttail");
1410 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1411 // detected sibcalls.
1418 // Analyze operands of the call, assigning locations to each operand.
1419 SmallVector<CCValAssign, 16> ArgLocs;
1420 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1421 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1422 CCInfo.AnalyzeCallOperands(Outs,
1423 CCAssignFnForNode(CallConv, /* Return*/ false,
1426 // Get a count of how many bytes are to be pushed on the stack.
1427 unsigned NumBytes = CCInfo.getNextStackOffset();
1429 // For tail calls, memory operands are available in our caller's stack.
1433 // Adjust the stack pointer for the new arguments...
1434 // These operations are automatically eliminated by the prolog/epilog pass
1436 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1439 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1441 RegsToPassVector RegsToPass;
1442 SmallVector<SDValue, 8> MemOpChains;
1444 // Walk the register/memloc assignments, inserting copies/loads. In the case
1445 // of tail call optimization, arguments are handled later.
1446 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1448 ++i, ++realArgIdx) {
1449 CCValAssign &VA = ArgLocs[i];
1450 SDValue Arg = OutVals[realArgIdx];
1451 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1452 bool isByVal = Flags.isByVal();
1454 // Promote the value if needed.
1455 switch (VA.getLocInfo()) {
1456 default: llvm_unreachable("Unknown loc info!");
1457 case CCValAssign::Full: break;
1458 case CCValAssign::SExt:
1459 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1461 case CCValAssign::ZExt:
1462 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1464 case CCValAssign::AExt:
1465 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1467 case CCValAssign::BCvt:
1468 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1472 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1473 if (VA.needsCustom()) {
1474 if (VA.getLocVT() == MVT::v2f64) {
1475 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1476 DAG.getConstant(0, MVT::i32));
1477 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1478 DAG.getConstant(1, MVT::i32));
1480 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1481 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1483 VA = ArgLocs[++i]; // skip ahead to next loc
1484 if (VA.isRegLoc()) {
1485 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1486 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1488 assert(VA.isMemLoc());
1490 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1491 dl, DAG, VA, Flags));
1494 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1495 StackPtr, MemOpChains, Flags);
1497 } else if (VA.isRegLoc()) {
1498 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1499 assert(VA.getLocVT() == MVT::i32 &&
1500 "unexpected calling convention register assignment");
1501 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1502 "unexpected use of 'returned'");
1503 isThisReturn = true;
1505 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1506 } else if (isByVal) {
1507 assert(VA.isMemLoc());
1508 unsigned offset = 0;
1510 // True if this byval aggregate will be split between registers
1512 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1513 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1515 if (CurByValIdx < ByValArgsCount) {
1517 unsigned RegBegin, RegEnd;
1518 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1520 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1522 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1523 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1524 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1525 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1526 MachinePointerInfo(),
1527 false, false, false,
1528 DAG.InferPtrAlignment(AddArg));
1529 MemOpChains.push_back(Load.getValue(1));
1530 RegsToPass.push_back(std::make_pair(j, Load));
1533 // If parameter size outsides register area, "offset" value
1534 // helps us to calculate stack slot for remained part properly.
1535 offset = RegEnd - RegBegin;
1537 CCInfo.nextInRegsParam();
1540 if (Flags.getByValSize() > 4*offset) {
1541 unsigned LocMemOffset = VA.getLocMemOffset();
1542 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1543 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1545 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1546 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1547 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1549 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1551 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1552 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1553 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1556 } else if (!isSibCall) {
1557 assert(VA.isMemLoc());
1559 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1560 dl, DAG, VA, Flags));
1564 if (!MemOpChains.empty())
1565 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1567 // Build a sequence of copy-to-reg nodes chained together with token chain
1568 // and flag operands which copy the outgoing args into the appropriate regs.
1570 // Tail call byval lowering might overwrite argument registers so in case of
1571 // tail call optimization the copies to registers are lowered later.
1573 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1574 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1575 RegsToPass[i].second, InFlag);
1576 InFlag = Chain.getValue(1);
1579 // For tail calls lower the arguments to the 'real' stack slot.
1581 // Force all the incoming stack arguments to be loaded from the stack
1582 // before any new outgoing arguments are stored to the stack, because the
1583 // outgoing stack slots may alias the incoming argument stack slots, and
1584 // the alias isn't otherwise explicit. This is slightly more conservative
1585 // than necessary, because it means that each store effectively depends
1586 // on every argument instead of just those arguments it would clobber.
1588 // Do not flag preceding copytoreg stuff together with the following stuff.
1590 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1591 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1592 RegsToPass[i].second, InFlag);
1593 InFlag = Chain.getValue(1);
1598 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1599 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1600 // node so that legalize doesn't hack it.
1601 bool isDirect = false;
1602 bool isARMFunc = false;
1603 bool isLocalARMFunc = false;
1604 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1606 if (EnableARMLongCalls) {
1607 assert((Subtarget->isTargetWindows() ||
1608 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1609 "long-calls with non-static relocation model!");
1610 // Handle a global address or an external symbol. If it's not one of
1611 // those, the target's already in a register, so we don't need to do
1613 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1614 const GlobalValue *GV = G->getGlobal();
1615 // Create a constant pool entry for the callee address
1616 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1617 ARMConstantPoolValue *CPV =
1618 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1620 // Get the address of the callee into a register
1621 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1622 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1623 Callee = DAG.getLoad(getPointerTy(), dl,
1624 DAG.getEntryNode(), CPAddr,
1625 MachinePointerInfo::getConstantPool(),
1626 false, false, false, 0);
1627 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1628 const char *Sym = S->getSymbol();
1630 // Create a constant pool entry for the callee address
1631 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1632 ARMConstantPoolValue *CPV =
1633 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1634 ARMPCLabelIndex, 0);
1635 // Get the address of the callee into a register
1636 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1637 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1638 Callee = DAG.getLoad(getPointerTy(), dl,
1639 DAG.getEntryNode(), CPAddr,
1640 MachinePointerInfo::getConstantPool(),
1641 false, false, false, 0);
1643 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1644 const GlobalValue *GV = G->getGlobal();
1646 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1647 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1648 getTargetMachine().getRelocationModel() != Reloc::Static;
1649 isARMFunc = !Subtarget->isThumb() || isStub;
1650 // ARM call to a local ARM function is predicable.
1651 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1652 // tBX takes a register source operand.
1653 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1654 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1655 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1656 DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1658 // On ELF targets for PIC code, direct calls should go through the PLT
1659 unsigned OpFlags = 0;
1660 if (Subtarget->isTargetELF() &&
1661 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1662 OpFlags = ARMII::MO_PLT;
1663 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1665 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1667 bool isStub = Subtarget->isTargetMachO() &&
1668 getTargetMachine().getRelocationModel() != Reloc::Static;
1669 isARMFunc = !Subtarget->isThumb() || isStub;
1670 // tBX takes a register source operand.
1671 const char *Sym = S->getSymbol();
1672 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1673 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1674 ARMConstantPoolValue *CPV =
1675 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1676 ARMPCLabelIndex, 4);
1677 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1678 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1679 Callee = DAG.getLoad(getPointerTy(), dl,
1680 DAG.getEntryNode(), CPAddr,
1681 MachinePointerInfo::getConstantPool(),
1682 false, false, false, 0);
1683 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1684 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1685 getPointerTy(), Callee, PICLabel);
1687 unsigned OpFlags = 0;
1688 // On ELF targets for PIC code, direct calls should go through the PLT
1689 if (Subtarget->isTargetELF() &&
1690 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1691 OpFlags = ARMII::MO_PLT;
1692 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1696 // FIXME: handle tail calls differently.
1698 bool HasMinSizeAttr = Subtarget->isMinSize();
1699 if (Subtarget->isThumb()) {
1700 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1701 CallOpc = ARMISD::CALL_NOLINK;
1703 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1705 if (!isDirect && !Subtarget->hasV5TOps())
1706 CallOpc = ARMISD::CALL_NOLINK;
1707 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1708 // Emit regular call when code size is the priority
1710 // "mov lr, pc; b _foo" to avoid confusing the RSP
1711 CallOpc = ARMISD::CALL_NOLINK;
1713 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1716 std::vector<SDValue> Ops;
1717 Ops.push_back(Chain);
1718 Ops.push_back(Callee);
1720 // Add argument registers to the end of the list so that they are known live
1722 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1723 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1724 RegsToPass[i].second.getValueType()));
1726 // Add a register mask operand representing the call-preserved registers.
1728 const uint32_t *Mask;
1729 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1730 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1732 // For 'this' returns, use the R0-preserving mask if applicable
1733 Mask = ARI->getThisReturnPreservedMask(CallConv);
1735 // Set isThisReturn to false if the calling convention is not one that
1736 // allows 'returned' to be modeled in this way, so LowerCallResult does
1737 // not try to pass 'this' straight through
1738 isThisReturn = false;
1739 Mask = ARI->getCallPreservedMask(CallConv);
1742 Mask = ARI->getCallPreservedMask(CallConv);
1744 assert(Mask && "Missing call preserved mask for calling convention");
1745 Ops.push_back(DAG.getRegisterMask(Mask));
1748 if (InFlag.getNode())
1749 Ops.push_back(InFlag);
1751 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1753 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1755 // Returns a chain and a flag for retval copy to use.
1756 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1757 InFlag = Chain.getValue(1);
1759 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1760 DAG.getIntPtrConstant(0, true), InFlag, dl);
1762 InFlag = Chain.getValue(1);
1764 // Handle result values, copying them out of physregs into vregs that we
1766 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1767 InVals, isThisReturn,
1768 isThisReturn ? OutVals[0] : SDValue());
1771 /// HandleByVal - Every parameter *after* a byval parameter is passed
1772 /// on the stack. Remember the next parameter register to allocate,
1773 /// and then confiscate the rest of the parameter registers to insure
1776 ARMTargetLowering::HandleByVal(
1777 CCState *State, unsigned &size, unsigned Align) const {
1778 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1779 assert((State->getCallOrPrologue() == Prologue ||
1780 State->getCallOrPrologue() == Call) &&
1781 "unhandled ParmContext");
1783 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1784 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1785 unsigned AlignInRegs = Align / 4;
1786 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1787 for (unsigned i = 0; i < Waste; ++i)
1788 reg = State->AllocateReg(GPRArgRegs, 4);
1791 unsigned excess = 4 * (ARM::R4 - reg);
1793 // Special case when NSAA != SP and parameter size greater than size of
1794 // all remained GPR regs. In that case we can't split parameter, we must
1795 // send it to stack. We also must set NCRN to R4, so waste all
1796 // remained registers.
1797 const unsigned NSAAOffset = State->getNextStackOffset();
1798 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1799 while (State->AllocateReg(GPRArgRegs, 4))
1804 // First register for byval parameter is the first register that wasn't
1805 // allocated before this method call, so it would be "reg".
1806 // If parameter is small enough to be saved in range [reg, r4), then
1807 // the end (first after last) register would be reg + param-size-in-regs,
1808 // else parameter would be splitted between registers and stack,
1809 // end register would be r4 in this case.
1810 unsigned ByValRegBegin = reg;
1811 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1812 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1813 // Note, first register is allocated in the beginning of function already,
1814 // allocate remained amount of registers we need.
1815 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1816 State->AllocateReg(GPRArgRegs, 4);
1817 // A byval parameter that is split between registers and memory needs its
1818 // size truncated here.
1819 // In the case where the entire structure fits in registers, we set the
1820 // size in memory to zero.
1829 /// MatchingStackOffset - Return true if the given stack call argument is
1830 /// already available in the same position (relatively) of the caller's
1831 /// incoming argument stack.
1833 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1834 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1835 const TargetInstrInfo *TII) {
1836 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1838 if (Arg.getOpcode() == ISD::CopyFromReg) {
1839 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1840 if (!TargetRegisterInfo::isVirtualRegister(VR))
1842 MachineInstr *Def = MRI->getVRegDef(VR);
1845 if (!Flags.isByVal()) {
1846 if (!TII->isLoadFromStackSlot(Def, FI))
1851 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1852 if (Flags.isByVal())
1853 // ByVal argument is passed in as a pointer but it's now being
1854 // dereferenced. e.g.
1855 // define @foo(%struct.X* %A) {
1856 // tail call @bar(%struct.X* byval %A)
1859 SDValue Ptr = Ld->getBasePtr();
1860 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1863 FI = FINode->getIndex();
1867 assert(FI != INT_MAX);
1868 if (!MFI->isFixedObjectIndex(FI))
1870 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1873 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1874 /// for tail call optimization. Targets which want to do tail call
1875 /// optimization should implement this function.
1877 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1878 CallingConv::ID CalleeCC,
1880 bool isCalleeStructRet,
1881 bool isCallerStructRet,
1882 const SmallVectorImpl<ISD::OutputArg> &Outs,
1883 const SmallVectorImpl<SDValue> &OutVals,
1884 const SmallVectorImpl<ISD::InputArg> &Ins,
1885 SelectionDAG& DAG) const {
1886 const Function *CallerF = DAG.getMachineFunction().getFunction();
1887 CallingConv::ID CallerCC = CallerF->getCallingConv();
1888 bool CCMatch = CallerCC == CalleeCC;
1890 // Look for obvious safe cases to perform tail call optimization that do not
1891 // require ABI changes. This is what gcc calls sibcall.
1893 // Do not sibcall optimize vararg calls unless the call site is not passing
1895 if (isVarArg && !Outs.empty())
1898 // Exception-handling functions need a special set of instructions to indicate
1899 // a return to the hardware. Tail-calling another function would probably
1901 if (CallerF->hasFnAttribute("interrupt"))
1904 // Also avoid sibcall optimization if either caller or callee uses struct
1905 // return semantics.
1906 if (isCalleeStructRet || isCallerStructRet)
1909 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1910 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1911 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1912 // support in the assembler and linker to be used. This would need to be
1913 // fixed to fully support tail calls in Thumb1.
1915 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1916 // LR. This means if we need to reload LR, it takes an extra instructions,
1917 // which outweighs the value of the tail call; but here we don't know yet
1918 // whether LR is going to be used. Probably the right approach is to
1919 // generate the tail call here and turn it back into CALL/RET in
1920 // emitEpilogue if LR is used.
1922 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1923 // but we need to make sure there are enough registers; the only valid
1924 // registers are the 4 used for parameters. We don't currently do this
1926 if (Subtarget->isThumb1Only())
1929 // If the calling conventions do not match, then we'd better make sure the
1930 // results are returned in the same way as what the caller expects.
1932 SmallVector<CCValAssign, 16> RVLocs1;
1933 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1934 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1935 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1937 SmallVector<CCValAssign, 16> RVLocs2;
1938 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1939 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1940 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1942 if (RVLocs1.size() != RVLocs2.size())
1944 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1945 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1947 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1949 if (RVLocs1[i].isRegLoc()) {
1950 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1953 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1959 // If Caller's vararg or byval argument has been split between registers and
1960 // stack, do not perform tail call, since part of the argument is in caller's
1962 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1963 getInfo<ARMFunctionInfo>();
1964 if (AFI_Caller->getArgRegsSaveSize())
1967 // If the callee takes no arguments then go on to check the results of the
1969 if (!Outs.empty()) {
1970 // Check if stack adjustment is needed. For now, do not do this if any
1971 // argument is passed on the stack.
1972 SmallVector<CCValAssign, 16> ArgLocs;
1973 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1974 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1975 CCInfo.AnalyzeCallOperands(Outs,
1976 CCAssignFnForNode(CalleeCC, false, isVarArg));
1977 if (CCInfo.getNextStackOffset()) {
1978 MachineFunction &MF = DAG.getMachineFunction();
1980 // Check if the arguments are already laid out in the right way as
1981 // the caller's fixed stack objects.
1982 MachineFrameInfo *MFI = MF.getFrameInfo();
1983 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1984 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1985 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1987 ++i, ++realArgIdx) {
1988 CCValAssign &VA = ArgLocs[i];
1989 EVT RegVT = VA.getLocVT();
1990 SDValue Arg = OutVals[realArgIdx];
1991 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1992 if (VA.getLocInfo() == CCValAssign::Indirect)
1994 if (VA.needsCustom()) {
1995 // f64 and vector types are split into multiple registers or
1996 // register/stack-slot combinations. The types will not match
1997 // the registers; give up on memory f64 refs until we figure
1998 // out what to do about this.
2001 if (!ArgLocs[++i].isRegLoc())
2003 if (RegVT == MVT::v2f64) {
2004 if (!ArgLocs[++i].isRegLoc())
2006 if (!ArgLocs[++i].isRegLoc())
2009 } else if (!VA.isRegLoc()) {
2010 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2022 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2023 MachineFunction &MF, bool isVarArg,
2024 const SmallVectorImpl<ISD::OutputArg> &Outs,
2025 LLVMContext &Context) const {
2026 SmallVector<CCValAssign, 16> RVLocs;
2027 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2028 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2032 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2033 SDLoc DL, SelectionDAG &DAG) {
2034 const MachineFunction &MF = DAG.getMachineFunction();
2035 const Function *F = MF.getFunction();
2037 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2039 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2040 // version of the "preferred return address". These offsets affect the return
2041 // instruction if this is a return from PL1 without hypervisor extensions.
2042 // IRQ/FIQ: +4 "subs pc, lr, #4"
2043 // SWI: 0 "subs pc, lr, #0"
2044 // ABORT: +4 "subs pc, lr, #4"
2045 // UNDEF: +4/+2 "subs pc, lr, #0"
2046 // UNDEF varies depending on where the exception came from ARM or Thumb
2047 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2050 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2053 else if (IntKind == "SWI" || IntKind == "UNDEF")
2056 report_fatal_error("Unsupported interrupt attribute. If present, value "
2057 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2059 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2061 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2065 ARMTargetLowering::LowerReturn(SDValue Chain,
2066 CallingConv::ID CallConv, bool isVarArg,
2067 const SmallVectorImpl<ISD::OutputArg> &Outs,
2068 const SmallVectorImpl<SDValue> &OutVals,
2069 SDLoc dl, SelectionDAG &DAG) const {
2071 // CCValAssign - represent the assignment of the return value to a location.
2072 SmallVector<CCValAssign, 16> RVLocs;
2074 // CCState - Info about the registers and stack slots.
2075 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2076 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2078 // Analyze outgoing return values.
2079 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2083 SmallVector<SDValue, 4> RetOps;
2084 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2085 bool isLittleEndian = Subtarget->isLittle();
2087 // Copy the result values into the output registers.
2088 for (unsigned i = 0, realRVLocIdx = 0;
2090 ++i, ++realRVLocIdx) {
2091 CCValAssign &VA = RVLocs[i];
2092 assert(VA.isRegLoc() && "Can only return in registers!");
2094 SDValue Arg = OutVals[realRVLocIdx];
2096 switch (VA.getLocInfo()) {
2097 default: llvm_unreachable("Unknown loc info!");
2098 case CCValAssign::Full: break;
2099 case CCValAssign::BCvt:
2100 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2104 if (VA.needsCustom()) {
2105 if (VA.getLocVT() == MVT::v2f64) {
2106 // Extract the first half and return it in two registers.
2107 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2108 DAG.getConstant(0, MVT::i32));
2109 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2110 DAG.getVTList(MVT::i32, MVT::i32), Half);
2112 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2113 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2115 Flag = Chain.getValue(1);
2116 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2117 VA = RVLocs[++i]; // skip ahead to next loc
2118 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2119 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2121 Flag = Chain.getValue(1);
2122 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2123 VA = RVLocs[++i]; // skip ahead to next loc
2125 // Extract the 2nd half and fall through to handle it as an f64 value.
2126 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2127 DAG.getConstant(1, MVT::i32));
2129 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2131 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2132 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2133 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2134 fmrrd.getValue(isLittleEndian ? 0 : 1),
2136 Flag = Chain.getValue(1);
2137 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2138 VA = RVLocs[++i]; // skip ahead to next loc
2139 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2140 fmrrd.getValue(isLittleEndian ? 1 : 0),
2143 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2145 // Guarantee that all emitted copies are
2146 // stuck together, avoiding something bad.
2147 Flag = Chain.getValue(1);
2148 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2151 // Update chain and glue.
2154 RetOps.push_back(Flag);
2156 // CPUs which aren't M-class use a special sequence to return from
2157 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2158 // though we use "subs pc, lr, #N").
2160 // M-class CPUs actually use a normal return sequence with a special
2161 // (hardware-provided) value in LR, so the normal code path works.
2162 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2163 !Subtarget->isMClass()) {
2164 if (Subtarget->isThumb1Only())
2165 report_fatal_error("interrupt attribute is not supported in Thumb1");
2166 return LowerInterruptReturn(RetOps, dl, DAG);
2169 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2172 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2173 if (N->getNumValues() != 1)
2175 if (!N->hasNUsesOfValue(1, 0))
2178 SDValue TCChain = Chain;
2179 SDNode *Copy = *N->use_begin();
2180 if (Copy->getOpcode() == ISD::CopyToReg) {
2181 // If the copy has a glue operand, we conservatively assume it isn't safe to
2182 // perform a tail call.
2183 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2185 TCChain = Copy->getOperand(0);
2186 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2187 SDNode *VMov = Copy;
2188 // f64 returned in a pair of GPRs.
2189 SmallPtrSet<SDNode*, 2> Copies;
2190 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2192 if (UI->getOpcode() != ISD::CopyToReg)
2196 if (Copies.size() > 2)
2199 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2201 SDValue UseChain = UI->getOperand(0);
2202 if (Copies.count(UseChain.getNode()))
2209 } else if (Copy->getOpcode() == ISD::BITCAST) {
2210 // f32 returned in a single GPR.
2211 if (!Copy->hasOneUse())
2213 Copy = *Copy->use_begin();
2214 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2216 TCChain = Copy->getOperand(0);
2221 bool HasRet = false;
2222 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2224 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2225 UI->getOpcode() != ARMISD::INTRET_FLAG)
2237 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2238 if (!Subtarget->supportsTailCall())
2241 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2244 return !Subtarget->isThumb1Only();
2247 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2248 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2249 // one of the above mentioned nodes. It has to be wrapped because otherwise
2250 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2251 // be used to form addressing mode. These wrapped nodes will be selected
2253 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2254 EVT PtrVT = Op.getValueType();
2255 // FIXME there is no actual debug info here
2257 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2259 if (CP->isMachineConstantPoolEntry())
2260 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2261 CP->getAlignment());
2263 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2264 CP->getAlignment());
2265 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2268 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2269 return MachineJumpTableInfo::EK_Inline;
2272 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2273 SelectionDAG &DAG) const {
2274 MachineFunction &MF = DAG.getMachineFunction();
2275 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2276 unsigned ARMPCLabelIndex = 0;
2278 EVT PtrVT = getPointerTy();
2279 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2280 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2282 if (RelocM == Reloc::Static) {
2283 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2285 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2286 ARMPCLabelIndex = AFI->createPICLabelUId();
2287 ARMConstantPoolValue *CPV =
2288 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2289 ARMCP::CPBlockAddress, PCAdj);
2290 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2292 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2293 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2294 MachinePointerInfo::getConstantPool(),
2295 false, false, false, 0);
2296 if (RelocM == Reloc::Static)
2298 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2299 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2302 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2304 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2305 SelectionDAG &DAG) const {
2307 EVT PtrVT = getPointerTy();
2308 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2309 MachineFunction &MF = DAG.getMachineFunction();
2310 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2311 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2312 ARMConstantPoolValue *CPV =
2313 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2314 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2315 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2316 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2317 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2318 MachinePointerInfo::getConstantPool(),
2319 false, false, false, 0);
2320 SDValue Chain = Argument.getValue(1);
2322 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2323 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2325 // call __tls_get_addr.
2328 Entry.Node = Argument;
2329 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2330 Args.push_back(Entry);
2332 // FIXME: is there useful debug info available here?
2333 TargetLowering::CallLoweringInfo CLI(DAG);
2334 CLI.setDebugLoc(dl).setChain(Chain)
2335 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2336 DAG.getExternalSymbol("__tls_get_addr", PtrVT), &Args, 0);
2338 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2339 return CallResult.first;
2342 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2343 // "local exec" model.
2345 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2347 TLSModel::Model model) const {
2348 const GlobalValue *GV = GA->getGlobal();
2351 SDValue Chain = DAG.getEntryNode();
2352 EVT PtrVT = getPointerTy();
2353 // Get the Thread Pointer
2354 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2356 if (model == TLSModel::InitialExec) {
2357 MachineFunction &MF = DAG.getMachineFunction();
2358 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2359 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2360 // Initial exec model.
2361 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2362 ARMConstantPoolValue *CPV =
2363 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2364 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2366 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2367 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2368 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2369 MachinePointerInfo::getConstantPool(),
2370 false, false, false, 0);
2371 Chain = Offset.getValue(1);
2373 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2374 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2376 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2377 MachinePointerInfo::getConstantPool(),
2378 false, false, false, 0);
2381 assert(model == TLSModel::LocalExec);
2382 ARMConstantPoolValue *CPV =
2383 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2384 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2385 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2386 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2387 MachinePointerInfo::getConstantPool(),
2388 false, false, false, 0);
2391 // The address of the thread local variable is the add of the thread
2392 // pointer with the offset of the variable.
2393 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2397 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2398 // TODO: implement the "local dynamic" model
2399 assert(Subtarget->isTargetELF() &&
2400 "TLS not implemented for non-ELF targets");
2401 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2403 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2406 case TLSModel::GeneralDynamic:
2407 case TLSModel::LocalDynamic:
2408 return LowerToTLSGeneralDynamicModel(GA, DAG);
2409 case TLSModel::InitialExec:
2410 case TLSModel::LocalExec:
2411 return LowerToTLSExecModels(GA, DAG, model);
2413 llvm_unreachable("bogus TLS model");
2416 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2417 SelectionDAG &DAG) const {
2418 EVT PtrVT = getPointerTy();
2420 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2421 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2422 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2423 ARMConstantPoolValue *CPV =
2424 ARMConstantPoolConstant::Create(GV,
2425 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2426 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2427 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2428 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2430 MachinePointerInfo::getConstantPool(),
2431 false, false, false, 0);
2432 SDValue Chain = Result.getValue(1);
2433 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2434 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2436 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2437 MachinePointerInfo::getGOT(),
2438 false, false, false, 0);
2442 // If we have T2 ops, we can materialize the address directly via movt/movw
2443 // pair. This is always cheaper.
2444 if (Subtarget->useMovt()) {
2446 // FIXME: Once remat is capable of dealing with instructions with register
2447 // operands, expand this into two nodes.
2448 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2449 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2451 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2452 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2453 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2454 MachinePointerInfo::getConstantPool(),
2455 false, false, false, 0);
2459 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2460 SelectionDAG &DAG) const {
2461 EVT PtrVT = getPointerTy();
2463 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2464 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2466 if (Subtarget->useMovt())
2469 // FIXME: Once remat is capable of dealing with instructions with register
2470 // operands, expand this into multiple nodes
2472 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2474 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2475 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2477 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2478 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2479 MachinePointerInfo::getGOT(), false, false, false, 0);
2483 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2484 SelectionDAG &DAG) const {
2485 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2486 assert(Subtarget->useMovt() && "Windows on ARM expects to use movw/movt");
2488 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2489 EVT PtrVT = getPointerTy();
2494 // FIXME: Once remat is capable of dealing with instructions with register
2495 // operands, expand this into two nodes.
2496 return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2497 DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2500 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2501 SelectionDAG &DAG) const {
2502 assert(Subtarget->isTargetELF() &&
2503 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2504 MachineFunction &MF = DAG.getMachineFunction();
2505 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2506 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2507 EVT PtrVT = getPointerTy();
2509 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2510 ARMConstantPoolValue *CPV =
2511 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2512 ARMPCLabelIndex, PCAdj);
2513 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2514 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2515 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2516 MachinePointerInfo::getConstantPool(),
2517 false, false, false, 0);
2518 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2519 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2523 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2525 SDValue Val = DAG.getConstant(0, MVT::i32);
2526 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2527 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2528 Op.getOperand(1), Val);
2532 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2534 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2535 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2539 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2540 const ARMSubtarget *Subtarget) const {
2541 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2544 default: return SDValue(); // Don't custom lower most intrinsics.
2545 case Intrinsic::arm_thread_pointer: {
2546 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2547 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2549 case Intrinsic::eh_sjlj_lsda: {
2550 MachineFunction &MF = DAG.getMachineFunction();
2551 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2552 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2553 EVT PtrVT = getPointerTy();
2554 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2556 unsigned PCAdj = (RelocM != Reloc::PIC_)
2557 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2558 ARMConstantPoolValue *CPV =
2559 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2560 ARMCP::CPLSDA, PCAdj);
2561 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2562 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2564 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2565 MachinePointerInfo::getConstantPool(),
2566 false, false, false, 0);
2568 if (RelocM == Reloc::PIC_) {
2569 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2570 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2574 case Intrinsic::arm_neon_vmulls:
2575 case Intrinsic::arm_neon_vmullu: {
2576 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2577 ? ARMISD::VMULLs : ARMISD::VMULLu;
2578 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2579 Op.getOperand(1), Op.getOperand(2));
2584 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2585 const ARMSubtarget *Subtarget) {
2586 // FIXME: handle "fence singlethread" more efficiently.
2588 if (!Subtarget->hasDataBarrier()) {
2589 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2590 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2592 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2593 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2594 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2595 DAG.getConstant(0, MVT::i32));
2598 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2599 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2600 unsigned Domain = ARM_MB::ISH;
2601 if (Subtarget->isMClass()) {
2602 // Only a full system barrier exists in the M-class architectures.
2603 Domain = ARM_MB::SY;
2604 } else if (Subtarget->isSwift() && Ord == Release) {
2605 // Swift happens to implement ISHST barriers in a way that's compatible with
2606 // Release semantics but weaker than ISH so we'd be fools not to use
2607 // it. Beware: other processors probably don't!
2608 Domain = ARM_MB::ISHST;
2611 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2612 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2613 DAG.getConstant(Domain, MVT::i32));
2616 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2617 const ARMSubtarget *Subtarget) {
2618 // ARM pre v5TE and Thumb1 does not have preload instructions.
2619 if (!(Subtarget->isThumb2() ||
2620 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2621 // Just preserve the chain.
2622 return Op.getOperand(0);
2625 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2627 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2628 // ARMv7 with MP extension has PLDW.
2629 return Op.getOperand(0);
2631 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2632 if (Subtarget->isThumb()) {
2634 isRead = ~isRead & 1;
2635 isData = ~isData & 1;
2638 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2639 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2640 DAG.getConstant(isData, MVT::i32));
2643 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2644 MachineFunction &MF = DAG.getMachineFunction();
2645 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2647 // vastart just stores the address of the VarArgsFrameIndex slot into the
2648 // memory location argument.
2650 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2651 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2652 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2653 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2654 MachinePointerInfo(SV), false, false, 0);
2658 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2659 SDValue &Root, SelectionDAG &DAG,
2661 MachineFunction &MF = DAG.getMachineFunction();
2662 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2664 const TargetRegisterClass *RC;
2665 if (AFI->isThumb1OnlyFunction())
2666 RC = &ARM::tGPRRegClass;
2668 RC = &ARM::GPRRegClass;
2670 // Transform the arguments stored in physical registers into virtual ones.
2671 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2672 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2675 if (NextVA.isMemLoc()) {
2676 MachineFrameInfo *MFI = MF.getFrameInfo();
2677 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2679 // Create load node to retrieve arguments from the stack.
2680 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2681 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2682 MachinePointerInfo::getFixedStack(FI),
2683 false, false, false, 0);
2685 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2686 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2688 if (!Subtarget->isLittle())
2689 std::swap (ArgValue, ArgValue2);
2690 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2694 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2695 unsigned InRegsParamRecordIdx,
2697 unsigned &ArgRegsSize,
2698 unsigned &ArgRegsSaveSize)
2701 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2702 unsigned RBegin, REnd;
2703 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2704 NumGPRs = REnd - RBegin;
2706 unsigned int firstUnalloced;
2707 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2708 sizeof(GPRArgRegs) /
2709 sizeof(GPRArgRegs[0]));
2710 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2713 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2714 ArgRegsSize = NumGPRs * 4;
2716 // If parameter is split between stack and GPRs...
2717 if (NumGPRs && Align > 4 &&
2718 (ArgRegsSize < ArgSize ||
2719 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2720 // Add padding for part of param recovered from GPRs. For example,
2721 // if Align == 8, its last byte must be at address K*8 - 1.
2722 // We need to do it, since remained (stack) part of parameter has
2723 // stack alignment, and we need to "attach" "GPRs head" without gaps
2726 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2727 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2729 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2731 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2732 ArgRegsSaveSize = ArgRegsSize + Padding;
2734 // We don't need to extend regs save size for byval parameters if they
2735 // are passed via GPRs only.
2736 ArgRegsSaveSize = ArgRegsSize;
2739 // The remaining GPRs hold either the beginning of variable-argument
2740 // data, or the beginning of an aggregate passed by value (usually
2741 // byval). Either way, we allocate stack slots adjacent to the data
2742 // provided by our caller, and store the unallocated registers there.
2743 // If this is a variadic function, the va_list pointer will begin with
2744 // these values; otherwise, this reassembles a (byval) structure that
2745 // was split between registers and memory.
2746 // Return: The frame index registers were stored into.
2748 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2749 SDLoc dl, SDValue &Chain,
2750 const Value *OrigArg,
2751 unsigned InRegsParamRecordIdx,
2752 unsigned OffsetFromOrigArg,
2756 unsigned ByValStoreOffset,
2757 unsigned TotalArgRegsSaveSize) const {
2759 // Currently, two use-cases possible:
2760 // Case #1. Non-var-args function, and we meet first byval parameter.
2761 // Setup first unallocated register as first byval register;
2762 // eat all remained registers
2763 // (these two actions are performed by HandleByVal method).
2764 // Then, here, we initialize stack frame with
2765 // "store-reg" instructions.
2766 // Case #2. Var-args function, that doesn't contain byval parameters.
2767 // The same: eat all remained unallocated registers,
2768 // initialize stack frame.
2770 MachineFunction &MF = DAG.getMachineFunction();
2771 MachineFrameInfo *MFI = MF.getFrameInfo();
2772 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2773 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2774 unsigned RBegin, REnd;
2775 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2776 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2777 firstRegToSaveIndex = RBegin - ARM::R0;
2778 lastRegToSaveIndex = REnd - ARM::R0;
2780 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2781 (GPRArgRegs, array_lengthof(GPRArgRegs));
2782 lastRegToSaveIndex = 4;
2785 unsigned ArgRegsSize, ArgRegsSaveSize;
2786 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2787 ArgRegsSize, ArgRegsSaveSize);
2789 // Store any by-val regs to their spots on the stack so that they may be
2790 // loaded by deferencing the result of formal parameter pointer or va_next.
2791 // Note: once stack area for byval/varargs registers
2792 // was initialized, it can't be initialized again.
2793 if (ArgRegsSaveSize) {
2794 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2797 assert(AFI->getStoredByValParamsPadding() == 0 &&
2798 "The only parameter may be padded.");
2799 AFI->setStoredByValParamsPadding(Padding);
2802 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2805 (int64_t)TotalArgRegsSaveSize,
2807 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2809 MFI->CreateFixedObject(Padding,
2810 ArgOffset + ByValStoreOffset -
2811 (int64_t)ArgRegsSaveSize,
2815 SmallVector<SDValue, 4> MemOps;
2816 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2817 ++firstRegToSaveIndex, ++i) {
2818 const TargetRegisterClass *RC;
2819 if (AFI->isThumb1OnlyFunction())
2820 RC = &ARM::tGPRRegClass;
2822 RC = &ARM::GPRRegClass;
2824 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2825 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2827 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2828 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2830 MemOps.push_back(Store);
2831 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2832 DAG.getConstant(4, getPointerTy()));
2835 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2837 if (!MemOps.empty())
2838 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2842 // We cannot allocate a zero-byte object for the first variadic argument,
2843 // so just make up a size.
2846 // This will point to the next argument passed via stack.
2847 return MFI->CreateFixedObject(
2848 ArgSize, ArgOffset, !ForceMutable);
2852 // Setup stack frame, the va_list pointer will start from.
2854 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2855 SDLoc dl, SDValue &Chain,
2857 unsigned TotalArgRegsSaveSize,
2858 bool ForceMutable) const {
2859 MachineFunction &MF = DAG.getMachineFunction();
2860 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2862 // Try to store any remaining integer argument regs
2863 // to their spots on the stack so that they may be loaded by deferencing
2864 // the result of va_next.
2865 // If there is no regs to be stored, just point address after last
2866 // argument passed via stack.
2868 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2869 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2870 0, TotalArgRegsSaveSize);
2872 AFI->setVarArgsFrameIndex(FrameIndex);
2876 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2877 CallingConv::ID CallConv, bool isVarArg,
2878 const SmallVectorImpl<ISD::InputArg>
2880 SDLoc dl, SelectionDAG &DAG,
2881 SmallVectorImpl<SDValue> &InVals)
2883 MachineFunction &MF = DAG.getMachineFunction();
2884 MachineFrameInfo *MFI = MF.getFrameInfo();
2886 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2888 // Assign locations to all of the incoming arguments.
2889 SmallVector<CCValAssign, 16> ArgLocs;
2890 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2891 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2892 CCInfo.AnalyzeFormalArguments(Ins,
2893 CCAssignFnForNode(CallConv, /* Return*/ false,
2896 SmallVector<SDValue, 16> ArgValues;
2897 int lastInsIndex = -1;
2899 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2900 unsigned CurArgIdx = 0;
2902 // Initially ArgRegsSaveSize is zero.
2903 // Then we increase this value each time we meet byval parameter.
2904 // We also increase this value in case of varargs function.
2905 AFI->setArgRegsSaveSize(0);
2907 unsigned ByValStoreOffset = 0;
2908 unsigned TotalArgRegsSaveSize = 0;
2909 unsigned ArgRegsSaveSizeMaxAlign = 4;
2911 // Calculate the amount of stack space that we need to allocate to store
2912 // byval and variadic arguments that are passed in registers.
2913 // We need to know this before we allocate the first byval or variadic
2914 // argument, as they will be allocated a stack slot below the CFA (Canonical
2915 // Frame Address, the stack pointer at entry to the function).
2916 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2917 CCValAssign &VA = ArgLocs[i];
2918 if (VA.isMemLoc()) {
2919 int index = VA.getValNo();
2920 if (index != lastInsIndex) {
2921 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2922 if (Flags.isByVal()) {
2923 unsigned ExtraArgRegsSize;
2924 unsigned ExtraArgRegsSaveSize;
2925 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2926 Flags.getByValSize(),
2927 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2929 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2930 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2931 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2932 CCInfo.nextInRegsParam();
2934 lastInsIndex = index;
2938 CCInfo.rewindByValRegsInfo();
2941 unsigned ExtraArgRegsSize;
2942 unsigned ExtraArgRegsSaveSize;
2943 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2944 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2945 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2947 // If the arg regs save area contains N-byte aligned values, the
2948 // bottom of it must be at least N-byte aligned.
2949 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2950 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2952 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2953 CCValAssign &VA = ArgLocs[i];
2954 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2955 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2956 // Arguments stored in registers.
2957 if (VA.isRegLoc()) {
2958 EVT RegVT = VA.getLocVT();
2960 if (VA.needsCustom()) {
2961 // f64 and vector types are split up into multiple registers or
2962 // combinations of registers and stack slots.
2963 if (VA.getLocVT() == MVT::v2f64) {
2964 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2966 VA = ArgLocs[++i]; // skip ahead to next loc
2968 if (VA.isMemLoc()) {
2969 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2970 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2971 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2972 MachinePointerInfo::getFixedStack(FI),
2973 false, false, false, 0);
2975 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2978 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2979 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2980 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2981 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2982 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2984 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2987 const TargetRegisterClass *RC;
2989 if (RegVT == MVT::f32)
2990 RC = &ARM::SPRRegClass;
2991 else if (RegVT == MVT::f64)
2992 RC = &ARM::DPRRegClass;
2993 else if (RegVT == MVT::v2f64)
2994 RC = &ARM::QPRRegClass;
2995 else if (RegVT == MVT::i32)
2996 RC = AFI->isThumb1OnlyFunction() ?
2997 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2998 (const TargetRegisterClass*)&ARM::GPRRegClass;
3000 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3002 // Transform the arguments in physical registers into virtual ones.
3003 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3004 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3007 // If this is an 8 or 16-bit value, it is really passed promoted
3008 // to 32 bits. Insert an assert[sz]ext to capture this, then
3009 // truncate to the right size.
3010 switch (VA.getLocInfo()) {
3011 default: llvm_unreachable("Unknown loc info!");
3012 case CCValAssign::Full: break;
3013 case CCValAssign::BCvt:
3014 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3016 case CCValAssign::SExt:
3017 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3018 DAG.getValueType(VA.getValVT()));
3019 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3021 case CCValAssign::ZExt:
3022 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3023 DAG.getValueType(VA.getValVT()));
3024 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3028 InVals.push_back(ArgValue);
3030 } else { // VA.isRegLoc()
3033 assert(VA.isMemLoc());
3034 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3036 int index = ArgLocs[i].getValNo();
3038 // Some Ins[] entries become multiple ArgLoc[] entries.
3039 // Process them only once.
3040 if (index != lastInsIndex)
3042 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3043 // FIXME: For now, all byval parameter objects are marked mutable.
3044 // This can be changed with more analysis.
3045 // In case of tail call optimization mark all arguments mutable.
3046 // Since they could be overwritten by lowering of arguments in case of
3048 if (Flags.isByVal()) {
3049 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3051 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3052 int FrameIndex = StoreByValRegs(
3053 CCInfo, DAG, dl, Chain, CurOrigArg,
3055 Ins[VA.getValNo()].PartOffset,
3056 VA.getLocMemOffset(),
3057 Flags.getByValSize(),
3058 true /*force mutable frames*/,
3060 TotalArgRegsSaveSize);
3061 ByValStoreOffset += Flags.getByValSize();
3062 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3063 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3064 CCInfo.nextInRegsParam();
3066 unsigned FIOffset = VA.getLocMemOffset();
3067 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3070 // Create load nodes to retrieve arguments from the stack.
3071 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3072 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3073 MachinePointerInfo::getFixedStack(FI),
3074 false, false, false, 0));
3076 lastInsIndex = index;
3083 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3084 CCInfo.getNextStackOffset(),
3085 TotalArgRegsSaveSize);
3087 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3092 /// isFloatingPointZero - Return true if this is +0.0.
3093 static bool isFloatingPointZero(SDValue Op) {
3094 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3095 return CFP->getValueAPF().isPosZero();
3096 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3097 // Maybe this has already been legalized into the constant pool?
3098 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3099 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3100 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3101 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3102 return CFP->getValueAPF().isPosZero();
3108 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3109 /// the given operands.
3111 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3112 SDValue &ARMcc, SelectionDAG &DAG,
3114 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3115 unsigned C = RHSC->getZExtValue();
3116 if (!isLegalICmpImmediate(C)) {
3117 // Constant does not fit, try adjusting it by one?
3122 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3123 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3124 RHS = DAG.getConstant(C-1, MVT::i32);
3129 if (C != 0 && isLegalICmpImmediate(C-1)) {
3130 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3131 RHS = DAG.getConstant(C-1, MVT::i32);
3136 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3137 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3138 RHS = DAG.getConstant(C+1, MVT::i32);
3143 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3144 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3145 RHS = DAG.getConstant(C+1, MVT::i32);
3152 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3153 ARMISD::NodeType CompareType;
3156 CompareType = ARMISD::CMP;
3161 CompareType = ARMISD::CMPZ;
3164 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3165 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3168 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3170 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3173 if (!isFloatingPointZero(RHS))
3174 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3176 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3177 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3180 /// duplicateCmp - Glue values can have only one use, so this function
3181 /// duplicates a comparison node.
3183 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3184 unsigned Opc = Cmp.getOpcode();
3186 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3187 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3189 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3190 Cmp = Cmp.getOperand(0);
3191 Opc = Cmp.getOpcode();
3192 if (Opc == ARMISD::CMPFP)
3193 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3195 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3196 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3198 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3201 std::pair<SDValue, SDValue>
3202 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3203 SDValue &ARMcc) const {
3204 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3206 SDValue Value, OverflowCmp;
3207 SDValue LHS = Op.getOperand(0);
3208 SDValue RHS = Op.getOperand(1);
3211 // FIXME: We are currently always generating CMPs because we don't support
3212 // generating CMN through the backend. This is not as good as the natural
3213 // CMP case because it causes a register dependency and cannot be folded
3216 switch (Op.getOpcode()) {
3218 llvm_unreachable("Unknown overflow instruction!");
3220 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3221 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3222 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3225 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3226 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3227 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3230 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3231 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3232 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3235 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3236 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3237 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3241 return std::make_pair(Value, OverflowCmp);
3246 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3247 // Let legalize expand this if it isn't a legal type yet.
3248 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3251 SDValue Value, OverflowCmp;
3253 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3254 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3255 // We use 0 and 1 as false and true values.
3256 SDValue TVal = DAG.getConstant(1, MVT::i32);
3257 SDValue FVal = DAG.getConstant(0, MVT::i32);
3258 EVT VT = Op.getValueType();
3260 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3261 ARMcc, CCR, OverflowCmp);
3263 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3264 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3268 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3269 SDValue Cond = Op.getOperand(0);
3270 SDValue SelectTrue = Op.getOperand(1);
3271 SDValue SelectFalse = Op.getOperand(2);
3273 unsigned Opc = Cond.getOpcode();
3275 if (Cond.getResNo() == 1 &&
3276 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3277 Opc == ISD::USUBO)) {
3278 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3281 SDValue Value, OverflowCmp;
3283 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3284 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3285 EVT VT = Op.getValueType();
3287 return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3288 ARMcc, CCR, OverflowCmp);
3294 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3295 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3297 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3298 const ConstantSDNode *CMOVTrue =
3299 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3300 const ConstantSDNode *CMOVFalse =
3301 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3303 if (CMOVTrue && CMOVFalse) {
3304 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3305 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3309 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3311 False = SelectFalse;
3312 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3317 if (True.getNode() && False.getNode()) {
3318 EVT VT = Op.getValueType();
3319 SDValue ARMcc = Cond.getOperand(2);
3320 SDValue CCR = Cond.getOperand(3);
3321 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3322 assert(True.getValueType() == VT);
3323 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3328 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3329 // undefined bits before doing a full-word comparison with zero.
3330 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3331 DAG.getConstant(1, Cond.getValueType()));
3333 return DAG.getSelectCC(dl, Cond,
3334 DAG.getConstant(0, Cond.getValueType()),
3335 SelectTrue, SelectFalse, ISD::SETNE);
3338 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3339 if (CC == ISD::SETNE)
3341 return ISD::getSetCCInverse(CC, true);
3344 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3345 bool &swpCmpOps, bool &swpVselOps) {
3346 // Start by selecting the GE condition code for opcodes that return true for
3348 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3350 CondCode = ARMCC::GE;
3352 // and GT for opcodes that return false for 'equality'.
3353 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3355 CondCode = ARMCC::GT;
3357 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3358 // to swap the compare operands.
3359 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3363 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3364 // If we have an unordered opcode, we need to swap the operands to the VSEL
3365 // instruction (effectively negating the condition).
3367 // This also has the effect of swapping which one of 'less' or 'greater'
3368 // returns true, so we also swap the compare operands. It also switches
3369 // whether we return true for 'equality', so we compensate by picking the
3370 // opposite condition code to our original choice.
3371 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3372 CC == ISD::SETUGT) {
3373 swpCmpOps = !swpCmpOps;
3374 swpVselOps = !swpVselOps;
3375 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3378 // 'ordered' is 'anything but unordered', so use the VS condition code and
3379 // swap the VSEL operands.
3380 if (CC == ISD::SETO) {
3381 CondCode = ARMCC::VS;
3385 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3386 // code and swap the VSEL operands.
3387 if (CC == ISD::SETUNE) {
3388 CondCode = ARMCC::EQ;
3393 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3394 EVT VT = Op.getValueType();
3395 SDValue LHS = Op.getOperand(0);
3396 SDValue RHS = Op.getOperand(1);
3397 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3398 SDValue TrueVal = Op.getOperand(2);
3399 SDValue FalseVal = Op.getOperand(3);
3402 if (LHS.getValueType() == MVT::i32) {
3403 // Try to generate VSEL on ARMv8.
3404 // The VSEL instruction can't use all the usual ARM condition
3405 // codes: it only has two bits to select the condition code, so it's
3406 // constrained to use only GE, GT, VS and EQ.
3408 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3409 // swap the operands of the previous compare instruction (effectively
3410 // inverting the compare condition, swapping 'less' and 'greater') and
3411 // sometimes need to swap the operands to the VSEL (which inverts the
3412 // condition in the sense of firing whenever the previous condition didn't)
3413 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3414 TrueVal.getValueType() == MVT::f64)) {
3415 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3416 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3417 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3418 CC = getInverseCCForVSEL(CC);
3419 std::swap(TrueVal, FalseVal);
3424 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3425 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3426 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3430 ARMCC::CondCodes CondCode, CondCode2;
3431 FPCCToARMCC(CC, CondCode, CondCode2);
3433 // Try to generate VSEL on ARMv8.
3434 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3435 TrueVal.getValueType() == MVT::f64)) {
3436 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3437 // same operands, as follows:
3438 // c = fcmp [ogt, olt, ugt, ult] a, b
3440 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3441 // handled differently than the original code sequence.
3442 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3444 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3445 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3446 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3447 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3450 bool swpCmpOps = false;
3451 bool swpVselOps = false;
3452 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3454 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3455 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3457 std::swap(LHS, RHS);
3459 std::swap(TrueVal, FalseVal);
3463 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3464 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3465 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3466 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3468 if (CondCode2 != ARMCC::AL) {
3469 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3470 // FIXME: Needs another CMP because flag can have but one use.
3471 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3472 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3473 Result, TrueVal, ARMcc2, CCR, Cmp2);
3478 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3479 /// to morph to an integer compare sequence.
3480 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3481 const ARMSubtarget *Subtarget) {
3482 SDNode *N = Op.getNode();
3483 if (!N->hasOneUse())
3484 // Otherwise it requires moving the value from fp to integer registers.
3486 if (!N->getNumValues())
3488 EVT VT = Op.getValueType();
3489 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3490 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3491 // vmrs are very slow, e.g. cortex-a8.
3494 if (isFloatingPointZero(Op)) {
3498 return ISD::isNormalLoad(N);
3501 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3502 if (isFloatingPointZero(Op))
3503 return DAG.getConstant(0, MVT::i32);
3505 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3506 return DAG.getLoad(MVT::i32, SDLoc(Op),
3507 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3508 Ld->isVolatile(), Ld->isNonTemporal(),
3509 Ld->isInvariant(), Ld->getAlignment());
3511 llvm_unreachable("Unknown VFP cmp argument!");
3514 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3515 SDValue &RetVal1, SDValue &RetVal2) {
3516 if (isFloatingPointZero(Op)) {
3517 RetVal1 = DAG.getConstant(0, MVT::i32);
3518 RetVal2 = DAG.getConstant(0, MVT::i32);
3522 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3523 SDValue Ptr = Ld->getBasePtr();
3524 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3525 Ld->getChain(), Ptr,
3526 Ld->getPointerInfo(),
3527 Ld->isVolatile(), Ld->isNonTemporal(),
3528 Ld->isInvariant(), Ld->getAlignment());
3530 EVT PtrType = Ptr.getValueType();
3531 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3532 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3533 PtrType, Ptr, DAG.getConstant(4, PtrType));
3534 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3535 Ld->getChain(), NewPtr,
3536 Ld->getPointerInfo().getWithOffset(4),
3537 Ld->isVolatile(), Ld->isNonTemporal(),
3538 Ld->isInvariant(), NewAlign);
3542 llvm_unreachable("Unknown VFP cmp argument!");
3545 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3546 /// f32 and even f64 comparisons to integer ones.
3548 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3549 SDValue Chain = Op.getOperand(0);
3550 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3551 SDValue LHS = Op.getOperand(2);
3552 SDValue RHS = Op.getOperand(3);
3553 SDValue Dest = Op.getOperand(4);
3556 bool LHSSeenZero = false;
3557 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3558 bool RHSSeenZero = false;
3559 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3560 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3561 // If unsafe fp math optimization is enabled and there are no other uses of
3562 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3563 // to an integer comparison.
3564 if (CC == ISD::SETOEQ)
3566 else if (CC == ISD::SETUNE)
3569 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3571 if (LHS.getValueType() == MVT::f32) {
3572 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3573 bitcastf32Toi32(LHS, DAG), Mask);
3574 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3575 bitcastf32Toi32(RHS, DAG), Mask);
3576 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3577 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3578 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3579 Chain, Dest, ARMcc, CCR, Cmp);
3584 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3585 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3586 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3587 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3588 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3589 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3590 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3591 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3592 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3598 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3599 SDValue Chain = Op.getOperand(0);
3600 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3601 SDValue LHS = Op.getOperand(2);
3602 SDValue RHS = Op.getOperand(3);
3603 SDValue Dest = Op.getOperand(4);
3606 if (LHS.getValueType() == MVT::i32) {
3608 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3609 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3610 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3611 Chain, Dest, ARMcc, CCR, Cmp);
3614 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3616 if (getTargetMachine().Options.UnsafeFPMath &&
3617 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3618 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3619 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3620 if (Result.getNode())
3624 ARMCC::CondCodes CondCode, CondCode2;
3625 FPCCToARMCC(CC, CondCode, CondCode2);
3627 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3628 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3629 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3630 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3631 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3632 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3633 if (CondCode2 != ARMCC::AL) {
3634 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3635 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3636 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3641 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3642 SDValue Chain = Op.getOperand(0);
3643 SDValue Table = Op.getOperand(1);
3644 SDValue Index = Op.getOperand(2);
3647 EVT PTy = getPointerTy();
3648 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3649 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3650 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3651 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3652 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3653 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3654 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3655 if (Subtarget->isThumb2()) {
3656 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3657 // which does another jump to the destination. This also makes it easier
3658 // to translate it to TBB / TBH later.
3659 // FIXME: This might not work if the function is extremely large.
3660 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3661 Addr, Op.getOperand(2), JTI, UId);
3663 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3664 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3665 MachinePointerInfo::getJumpTable(),
3666 false, false, false, 0);
3667 Chain = Addr.getValue(1);
3668 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3669 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3671 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3672 MachinePointerInfo::getJumpTable(),
3673 false, false, false, 0);
3674 Chain = Addr.getValue(1);
3675 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3679 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3680 EVT VT = Op.getValueType();
3683 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3684 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3686 return DAG.UnrollVectorOp(Op.getNode());
3689 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3690 "Invalid type for custom lowering!");
3691 if (VT != MVT::v4i16)
3692 return DAG.UnrollVectorOp(Op.getNode());
3694 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3695 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3698 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3699 EVT VT = Op.getValueType();
3701 return LowerVectorFP_TO_INT(Op, DAG);
3706 switch (Op.getOpcode()) {
3707 default: llvm_unreachable("Invalid opcode!");
3708 case ISD::FP_TO_SINT:
3709 Opc = ARMISD::FTOSI;
3711 case ISD::FP_TO_UINT:
3712 Opc = ARMISD::FTOUI;
3715 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3716 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3719 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3720 EVT VT = Op.getValueType();
3723 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3724 if (VT.getVectorElementType() == MVT::f32)
3726 return DAG.UnrollVectorOp(Op.getNode());
3729 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3730 "Invalid type for custom lowering!");
3731 if (VT != MVT::v4f32)
3732 return DAG.UnrollVectorOp(Op.getNode());
3736 switch (Op.getOpcode()) {
3737 default: llvm_unreachable("Invalid opcode!");
3738 case ISD::SINT_TO_FP:
3739 CastOpc = ISD::SIGN_EXTEND;
3740 Opc = ISD::SINT_TO_FP;
3742 case ISD::UINT_TO_FP:
3743 CastOpc = ISD::ZERO_EXTEND;
3744 Opc = ISD::UINT_TO_FP;
3748 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3749 return DAG.getNode(Opc, dl, VT, Op);
3752 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3753 EVT VT = Op.getValueType();
3755 return LowerVectorINT_TO_FP(Op, DAG);
3760 switch (Op.getOpcode()) {
3761 default: llvm_unreachable("Invalid opcode!");
3762 case ISD::SINT_TO_FP:
3763 Opc = ARMISD::SITOF;
3765 case ISD::UINT_TO_FP:
3766 Opc = ARMISD::UITOF;
3770 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3771 return DAG.getNode(Opc, dl, VT, Op);
3774 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3775 // Implement fcopysign with a fabs and a conditional fneg.
3776 SDValue Tmp0 = Op.getOperand(0);
3777 SDValue Tmp1 = Op.getOperand(1);
3779 EVT VT = Op.getValueType();
3780 EVT SrcVT = Tmp1.getValueType();
3781 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3782 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3783 bool UseNEON = !InGPR && Subtarget->hasNEON();
3786 // Use VBSL to copy the sign bit.
3787 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3788 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3789 DAG.getTargetConstant(EncodedVal, MVT::i32));
3790 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3792 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3793 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3794 DAG.getConstant(32, MVT::i32));
3795 else /*if (VT == MVT::f32)*/
3796 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3797 if (SrcVT == MVT::f32) {
3798 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3800 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3801 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3802 DAG.getConstant(32, MVT::i32));
3803 } else if (VT == MVT::f32)
3804 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3805 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3806 DAG.getConstant(32, MVT::i32));
3807 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3808 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3810 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3812 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3813 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3814 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3816 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3817 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3818 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3819 if (VT == MVT::f32) {
3820 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3821 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3822 DAG.getConstant(0, MVT::i32));
3824 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3830 // Bitcast operand 1 to i32.
3831 if (SrcVT == MVT::f64)
3832 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3834 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3836 // Or in the signbit with integer operations.
3837 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3838 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3839 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3840 if (VT == MVT::f32) {
3841 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3842 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3843 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3844 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3847 // f64: Or the high part with signbit and then combine two parts.
3848 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3850 SDValue Lo = Tmp0.getValue(0);
3851 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3852 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3853 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3856 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3857 MachineFunction &MF = DAG.getMachineFunction();
3858 MachineFrameInfo *MFI = MF.getFrameInfo();
3859 MFI->setReturnAddressIsTaken(true);
3861 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3864 EVT VT = Op.getValueType();
3866 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3868 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3869 SDValue Offset = DAG.getConstant(4, MVT::i32);
3870 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3871 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3872 MachinePointerInfo(), false, false, false, 0);
3875 // Return LR, which contains the return address. Mark it an implicit live-in.
3876 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3877 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3880 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3881 const ARMBaseRegisterInfo &ARI =
3882 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3883 MachineFunction &MF = DAG.getMachineFunction();
3884 MachineFrameInfo *MFI = MF.getFrameInfo();
3885 MFI->setFrameAddressIsTaken(true);
3887 EVT VT = Op.getValueType();
3888 SDLoc dl(Op); // FIXME probably not meaningful
3889 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3890 unsigned FrameReg = ARI.getFrameRegister(MF);
3891 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3893 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3894 MachinePointerInfo(),
3895 false, false, false, 0);
3899 // FIXME? Maybe this could be a TableGen attribute on some registers and
3900 // this table could be generated automatically from RegInfo.
3901 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3903 unsigned Reg = StringSwitch<unsigned>(RegName)
3904 .Case("sp", ARM::SP)
3908 report_fatal_error("Invalid register name global variable");
3911 /// ExpandBITCAST - If the target supports VFP, this function is called to
3912 /// expand a bit convert where either the source or destination type is i64 to
3913 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3914 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3915 /// vectors), since the legalizer won't know what to do with that.
3916 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3917 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3919 SDValue Op = N->getOperand(0);
3921 // This function is only supposed to be called for i64 types, either as the
3922 // source or destination of the bit convert.
3923 EVT SrcVT = Op.getValueType();
3924 EVT DstVT = N->getValueType(0);
3925 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3926 "ExpandBITCAST called for non-i64 type");
3928 // Turn i64->f64 into VMOVDRR.
3929 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3930 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3931 DAG.getConstant(0, MVT::i32));
3932 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3933 DAG.getConstant(1, MVT::i32));
3934 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3935 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3938 // Turn f64->i64 into VMOVRRD.
3939 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3941 if (TLI.isBigEndian() && SrcVT.isVector() &&
3942 SrcVT.getVectorNumElements() > 1)
3943 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3944 DAG.getVTList(MVT::i32, MVT::i32),
3945 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3947 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3948 DAG.getVTList(MVT::i32, MVT::i32), Op);
3949 // Merge the pieces into a single i64 value.
3950 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3956 /// getZeroVector - Returns a vector of specified type with all zero elements.
3957 /// Zero vectors are used to represent vector negation and in those cases
3958 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3959 /// not support i64 elements, so sometimes the zero vectors will need to be
3960 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3962 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3963 assert(VT.isVector() && "Expected a vector type");
3964 // The canonical modified immediate encoding of a zero vector is....0!
3965 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3966 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3967 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3968 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3971 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3972 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3973 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3974 SelectionDAG &DAG) const {
3975 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3976 EVT VT = Op.getValueType();
3977 unsigned VTBits = VT.getSizeInBits();
3979 SDValue ShOpLo = Op.getOperand(0);
3980 SDValue ShOpHi = Op.getOperand(1);
3981 SDValue ShAmt = Op.getOperand(2);
3983 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3985 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3987 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3988 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3989 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3990 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3991 DAG.getConstant(VTBits, MVT::i32));
3992 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3993 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3994 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3996 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3997 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3999 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4000 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4003 SDValue Ops[2] = { Lo, Hi };
4004 return DAG.getMergeValues(Ops, dl);
4007 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4008 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4009 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4010 SelectionDAG &DAG) const {
4011 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4012 EVT VT = Op.getValueType();
4013 unsigned VTBits = VT.getSizeInBits();
4015 SDValue ShOpLo = Op.getOperand(0);
4016 SDValue ShOpHi = Op.getOperand(1);
4017 SDValue ShAmt = Op.getOperand(2);
4020 assert(Op.getOpcode() == ISD::SHL_PARTS);
4021 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4022 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4023 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4024 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4025 DAG.getConstant(VTBits, MVT::i32));
4026 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4027 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4029 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4030 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4031 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4033 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4034 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4037 SDValue Ops[2] = { Lo, Hi };
4038 return DAG.getMergeValues(Ops, dl);
4041 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4042 SelectionDAG &DAG) const {
4043 // The rounding mode is in bits 23:22 of the FPSCR.
4044 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4045 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4046 // so that the shift + and get folded into a bitfield extract.
4048 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4049 DAG.getConstant(Intrinsic::arm_get_fpscr,
4051 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4052 DAG.getConstant(1U << 22, MVT::i32));
4053 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4054 DAG.getConstant(22, MVT::i32));
4055 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4056 DAG.getConstant(3, MVT::i32));
4059 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4060 const ARMSubtarget *ST) {
4061 EVT VT = N->getValueType(0);
4064 if (!ST->hasV6T2Ops())
4067 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4068 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4071 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4072 /// for each 16-bit element from operand, repeated. The basic idea is to
4073 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4075 /// Trace for v4i16:
4076 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4077 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4078 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4079 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4080 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4081 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4082 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4083 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4084 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4085 EVT VT = N->getValueType(0);
4088 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4089 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4090 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4091 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4092 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4093 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4096 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4097 /// bit-count for each 16-bit element from the operand. We need slightly
4098 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4099 /// 64/128-bit registers.
4101 /// Trace for v4i16:
4102 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4103 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4104 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4105 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4106 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4107 EVT VT = N->getValueType(0);
4110 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4111 if (VT.is64BitVector()) {
4112 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4113 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4114 DAG.getIntPtrConstant(0));
4116 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4117 BitCounts, DAG.getIntPtrConstant(0));
4118 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4122 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4123 /// bit-count for each 32-bit element from the operand. The idea here is
4124 /// to split the vector into 16-bit elements, leverage the 16-bit count
4125 /// routine, and then combine the results.
4127 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4128 /// input = [v0 v1 ] (vi: 32-bit elements)
4129 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4130 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4131 /// vrev: N0 = [k1 k0 k3 k2 ]
4133 /// N1 =+[k1 k0 k3 k2 ]
4135 /// N2 =+[k1 k3 k0 k2 ]
4137 /// Extended =+[k1 k3 k0 k2 ]
4139 /// Extracted=+[k1 k3 ]
4141 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4142 EVT VT = N->getValueType(0);
4145 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4147 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4148 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4149 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4150 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4151 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4153 if (VT.is64BitVector()) {
4154 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4155 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4156 DAG.getIntPtrConstant(0));
4158 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4159 DAG.getIntPtrConstant(0));
4160 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4164 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4165 const ARMSubtarget *ST) {
4166 EVT VT = N->getValueType(0);
4168 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4169 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4170 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4171 "Unexpected type for custom ctpop lowering");
4173 if (VT.getVectorElementType() == MVT::i32)
4174 return lowerCTPOP32BitElements(N, DAG);
4176 return lowerCTPOP16BitElements(N, DAG);
4179 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4180 const ARMSubtarget *ST) {
4181 EVT VT = N->getValueType(0);
4187 // Lower vector shifts on NEON to use VSHL.
4188 assert(ST->hasNEON() && "unexpected vector shift");
4190 // Left shifts translate directly to the vshiftu intrinsic.
4191 if (N->getOpcode() == ISD::SHL)
4192 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4193 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4194 N->getOperand(0), N->getOperand(1));
4196 assert((N->getOpcode() == ISD::SRA ||
4197 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4199 // NEON uses the same intrinsics for both left and right shifts. For
4200 // right shifts, the shift amounts are negative, so negate the vector of
4202 EVT ShiftVT = N->getOperand(1).getValueType();
4203 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4204 getZeroVector(ShiftVT, DAG, dl),
4206 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4207 Intrinsic::arm_neon_vshifts :
4208 Intrinsic::arm_neon_vshiftu);
4209 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4210 DAG.getConstant(vshiftInt, MVT::i32),
4211 N->getOperand(0), NegatedCount);
4214 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4215 const ARMSubtarget *ST) {
4216 EVT VT = N->getValueType(0);
4219 // We can get here for a node like i32 = ISD::SHL i32, i64
4223 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4224 "Unknown shift to lower!");
4226 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4227 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4228 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4231 // If we are in thumb mode, we don't have RRX.
4232 if (ST->isThumb1Only()) return SDValue();
4234 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4235 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4236 DAG.getConstant(0, MVT::i32));
4237 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4238 DAG.getConstant(1, MVT::i32));
4240 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4241 // captures the result into a carry flag.
4242 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4243 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4245 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4246 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4248 // Merge the pieces into a single i64 value.
4249 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4252 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4253 SDValue TmpOp0, TmpOp1;
4254 bool Invert = false;
4258 SDValue Op0 = Op.getOperand(0);
4259 SDValue Op1 = Op.getOperand(1);
4260 SDValue CC = Op.getOperand(2);
4261 EVT VT = Op.getValueType();
4262 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4265 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4266 switch (SetCCOpcode) {
4267 default: llvm_unreachable("Illegal FP comparison");
4269 case ISD::SETNE: Invert = true; // Fallthrough
4271 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4273 case ISD::SETLT: Swap = true; // Fallthrough
4275 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4277 case ISD::SETLE: Swap = true; // Fallthrough
4279 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4280 case ISD::SETUGE: Swap = true; // Fallthrough
4281 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4282 case ISD::SETUGT: Swap = true; // Fallthrough
4283 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4284 case ISD::SETUEQ: Invert = true; // Fallthrough
4286 // Expand this to (OLT | OGT).
4290 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4291 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4293 case ISD::SETUO: Invert = true; // Fallthrough
4295 // Expand this to (OLT | OGE).
4299 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4300 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4304 // Integer comparisons.
4305 switch (SetCCOpcode) {
4306 default: llvm_unreachable("Illegal integer comparison");
4307 case ISD::SETNE: Invert = true;
4308 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4309 case ISD::SETLT: Swap = true;
4310 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4311 case ISD::SETLE: Swap = true;
4312 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4313 case ISD::SETULT: Swap = true;
4314 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4315 case ISD::SETULE: Swap = true;
4316 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4319 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4320 if (Opc == ARMISD::VCEQ) {
4323 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4325 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4328 // Ignore bitconvert.
4329 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4330 AndOp = AndOp.getOperand(0);
4332 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4334 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4335 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4342 std::swap(Op0, Op1);
4344 // If one of the operands is a constant vector zero, attempt to fold the
4345 // comparison to a specialized compare-against-zero form.
4347 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4349 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4350 if (Opc == ARMISD::VCGE)
4351 Opc = ARMISD::VCLEZ;
4352 else if (Opc == ARMISD::VCGT)
4353 Opc = ARMISD::VCLTZ;
4358 if (SingleOp.getNode()) {
4361 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4363 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4365 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4367 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4369 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4371 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4374 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4378 Result = DAG.getNOT(dl, Result, VT);
4383 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4384 /// valid vector constant for a NEON instruction with a "modified immediate"
4385 /// operand (e.g., VMOV). If so, return the encoded value.
4386 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4387 unsigned SplatBitSize, SelectionDAG &DAG,
4388 EVT &VT, bool is128Bits, NEONModImmType type) {
4389 unsigned OpCmode, Imm;
4391 // SplatBitSize is set to the smallest size that splats the vector, so a
4392 // zero vector will always have SplatBitSize == 8. However, NEON modified
4393 // immediate instructions others than VMOV do not support the 8-bit encoding
4394 // of a zero vector, and the default encoding of zero is supposed to be the
4399 switch (SplatBitSize) {
4401 if (type != VMOVModImm)
4403 // Any 1-byte value is OK. Op=0, Cmode=1110.
4404 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4407 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4411 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4412 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4413 if ((SplatBits & ~0xff) == 0) {
4414 // Value = 0x00nn: Op=x, Cmode=100x.
4419 if ((SplatBits & ~0xff00) == 0) {
4420 // Value = 0xnn00: Op=x, Cmode=101x.
4422 Imm = SplatBits >> 8;
4428 // NEON's 32-bit VMOV supports splat values where:
4429 // * only one byte is nonzero, or
4430 // * the least significant byte is 0xff and the second byte is nonzero, or
4431 // * the least significant 2 bytes are 0xff and the third is nonzero.
4432 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4433 if ((SplatBits & ~0xff) == 0) {
4434 // Value = 0x000000nn: Op=x, Cmode=000x.
4439 if ((SplatBits & ~0xff00) == 0) {
4440 // Value = 0x0000nn00: Op=x, Cmode=001x.
4442 Imm = SplatBits >> 8;
4445 if ((SplatBits & ~0xff0000) == 0) {
4446 // Value = 0x00nn0000: Op=x, Cmode=010x.
4448 Imm = SplatBits >> 16;
4451 if ((SplatBits & ~0xff000000) == 0) {
4452 // Value = 0xnn000000: Op=x, Cmode=011x.
4454 Imm = SplatBits >> 24;
4458 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4459 if (type == OtherModImm) return SDValue();
4461 if ((SplatBits & ~0xffff) == 0 &&
4462 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4463 // Value = 0x0000nnff: Op=x, Cmode=1100.
4465 Imm = SplatBits >> 8;
4469 if ((SplatBits & ~0xffffff) == 0 &&
4470 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4471 // Value = 0x00nnffff: Op=x, Cmode=1101.
4473 Imm = SplatBits >> 16;
4477 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4478 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4479 // VMOV.I32. A (very) minor optimization would be to replicate the value
4480 // and fall through here to test for a valid 64-bit splat. But, then the
4481 // caller would also need to check and handle the change in size.
4485 if (type != VMOVModImm)
4487 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4488 uint64_t BitMask = 0xff;
4490 unsigned ImmMask = 1;
4492 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4493 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4496 } else if ((SplatBits & BitMask) != 0) {
4502 // Op=1, Cmode=1110.
4504 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4509 llvm_unreachable("unexpected size for isNEONModifiedImm");
4512 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4513 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4516 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4517 const ARMSubtarget *ST) const {
4521 bool IsDouble = Op.getValueType() == MVT::f64;
4522 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4524 // Try splatting with a VMOV.f32...
4525 APFloat FPVal = CFP->getValueAPF();
4526 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4529 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4530 // We have code in place to select a valid ConstantFP already, no need to
4535 // It's a float and we are trying to use NEON operations where
4536 // possible. Lower it to a splat followed by an extract.
4538 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4539 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4541 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4542 DAG.getConstant(0, MVT::i32));
4545 // The rest of our options are NEON only, make sure that's allowed before
4547 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4551 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4553 // It wouldn't really be worth bothering for doubles except for one very
4554 // important value, which does happen to match: 0.0. So make sure we don't do
4556 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4559 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4560 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4562 if (NewVal != SDValue()) {
4564 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4567 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4569 // It's a float: cast and extract a vector element.
4570 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4572 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4573 DAG.getConstant(0, MVT::i32));
4576 // Finally, try a VMVN.i32
4577 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4579 if (NewVal != SDValue()) {
4581 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4584 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4586 // It's a float: cast and extract a vector element.
4587 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4589 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4590 DAG.getConstant(0, MVT::i32));
4596 // check if an VEXT instruction can handle the shuffle mask when the
4597 // vector sources of the shuffle are the same.
4598 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4599 unsigned NumElts = VT.getVectorNumElements();
4601 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4607 // If this is a VEXT shuffle, the immediate value is the index of the first
4608 // element. The other shuffle indices must be the successive elements after
4610 unsigned ExpectedElt = Imm;
4611 for (unsigned i = 1; i < NumElts; ++i) {
4612 // Increment the expected index. If it wraps around, just follow it
4613 // back to index zero and keep going.
4615 if (ExpectedElt == NumElts)
4618 if (M[i] < 0) continue; // ignore UNDEF indices
4619 if (ExpectedElt != static_cast<unsigned>(M[i]))
4627 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4628 bool &ReverseVEXT, unsigned &Imm) {
4629 unsigned NumElts = VT.getVectorNumElements();
4630 ReverseVEXT = false;
4632 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4638 // If this is a VEXT shuffle, the immediate value is the index of the first
4639 // element. The other shuffle indices must be the successive elements after
4641 unsigned ExpectedElt = Imm;
4642 for (unsigned i = 1; i < NumElts; ++i) {
4643 // Increment the expected index. If it wraps around, it may still be
4644 // a VEXT but the source vectors must be swapped.
4646 if (ExpectedElt == NumElts * 2) {
4651 if (M[i] < 0) continue; // ignore UNDEF indices
4652 if (ExpectedElt != static_cast<unsigned>(M[i]))
4656 // Adjust the index value if the source operands will be swapped.
4663 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4664 /// instruction with the specified blocksize. (The order of the elements
4665 /// within each block of the vector is reversed.)
4666 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4667 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4668 "Only possible block sizes for VREV are: 16, 32, 64");
4670 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4674 unsigned NumElts = VT.getVectorNumElements();
4675 unsigned BlockElts = M[0] + 1;
4676 // If the first shuffle index is UNDEF, be optimistic.
4678 BlockElts = BlockSize / EltSz;
4680 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4683 for (unsigned i = 0; i < NumElts; ++i) {
4684 if (M[i] < 0) continue; // ignore UNDEF indices
4685 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4692 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4693 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4694 // range, then 0 is placed into the resulting vector. So pretty much any mask
4695 // of 8 elements can work here.
4696 return VT == MVT::v8i8 && M.size() == 8;
4699 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4700 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4704 unsigned NumElts = VT.getVectorNumElements();
4705 WhichResult = (M[0] == 0 ? 0 : 1);
4706 for (unsigned i = 0; i < NumElts; i += 2) {
4707 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4708 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4714 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4715 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4716 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4717 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4718 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4722 unsigned NumElts = VT.getVectorNumElements();
4723 WhichResult = (M[0] == 0 ? 0 : 1);
4724 for (unsigned i = 0; i < NumElts; i += 2) {
4725 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4726 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4732 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4733 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4737 unsigned NumElts = VT.getVectorNumElements();
4738 WhichResult = (M[0] == 0 ? 0 : 1);
4739 for (unsigned i = 0; i != NumElts; ++i) {
4740 if (M[i] < 0) continue; // ignore UNDEF indices
4741 if ((unsigned) M[i] != 2 * i + WhichResult)
4745 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4746 if (VT.is64BitVector() && EltSz == 32)
4752 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4753 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4754 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4755 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4756 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4760 unsigned Half = VT.getVectorNumElements() / 2;
4761 WhichResult = (M[0] == 0 ? 0 : 1);
4762 for (unsigned j = 0; j != 2; ++j) {
4763 unsigned Idx = WhichResult;
4764 for (unsigned i = 0; i != Half; ++i) {
4765 int MIdx = M[i + j * Half];
4766 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4772 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4773 if (VT.is64BitVector() && EltSz == 32)
4779 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4780 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4784 unsigned NumElts = VT.getVectorNumElements();
4785 WhichResult = (M[0] == 0 ? 0 : 1);
4786 unsigned Idx = WhichResult * NumElts / 2;
4787 for (unsigned i = 0; i != NumElts; i += 2) {
4788 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4789 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4794 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4795 if (VT.is64BitVector() && EltSz == 32)
4801 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4802 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4803 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4804 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4805 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4809 unsigned NumElts = VT.getVectorNumElements();
4810 WhichResult = (M[0] == 0 ? 0 : 1);
4811 unsigned Idx = WhichResult * NumElts / 2;
4812 for (unsigned i = 0; i != NumElts; i += 2) {
4813 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4814 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4819 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4820 if (VT.is64BitVector() && EltSz == 32)
4826 /// \return true if this is a reverse operation on an vector.
4827 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4828 unsigned NumElts = VT.getVectorNumElements();
4829 // Make sure the mask has the right size.
4830 if (NumElts != M.size())
4833 // Look for <15, ..., 3, -1, 1, 0>.
4834 for (unsigned i = 0; i != NumElts; ++i)
4835 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4841 // If N is an integer constant that can be moved into a register in one
4842 // instruction, return an SDValue of such a constant (will become a MOV
4843 // instruction). Otherwise return null.
4844 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4845 const ARMSubtarget *ST, SDLoc dl) {
4847 if (!isa<ConstantSDNode>(N))
4849 Val = cast<ConstantSDNode>(N)->getZExtValue();
4851 if (ST->isThumb1Only()) {
4852 if (Val <= 255 || ~Val <= 255)
4853 return DAG.getConstant(Val, MVT::i32);
4855 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4856 return DAG.getConstant(Val, MVT::i32);
4861 // If this is a case we can't handle, return null and let the default
4862 // expansion code take care of it.
4863 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4864 const ARMSubtarget *ST) const {
4865 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4867 EVT VT = Op.getValueType();
4869 APInt SplatBits, SplatUndef;
4870 unsigned SplatBitSize;
4872 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4873 if (SplatBitSize <= 64) {
4874 // Check if an immediate VMOV works.
4876 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4877 SplatUndef.getZExtValue(), SplatBitSize,
4878 DAG, VmovVT, VT.is128BitVector(),
4880 if (Val.getNode()) {
4881 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4882 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4885 // Try an immediate VMVN.
4886 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4887 Val = isNEONModifiedImm(NegatedImm,
4888 SplatUndef.getZExtValue(), SplatBitSize,
4889 DAG, VmovVT, VT.is128BitVector(),
4891 if (Val.getNode()) {
4892 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4893 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4896 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4897 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4898 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4900 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4901 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4907 // Scan through the operands to see if only one value is used.
4909 // As an optimisation, even if more than one value is used it may be more
4910 // profitable to splat with one value then change some lanes.
4912 // Heuristically we decide to do this if the vector has a "dominant" value,
4913 // defined as splatted to more than half of the lanes.
4914 unsigned NumElts = VT.getVectorNumElements();
4915 bool isOnlyLowElement = true;
4916 bool usesOnlyOneValue = true;
4917 bool hasDominantValue = false;
4918 bool isConstant = true;
4920 // Map of the number of times a particular SDValue appears in the
4922 DenseMap<SDValue, unsigned> ValueCounts;
4924 for (unsigned i = 0; i < NumElts; ++i) {
4925 SDValue V = Op.getOperand(i);
4926 if (V.getOpcode() == ISD::UNDEF)
4929 isOnlyLowElement = false;
4930 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4933 ValueCounts.insert(std::make_pair(V, 0));
4934 unsigned &Count = ValueCounts[V];
4936 // Is this value dominant? (takes up more than half of the lanes)
4937 if (++Count > (NumElts / 2)) {
4938 hasDominantValue = true;
4942 if (ValueCounts.size() != 1)
4943 usesOnlyOneValue = false;
4944 if (!Value.getNode() && ValueCounts.size() > 0)
4945 Value = ValueCounts.begin()->first;
4947 if (ValueCounts.size() == 0)
4948 return DAG.getUNDEF(VT);
4950 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4951 // Keep going if we are hitting this case.
4952 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4953 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4955 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4957 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4958 // i32 and try again.
4959 if (hasDominantValue && EltSize <= 32) {
4963 // If we are VDUPing a value that comes directly from a vector, that will
4964 // cause an unnecessary move to and from a GPR, where instead we could
4965 // just use VDUPLANE. We can only do this if the lane being extracted
4966 // is at a constant index, as the VDUP from lane instructions only have
4967 // constant-index forms.
4968 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4969 isa<ConstantSDNode>(Value->getOperand(1))) {
4970 // We need to create a new undef vector to use for the VDUPLANE if the
4971 // size of the vector from which we get the value is different than the
4972 // size of the vector that we need to create. We will insert the element
4973 // such that the register coalescer will remove unnecessary copies.
4974 if (VT != Value->getOperand(0).getValueType()) {
4975 ConstantSDNode *constIndex;
4976 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4977 assert(constIndex && "The index is not a constant!");
4978 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4979 VT.getVectorNumElements();
4980 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4981 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4982 Value, DAG.getConstant(index, MVT::i32)),
4983 DAG.getConstant(index, MVT::i32));
4985 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4986 Value->getOperand(0), Value->getOperand(1));
4988 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4990 if (!usesOnlyOneValue) {
4991 // The dominant value was splatted as 'N', but we now have to insert
4992 // all differing elements.
4993 for (unsigned I = 0; I < NumElts; ++I) {
4994 if (Op.getOperand(I) == Value)
4996 SmallVector<SDValue, 3> Ops;
4998 Ops.push_back(Op.getOperand(I));
4999 Ops.push_back(DAG.getConstant(I, MVT::i32));
5000 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5005 if (VT.getVectorElementType().isFloatingPoint()) {
5006 SmallVector<SDValue, 8> Ops;
5007 for (unsigned i = 0; i < NumElts; ++i)
5008 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5010 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5011 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5012 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5014 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5016 if (usesOnlyOneValue) {
5017 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5018 if (isConstant && Val.getNode())
5019 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5023 // If all elements are constants and the case above didn't get hit, fall back
5024 // to the default expansion, which will generate a load from the constant
5029 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5031 SDValue shuffle = ReconstructShuffle(Op, DAG);
5032 if (shuffle != SDValue())
5036 // Vectors with 32- or 64-bit elements can be built by directly assigning
5037 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5038 // will be legalized.
5039 if (EltSize >= 32) {
5040 // Do the expansion with floating-point types, since that is what the VFP
5041 // registers are defined to use, and since i64 is not legal.
5042 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5043 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5044 SmallVector<SDValue, 8> Ops;
5045 for (unsigned i = 0; i < NumElts; ++i)
5046 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5047 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5048 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5051 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5052 // know the default expansion would otherwise fall back on something even
5053 // worse. For a vector with one or two non-undef values, that's
5054 // scalar_to_vector for the elements followed by a shuffle (provided the
5055 // shuffle is valid for the target) and materialization element by element
5056 // on the stack followed by a load for everything else.
5057 if (!isConstant && !usesOnlyOneValue) {
5058 SDValue Vec = DAG.getUNDEF(VT);
5059 for (unsigned i = 0 ; i < NumElts; ++i) {
5060 SDValue V = Op.getOperand(i);
5061 if (V.getOpcode() == ISD::UNDEF)
5063 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5064 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5072 // Gather data to see if the operation can be modelled as a
5073 // shuffle in combination with VEXTs.
5074 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5075 SelectionDAG &DAG) const {
5077 EVT VT = Op.getValueType();
5078 unsigned NumElts = VT.getVectorNumElements();
5080 SmallVector<SDValue, 2> SourceVecs;
5081 SmallVector<unsigned, 2> MinElts;
5082 SmallVector<unsigned, 2> MaxElts;
5084 for (unsigned i = 0; i < NumElts; ++i) {
5085 SDValue V = Op.getOperand(i);
5086 if (V.getOpcode() == ISD::UNDEF)
5088 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5089 // A shuffle can only come from building a vector from various
5090 // elements of other vectors.
5092 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5093 VT.getVectorElementType()) {
5094 // This code doesn't know how to handle shuffles where the vector
5095 // element types do not match (this happens because type legalization
5096 // promotes the return type of EXTRACT_VECTOR_ELT).
5097 // FIXME: It might be appropriate to extend this code to handle
5098 // mismatched types.
5102 // Record this extraction against the appropriate vector if possible...
5103 SDValue SourceVec = V.getOperand(0);
5104 // If the element number isn't a constant, we can't effectively
5105 // analyze what's going on.
5106 if (!isa<ConstantSDNode>(V.getOperand(1)))
5108 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5109 bool FoundSource = false;
5110 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5111 if (SourceVecs[j] == SourceVec) {
5112 if (MinElts[j] > EltNo)
5114 if (MaxElts[j] < EltNo)
5121 // Or record a new source if not...
5123 SourceVecs.push_back(SourceVec);
5124 MinElts.push_back(EltNo);
5125 MaxElts.push_back(EltNo);
5129 // Currently only do something sane when at most two source vectors
5131 if (SourceVecs.size() > 2)
5134 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5135 int VEXTOffsets[2] = {0, 0};
5137 // This loop extracts the usage patterns of the source vectors
5138 // and prepares appropriate SDValues for a shuffle if possible.
5139 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5140 if (SourceVecs[i].getValueType() == VT) {
5141 // No VEXT necessary
5142 ShuffleSrcs[i] = SourceVecs[i];
5145 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5146 // It probably isn't worth padding out a smaller vector just to
5147 // break it down again in a shuffle.
5151 // Since only 64-bit and 128-bit vectors are legal on ARM and
5152 // we've eliminated the other cases...
5153 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5154 "unexpected vector sizes in ReconstructShuffle");
5156 if (MaxElts[i] - MinElts[i] >= NumElts) {
5157 // Span too large for a VEXT to cope
5161 if (MinElts[i] >= NumElts) {
5162 // The extraction can just take the second half
5163 VEXTOffsets[i] = NumElts;
5164 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5166 DAG.getIntPtrConstant(NumElts));
5167 } else if (MaxElts[i] < NumElts) {
5168 // The extraction can just take the first half
5170 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5172 DAG.getIntPtrConstant(0));
5174 // An actual VEXT is needed
5175 VEXTOffsets[i] = MinElts[i];
5176 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5178 DAG.getIntPtrConstant(0));
5179 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5181 DAG.getIntPtrConstant(NumElts));
5182 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5183 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5187 SmallVector<int, 8> Mask;
5189 for (unsigned i = 0; i < NumElts; ++i) {
5190 SDValue Entry = Op.getOperand(i);
5191 if (Entry.getOpcode() == ISD::UNDEF) {
5196 SDValue ExtractVec = Entry.getOperand(0);
5197 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5198 .getOperand(1))->getSExtValue();
5199 if (ExtractVec == SourceVecs[0]) {
5200 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5202 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5206 // Final check before we try to produce nonsense...
5207 if (isShuffleMaskLegal(Mask, VT))
5208 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5214 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5215 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5216 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5217 /// are assumed to be legal.
5219 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5221 if (VT.getVectorNumElements() == 4 &&
5222 (VT.is128BitVector() || VT.is64BitVector())) {
5223 unsigned PFIndexes[4];
5224 for (unsigned i = 0; i != 4; ++i) {
5228 PFIndexes[i] = M[i];
5231 // Compute the index in the perfect shuffle table.
5232 unsigned PFTableIndex =
5233 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5234 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5235 unsigned Cost = (PFEntry >> 30);
5242 unsigned Imm, WhichResult;
5244 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5245 return (EltSize >= 32 ||
5246 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5247 isVREVMask(M, VT, 64) ||
5248 isVREVMask(M, VT, 32) ||
5249 isVREVMask(M, VT, 16) ||
5250 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5251 isVTBLMask(M, VT) ||
5252 isVTRNMask(M, VT, WhichResult) ||
5253 isVUZPMask(M, VT, WhichResult) ||
5254 isVZIPMask(M, VT, WhichResult) ||
5255 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5256 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5257 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5258 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5261 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5262 /// the specified operations to build the shuffle.
5263 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5264 SDValue RHS, SelectionDAG &DAG,
5266 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5267 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5268 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5271 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5280 OP_VUZPL, // VUZP, left result
5281 OP_VUZPR, // VUZP, right result
5282 OP_VZIPL, // VZIP, left result
5283 OP_VZIPR, // VZIP, right result
5284 OP_VTRNL, // VTRN, left result
5285 OP_VTRNR // VTRN, right result
5288 if (OpNum == OP_COPY) {
5289 if (LHSID == (1*9+2)*9+3) return LHS;
5290 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5294 SDValue OpLHS, OpRHS;
5295 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5296 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5297 EVT VT = OpLHS.getValueType();
5300 default: llvm_unreachable("Unknown shuffle opcode!");
5302 // VREV divides the vector in half and swaps within the half.
5303 if (VT.getVectorElementType() == MVT::i32 ||
5304 VT.getVectorElementType() == MVT::f32)
5305 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5306 // vrev <4 x i16> -> VREV32
5307 if (VT.getVectorElementType() == MVT::i16)
5308 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5309 // vrev <4 x i8> -> VREV16
5310 assert(VT.getVectorElementType() == MVT::i8);
5311 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5316 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5317 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5321 return DAG.getNode(ARMISD::VEXT, dl, VT,
5323 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5326 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5327 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5330 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5331 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5334 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5335 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5339 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5340 ArrayRef<int> ShuffleMask,
5341 SelectionDAG &DAG) {
5342 // Check to see if we can use the VTBL instruction.
5343 SDValue V1 = Op.getOperand(0);
5344 SDValue V2 = Op.getOperand(1);
5347 SmallVector<SDValue, 8> VTBLMask;
5348 for (ArrayRef<int>::iterator
5349 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5350 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5352 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5353 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5354 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5356 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5357 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5360 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5361 SelectionDAG &DAG) {
5363 SDValue OpLHS = Op.getOperand(0);
5364 EVT VT = OpLHS.getValueType();
5366 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5367 "Expect an v8i16/v16i8 type");
5368 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5369 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5370 // extract the first 8 bytes into the top double word and the last 8 bytes
5371 // into the bottom double word. The v8i16 case is similar.
5372 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5373 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5374 DAG.getConstant(ExtractNum, MVT::i32));
5377 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5378 SDValue V1 = Op.getOperand(0);
5379 SDValue V2 = Op.getOperand(1);
5381 EVT VT = Op.getValueType();
5382 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5384 // Convert shuffles that are directly supported on NEON to target-specific
5385 // DAG nodes, instead of keeping them as shuffles and matching them again
5386 // during code selection. This is more efficient and avoids the possibility
5387 // of inconsistencies between legalization and selection.
5388 // FIXME: floating-point vectors should be canonicalized to integer vectors
5389 // of the same time so that they get CSEd properly.
5390 ArrayRef<int> ShuffleMask = SVN->getMask();
5392 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5393 if (EltSize <= 32) {
5394 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5395 int Lane = SVN->getSplatIndex();
5396 // If this is undef splat, generate it via "just" vdup, if possible.
5397 if (Lane == -1) Lane = 0;
5399 // Test if V1 is a SCALAR_TO_VECTOR.
5400 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5401 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5403 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5404 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5406 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5407 !isa<ConstantSDNode>(V1.getOperand(0))) {
5408 bool IsScalarToVector = true;
5409 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5410 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5411 IsScalarToVector = false;
5414 if (IsScalarToVector)
5415 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5417 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5418 DAG.getConstant(Lane, MVT::i32));
5423 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5426 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5427 DAG.getConstant(Imm, MVT::i32));
5430 if (isVREVMask(ShuffleMask, VT, 64))
5431 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5432 if (isVREVMask(ShuffleMask, VT, 32))
5433 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5434 if (isVREVMask(ShuffleMask, VT, 16))
5435 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5437 if (V2->getOpcode() == ISD::UNDEF &&
5438 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5439 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5440 DAG.getConstant(Imm, MVT::i32));
5443 // Check for Neon shuffles that modify both input vectors in place.
5444 // If both results are used, i.e., if there are two shuffles with the same
5445 // source operands and with masks corresponding to both results of one of
5446 // these operations, DAG memoization will ensure that a single node is
5447 // used for both shuffles.
5448 unsigned WhichResult;
5449 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5450 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5451 V1, V2).getValue(WhichResult);
5452 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5453 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5454 V1, V2).getValue(WhichResult);
5455 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5456 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5457 V1, V2).getValue(WhichResult);
5459 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5460 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5461 V1, V1).getValue(WhichResult);
5462 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5463 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5464 V1, V1).getValue(WhichResult);
5465 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5466 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5467 V1, V1).getValue(WhichResult);
5470 // If the shuffle is not directly supported and it has 4 elements, use
5471 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5472 unsigned NumElts = VT.getVectorNumElements();
5474 unsigned PFIndexes[4];
5475 for (unsigned i = 0; i != 4; ++i) {
5476 if (ShuffleMask[i] < 0)
5479 PFIndexes[i] = ShuffleMask[i];
5482 // Compute the index in the perfect shuffle table.
5483 unsigned PFTableIndex =
5484 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5485 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5486 unsigned Cost = (PFEntry >> 30);
5489 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5492 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5493 if (EltSize >= 32) {
5494 // Do the expansion with floating-point types, since that is what the VFP
5495 // registers are defined to use, and since i64 is not legal.
5496 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5497 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5498 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5499 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5500 SmallVector<SDValue, 8> Ops;
5501 for (unsigned i = 0; i < NumElts; ++i) {
5502 if (ShuffleMask[i] < 0)
5503 Ops.push_back(DAG.getUNDEF(EltVT));
5505 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5506 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5507 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5510 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5511 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5514 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5515 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5517 if (VT == MVT::v8i8) {
5518 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5519 if (NewOp.getNode())
5526 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5527 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5528 SDValue Lane = Op.getOperand(2);
5529 if (!isa<ConstantSDNode>(Lane))
5535 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5536 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5537 SDValue Lane = Op.getOperand(1);
5538 if (!isa<ConstantSDNode>(Lane))
5541 SDValue Vec = Op.getOperand(0);
5542 if (Op.getValueType() == MVT::i32 &&
5543 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5545 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5551 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5552 // The only time a CONCAT_VECTORS operation can have legal types is when
5553 // two 64-bit vectors are concatenated to a 128-bit vector.
5554 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5555 "unexpected CONCAT_VECTORS");
5557 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5558 SDValue Op0 = Op.getOperand(0);
5559 SDValue Op1 = Op.getOperand(1);
5560 if (Op0.getOpcode() != ISD::UNDEF)
5561 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5562 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5563 DAG.getIntPtrConstant(0));
5564 if (Op1.getOpcode() != ISD::UNDEF)
5565 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5566 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5567 DAG.getIntPtrConstant(1));
5568 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5571 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5572 /// element has been zero/sign-extended, depending on the isSigned parameter,
5573 /// from an integer type half its size.
5574 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5576 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5577 EVT VT = N->getValueType(0);
5578 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5579 SDNode *BVN = N->getOperand(0).getNode();
5580 if (BVN->getValueType(0) != MVT::v4i32 ||
5581 BVN->getOpcode() != ISD::BUILD_VECTOR)
5583 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5584 unsigned HiElt = 1 - LoElt;
5585 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5586 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5587 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5588 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5589 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5592 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5593 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5596 if (Hi0->isNullValue() && Hi1->isNullValue())
5602 if (N->getOpcode() != ISD::BUILD_VECTOR)
5605 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5606 SDNode *Elt = N->getOperand(i).getNode();
5607 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5608 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5609 unsigned HalfSize = EltSize / 2;
5611 if (!isIntN(HalfSize, C->getSExtValue()))
5614 if (!isUIntN(HalfSize, C->getZExtValue()))
5625 /// isSignExtended - Check if a node is a vector value that is sign-extended
5626 /// or a constant BUILD_VECTOR with sign-extended elements.
5627 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5628 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5630 if (isExtendedBUILD_VECTOR(N, DAG, true))
5635 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5636 /// or a constant BUILD_VECTOR with zero-extended elements.
5637 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5638 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5640 if (isExtendedBUILD_VECTOR(N, DAG, false))
5645 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5646 if (OrigVT.getSizeInBits() >= 64)
5649 assert(OrigVT.isSimple() && "Expecting a simple value type");
5651 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5652 switch (OrigSimpleTy) {
5653 default: llvm_unreachable("Unexpected Vector Type");
5662 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5663 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5664 /// We insert the required extension here to get the vector to fill a D register.
5665 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5668 unsigned ExtOpcode) {
5669 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5670 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5671 // 64-bits we need to insert a new extension so that it will be 64-bits.
5672 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5673 if (OrigTy.getSizeInBits() >= 64)
5676 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5677 EVT NewVT = getExtensionTo64Bits(OrigTy);
5679 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5682 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5683 /// does not do any sign/zero extension. If the original vector is less
5684 /// than 64 bits, an appropriate extension will be added after the load to
5685 /// reach a total size of 64 bits. We have to add the extension separately
5686 /// because ARM does not have a sign/zero extending load for vectors.
5687 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5688 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5690 // The load already has the right type.
5691 if (ExtendedTy == LD->getMemoryVT())
5692 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5693 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5694 LD->isNonTemporal(), LD->isInvariant(),
5695 LD->getAlignment());
5697 // We need to create a zextload/sextload. We cannot just create a load
5698 // followed by a zext/zext node because LowerMUL is also run during normal
5699 // operation legalization where we can't create illegal types.
5700 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5701 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5702 LD->getMemoryVT(), LD->isVolatile(),
5703 LD->isNonTemporal(), LD->getAlignment());
5706 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5707 /// extending load, or BUILD_VECTOR with extended elements, return the
5708 /// unextended value. The unextended vector should be 64 bits so that it can
5709 /// be used as an operand to a VMULL instruction. If the original vector size
5710 /// before extension is less than 64 bits we add a an extension to resize
5711 /// the vector to 64 bits.
5712 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5713 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5714 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5715 N->getOperand(0)->getValueType(0),
5719 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5720 return SkipLoadExtensionForVMULL(LD, DAG);
5722 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5723 // have been legalized as a BITCAST from v4i32.
5724 if (N->getOpcode() == ISD::BITCAST) {
5725 SDNode *BVN = N->getOperand(0).getNode();
5726 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5727 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5728 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5729 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5730 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5732 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5733 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5734 EVT VT = N->getValueType(0);
5735 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5736 unsigned NumElts = VT.getVectorNumElements();
5737 MVT TruncVT = MVT::getIntegerVT(EltSize);
5738 SmallVector<SDValue, 8> Ops;
5739 for (unsigned i = 0; i != NumElts; ++i) {
5740 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5741 const APInt &CInt = C->getAPIntValue();
5742 // Element types smaller than 32 bits are not legal, so use i32 elements.
5743 // The values are implicitly truncated so sext vs. zext doesn't matter.
5744 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5746 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5747 MVT::getVectorVT(TruncVT, NumElts), Ops);
5750 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5751 unsigned Opcode = N->getOpcode();
5752 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5753 SDNode *N0 = N->getOperand(0).getNode();
5754 SDNode *N1 = N->getOperand(1).getNode();
5755 return N0->hasOneUse() && N1->hasOneUse() &&
5756 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5761 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5762 unsigned Opcode = N->getOpcode();
5763 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5764 SDNode *N0 = N->getOperand(0).getNode();
5765 SDNode *N1 = N->getOperand(1).getNode();
5766 return N0->hasOneUse() && N1->hasOneUse() &&
5767 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5772 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5773 // Multiplications are only custom-lowered for 128-bit vectors so that
5774 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5775 EVT VT = Op.getValueType();
5776 assert(VT.is128BitVector() && VT.isInteger() &&
5777 "unexpected type for custom-lowering ISD::MUL");
5778 SDNode *N0 = Op.getOperand(0).getNode();
5779 SDNode *N1 = Op.getOperand(1).getNode();
5780 unsigned NewOpc = 0;
5782 bool isN0SExt = isSignExtended(N0, DAG);
5783 bool isN1SExt = isSignExtended(N1, DAG);
5784 if (isN0SExt && isN1SExt)
5785 NewOpc = ARMISD::VMULLs;
5787 bool isN0ZExt = isZeroExtended(N0, DAG);
5788 bool isN1ZExt = isZeroExtended(N1, DAG);
5789 if (isN0ZExt && isN1ZExt)
5790 NewOpc = ARMISD::VMULLu;
5791 else if (isN1SExt || isN1ZExt) {
5792 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5793 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5794 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5795 NewOpc = ARMISD::VMULLs;
5797 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5798 NewOpc = ARMISD::VMULLu;
5800 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5802 NewOpc = ARMISD::VMULLu;
5808 if (VT == MVT::v2i64)
5809 // Fall through to expand this. It is not legal.
5812 // Other vector multiplications are legal.
5817 // Legalize to a VMULL instruction.
5820 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5822 Op0 = SkipExtensionForVMULL(N0, DAG);
5823 assert(Op0.getValueType().is64BitVector() &&
5824 Op1.getValueType().is64BitVector() &&
5825 "unexpected types for extended operands to VMULL");
5826 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5829 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5830 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5837 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5838 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5839 EVT Op1VT = Op1.getValueType();
5840 return DAG.getNode(N0->getOpcode(), DL, VT,
5841 DAG.getNode(NewOpc, DL, VT,
5842 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5843 DAG.getNode(NewOpc, DL, VT,
5844 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5848 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5850 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5851 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5852 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5853 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5854 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5855 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5856 // Get reciprocal estimate.
5857 // float4 recip = vrecpeq_f32(yf);
5858 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5859 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5860 // Because char has a smaller range than uchar, we can actually get away
5861 // without any newton steps. This requires that we use a weird bias
5862 // of 0xb000, however (again, this has been exhaustively tested).
5863 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5864 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5865 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5866 Y = DAG.getConstant(0xb000, MVT::i32);
5867 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5868 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5869 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5870 // Convert back to short.
5871 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5872 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5877 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5879 // Convert to float.
5880 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5881 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5882 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5883 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5884 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5885 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5887 // Use reciprocal estimate and one refinement step.
5888 // float4 recip = vrecpeq_f32(yf);
5889 // recip *= vrecpsq_f32(yf, recip);
5890 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5891 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5892 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5893 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5895 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5896 // Because short has a smaller range than ushort, we can actually get away
5897 // with only a single newton step. This requires that we use a weird bias
5898 // of 89, however (again, this has been exhaustively tested).
5899 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5900 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5901 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5902 N1 = DAG.getConstant(0x89, MVT::i32);
5903 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5904 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5905 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5906 // Convert back to integer and return.
5907 // return vmovn_s32(vcvt_s32_f32(result));
5908 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5909 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5913 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5914 EVT VT = Op.getValueType();
5915 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5916 "unexpected type for custom-lowering ISD::SDIV");
5919 SDValue N0 = Op.getOperand(0);
5920 SDValue N1 = Op.getOperand(1);
5923 if (VT == MVT::v8i8) {
5924 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5925 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5927 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5928 DAG.getIntPtrConstant(4));
5929 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5930 DAG.getIntPtrConstant(4));
5931 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5932 DAG.getIntPtrConstant(0));
5933 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5934 DAG.getIntPtrConstant(0));
5936 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5937 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5939 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5940 N0 = LowerCONCAT_VECTORS(N0, DAG);
5942 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5945 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5948 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5949 EVT VT = Op.getValueType();
5950 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5951 "unexpected type for custom-lowering ISD::UDIV");
5954 SDValue N0 = Op.getOperand(0);
5955 SDValue N1 = Op.getOperand(1);
5958 if (VT == MVT::v8i8) {
5959 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5960 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5962 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5963 DAG.getIntPtrConstant(4));
5964 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5965 DAG.getIntPtrConstant(4));
5966 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5967 DAG.getIntPtrConstant(0));
5968 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5969 DAG.getIntPtrConstant(0));
5971 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5972 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5974 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5975 N0 = LowerCONCAT_VECTORS(N0, DAG);
5977 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5978 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5983 // v4i16 sdiv ... Convert to float.
5984 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5985 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5986 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5987 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5988 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5989 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5991 // Use reciprocal estimate and two refinement steps.
5992 // float4 recip = vrecpeq_f32(yf);
5993 // recip *= vrecpsq_f32(yf, recip);
5994 // recip *= vrecpsq_f32(yf, recip);
5995 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5996 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5997 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5998 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6000 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6001 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6002 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6004 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6005 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6006 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6007 // and that it will never cause us to return an answer too large).
6008 // float4 result = as_float4(as_int4(xf*recip) + 2);
6009 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6010 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6011 N1 = DAG.getConstant(2, MVT::i32);
6012 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6013 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6014 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6015 // Convert back to integer and return.
6016 // return vmovn_u32(vcvt_s32_f32(result));
6017 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6018 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6022 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6023 EVT VT = Op.getNode()->getValueType(0);
6024 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6027 bool ExtraOp = false;
6028 switch (Op.getOpcode()) {
6029 default: llvm_unreachable("Invalid code");
6030 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6031 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6032 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6033 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6037 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6039 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6040 Op.getOperand(1), Op.getOperand(2));
6043 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6044 assert(Subtarget->isTargetDarwin());
6046 // For iOS, we want to call an alternative entry point: __sincos_stret,
6047 // return values are passed via sret.
6049 SDValue Arg = Op.getOperand(0);
6050 EVT ArgVT = Arg.getValueType();
6051 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6053 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6054 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6056 // Pair of floats / doubles used to pass the result.
6057 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6059 // Create stack object for sret.
6060 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6061 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6062 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6063 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6069 Entry.Ty = RetTy->getPointerTo();
6070 Entry.isSExt = false;
6071 Entry.isZExt = false;
6072 Entry.isSRet = true;
6073 Args.push_back(Entry);
6077 Entry.isSExt = false;
6078 Entry.isZExt = false;
6079 Args.push_back(Entry);
6081 const char *LibcallName = (ArgVT == MVT::f64)
6082 ? "__sincos_stret" : "__sincosf_stret";
6083 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6085 TargetLowering::CallLoweringInfo CLI(DAG);
6086 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6087 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6089 .setDiscardResult();
6091 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6093 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6094 MachinePointerInfo(), false, false, false, 0);
6096 // Address of cos field.
6097 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6098 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6099 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6100 MachinePointerInfo(), false, false, false, 0);
6102 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6103 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6104 LoadSin.getValue(0), LoadCos.getValue(0));
6107 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6108 // Monotonic load/store is legal for all targets
6109 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6112 // Acquire/Release load/store is not legal for targets without a
6113 // dmb or equivalent available.
6117 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6118 SmallVectorImpl<SDValue> &Results,
6120 const ARMSubtarget *Subtarget) {
6122 SDValue Cycles32, OutChain;
6124 if (Subtarget->hasPerfMon()) {
6125 // Under Power Management extensions, the cycle-count is:
6126 // mrc p15, #0, <Rt>, c9, c13, #0
6127 SDValue Ops[] = { N->getOperand(0), // Chain
6128 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6129 DAG.getConstant(15, MVT::i32),
6130 DAG.getConstant(0, MVT::i32),
6131 DAG.getConstant(9, MVT::i32),
6132 DAG.getConstant(13, MVT::i32),
6133 DAG.getConstant(0, MVT::i32)
6136 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6137 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6138 OutChain = Cycles32.getValue(1);
6140 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6141 // there are older ARM CPUs that have implementation-specific ways of
6142 // obtaining this information (FIXME!).
6143 Cycles32 = DAG.getConstant(0, MVT::i32);
6144 OutChain = DAG.getEntryNode();
6148 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6149 Cycles32, DAG.getConstant(0, MVT::i32));
6150 Results.push_back(Cycles64);
6151 Results.push_back(OutChain);
6154 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6155 switch (Op.getOpcode()) {
6156 default: llvm_unreachable("Don't know how to custom lower this!");
6157 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6158 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6159 case ISD::GlobalAddress:
6160 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6161 default: llvm_unreachable("unknown object format");
6163 return LowerGlobalAddressWindows(Op, DAG);
6165 return LowerGlobalAddressELF(Op, DAG);
6167 return LowerGlobalAddressDarwin(Op, DAG);
6169 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6170 case ISD::SELECT: return LowerSELECT(Op, DAG);
6171 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6172 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6173 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6174 case ISD::VASTART: return LowerVASTART(Op, DAG);
6175 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6176 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6177 case ISD::SINT_TO_FP:
6178 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6179 case ISD::FP_TO_SINT:
6180 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6181 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6182 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6183 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6184 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6185 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6186 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6187 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6189 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6192 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6193 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6194 case ISD::SRL_PARTS:
6195 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6196 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6197 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6198 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6199 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6200 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6201 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6202 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6203 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6204 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6205 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6206 case ISD::MUL: return LowerMUL(Op, DAG);
6207 case ISD::SDIV: return LowerSDIV(Op, DAG);
6208 case ISD::UDIV: return LowerUDIV(Op, DAG);
6212 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6217 return LowerXALUO(Op, DAG);
6218 case ISD::ATOMIC_LOAD:
6219 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6220 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6222 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6223 case ISD::DYNAMIC_STACKALLOC:
6224 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6225 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6226 llvm_unreachable("Don't know how to custom lower this!");
6230 /// ReplaceNodeResults - Replace the results of node with an illegal result
6231 /// type with new values built out of custom code.
6232 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6233 SmallVectorImpl<SDValue>&Results,
6234 SelectionDAG &DAG) const {
6236 switch (N->getOpcode()) {
6238 llvm_unreachable("Don't know how to custom expand this!");
6240 Res = ExpandBITCAST(N, DAG);
6244 Res = Expand64BitShift(N, DAG, Subtarget);
6246 case ISD::READCYCLECOUNTER:
6247 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6251 Results.push_back(Res);
6254 //===----------------------------------------------------------------------===//
6255 // ARM Scheduler Hooks
6256 //===----------------------------------------------------------------------===//
6258 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6259 /// registers the function context.
6260 void ARMTargetLowering::
6261 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6262 MachineBasicBlock *DispatchBB, int FI) const {
6263 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6264 DebugLoc dl = MI->getDebugLoc();
6265 MachineFunction *MF = MBB->getParent();
6266 MachineRegisterInfo *MRI = &MF->getRegInfo();
6267 MachineConstantPool *MCP = MF->getConstantPool();
6268 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6269 const Function *F = MF->getFunction();
6271 bool isThumb = Subtarget->isThumb();
6272 bool isThumb2 = Subtarget->isThumb2();
6274 unsigned PCLabelId = AFI->createPICLabelUId();
6275 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6276 ARMConstantPoolValue *CPV =
6277 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6278 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6280 const TargetRegisterClass *TRC = isThumb ?
6281 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6282 (const TargetRegisterClass*)&ARM::GPRRegClass;
6284 // Grab constant pool and fixed stack memory operands.
6285 MachineMemOperand *CPMMO =
6286 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6287 MachineMemOperand::MOLoad, 4, 4);
6289 MachineMemOperand *FIMMOSt =
6290 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6291 MachineMemOperand::MOStore, 4, 4);
6293 // Load the address of the dispatch MBB into the jump buffer.
6295 // Incoming value: jbuf
6296 // ldr.n r5, LCPI1_1
6299 // str r5, [$jbuf, #+4] ; &jbuf[1]
6300 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6301 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6302 .addConstantPoolIndex(CPI)
6303 .addMemOperand(CPMMO));
6304 // Set the low bit because of thumb mode.
6305 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6307 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6308 .addReg(NewVReg1, RegState::Kill)
6310 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6311 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6312 .addReg(NewVReg2, RegState::Kill)
6314 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6315 .addReg(NewVReg3, RegState::Kill)
6317 .addImm(36) // &jbuf[1] :: pc
6318 .addMemOperand(FIMMOSt));
6319 } else if (isThumb) {
6320 // Incoming value: jbuf
6321 // ldr.n r1, LCPI1_4
6325 // add r2, $jbuf, #+4 ; &jbuf[1]
6327 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6328 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6329 .addConstantPoolIndex(CPI)
6330 .addMemOperand(CPMMO));
6331 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6332 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6333 .addReg(NewVReg1, RegState::Kill)
6335 // Set the low bit because of thumb mode.
6336 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6337 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6338 .addReg(ARM::CPSR, RegState::Define)
6340 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6341 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6342 .addReg(ARM::CPSR, RegState::Define)
6343 .addReg(NewVReg2, RegState::Kill)
6344 .addReg(NewVReg3, RegState::Kill));
6345 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6346 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6348 .addImm(36)); // &jbuf[1] :: pc
6349 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6350 .addReg(NewVReg4, RegState::Kill)
6351 .addReg(NewVReg5, RegState::Kill)
6353 .addMemOperand(FIMMOSt));
6355 // Incoming value: jbuf
6358 // str r1, [$jbuf, #+4] ; &jbuf[1]
6359 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6360 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6361 .addConstantPoolIndex(CPI)
6363 .addMemOperand(CPMMO));
6364 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6365 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6366 .addReg(NewVReg1, RegState::Kill)
6367 .addImm(PCLabelId));
6368 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6369 .addReg(NewVReg2, RegState::Kill)
6371 .addImm(36) // &jbuf[1] :: pc
6372 .addMemOperand(FIMMOSt));
6376 MachineBasicBlock *ARMTargetLowering::
6377 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6378 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6379 DebugLoc dl = MI->getDebugLoc();
6380 MachineFunction *MF = MBB->getParent();
6381 MachineRegisterInfo *MRI = &MF->getRegInfo();
6382 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6383 MachineFrameInfo *MFI = MF->getFrameInfo();
6384 int FI = MFI->getFunctionContextIndex();
6386 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6387 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6388 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6390 // Get a mapping of the call site numbers to all of the landing pads they're
6392 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6393 unsigned MaxCSNum = 0;
6394 MachineModuleInfo &MMI = MF->getMMI();
6395 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6397 if (!BB->isLandingPad()) continue;
6399 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6401 for (MachineBasicBlock::iterator
6402 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6403 if (!II->isEHLabel()) continue;
6405 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6406 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6408 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6409 for (SmallVectorImpl<unsigned>::iterator
6410 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6411 CSI != CSE; ++CSI) {
6412 CallSiteNumToLPad[*CSI].push_back(BB);
6413 MaxCSNum = std::max(MaxCSNum, *CSI);
6419 // Get an ordered list of the machine basic blocks for the jump table.
6420 std::vector<MachineBasicBlock*> LPadList;
6421 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6422 LPadList.reserve(CallSiteNumToLPad.size());
6423 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6424 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6425 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6426 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6427 LPadList.push_back(*II);
6428 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6432 assert(!LPadList.empty() &&
6433 "No landing pad destinations for the dispatch jump table!");
6435 // Create the jump table and associated information.
6436 MachineJumpTableInfo *JTI =
6437 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6438 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6439 unsigned UId = AFI->createJumpTableUId();
6440 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6442 // Create the MBBs for the dispatch code.
6444 // Shove the dispatch's address into the return slot in the function context.
6445 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6446 DispatchBB->setIsLandingPad();
6448 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6449 unsigned trap_opcode;
6450 if (Subtarget->isThumb())
6451 trap_opcode = ARM::tTRAP;
6453 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6455 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6456 DispatchBB->addSuccessor(TrapBB);
6458 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6459 DispatchBB->addSuccessor(DispContBB);
6462 MF->insert(MF->end(), DispatchBB);
6463 MF->insert(MF->end(), DispContBB);
6464 MF->insert(MF->end(), TrapBB);
6466 // Insert code into the entry block that creates and registers the function
6468 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6470 MachineMemOperand *FIMMOLd =
6471 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6472 MachineMemOperand::MOLoad |
6473 MachineMemOperand::MOVolatile, 4, 4);
6475 MachineInstrBuilder MIB;
6476 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6478 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6479 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6481 // Add a register mask with no preserved registers. This results in all
6482 // registers being marked as clobbered.
6483 MIB.addRegMask(RI.getNoPreservedMask());
6485 unsigned NumLPads = LPadList.size();
6486 if (Subtarget->isThumb2()) {
6487 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6488 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6491 .addMemOperand(FIMMOLd));
6493 if (NumLPads < 256) {
6494 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6496 .addImm(LPadList.size()));
6498 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6499 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6500 .addImm(NumLPads & 0xFFFF));
6502 unsigned VReg2 = VReg1;
6503 if ((NumLPads & 0xFFFF0000) != 0) {
6504 VReg2 = MRI->createVirtualRegister(TRC);
6505 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6507 .addImm(NumLPads >> 16));
6510 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6515 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6520 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6521 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6522 .addJumpTableIndex(MJTI)
6525 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6528 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6529 .addReg(NewVReg3, RegState::Kill)
6531 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6533 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6534 .addReg(NewVReg4, RegState::Kill)
6536 .addJumpTableIndex(MJTI)
6538 } else if (Subtarget->isThumb()) {
6539 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6540 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6543 .addMemOperand(FIMMOLd));
6545 if (NumLPads < 256) {
6546 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6550 MachineConstantPool *ConstantPool = MF->getConstantPool();
6551 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6552 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6554 // MachineConstantPool wants an explicit alignment.
6555 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6557 Align = getDataLayout()->getTypeAllocSize(C->getType());
6558 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6560 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6561 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6562 .addReg(VReg1, RegState::Define)
6563 .addConstantPoolIndex(Idx));
6564 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6569 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6574 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6575 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6576 .addReg(ARM::CPSR, RegState::Define)
6580 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6581 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6582 .addJumpTableIndex(MJTI)
6585 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6586 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6587 .addReg(ARM::CPSR, RegState::Define)
6588 .addReg(NewVReg2, RegState::Kill)
6591 MachineMemOperand *JTMMOLd =
6592 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6593 MachineMemOperand::MOLoad, 4, 4);
6595 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6596 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6597 .addReg(NewVReg4, RegState::Kill)
6599 .addMemOperand(JTMMOLd));
6601 unsigned NewVReg6 = NewVReg5;
6602 if (RelocM == Reloc::PIC_) {
6603 NewVReg6 = MRI->createVirtualRegister(TRC);
6604 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6605 .addReg(ARM::CPSR, RegState::Define)
6606 .addReg(NewVReg5, RegState::Kill)
6610 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6611 .addReg(NewVReg6, RegState::Kill)
6612 .addJumpTableIndex(MJTI)
6615 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6616 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6619 .addMemOperand(FIMMOLd));
6621 if (NumLPads < 256) {
6622 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6625 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6626 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6627 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6628 .addImm(NumLPads & 0xFFFF));
6630 unsigned VReg2 = VReg1;
6631 if ((NumLPads & 0xFFFF0000) != 0) {
6632 VReg2 = MRI->createVirtualRegister(TRC);
6633 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6635 .addImm(NumLPads >> 16));
6638 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6642 MachineConstantPool *ConstantPool = MF->getConstantPool();
6643 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6644 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6646 // MachineConstantPool wants an explicit alignment.
6647 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6649 Align = getDataLayout()->getTypeAllocSize(C->getType());
6650 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6652 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6653 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6654 .addReg(VReg1, RegState::Define)
6655 .addConstantPoolIndex(Idx)
6657 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6659 .addReg(VReg1, RegState::Kill));
6662 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6667 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6669 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6671 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6672 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6673 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6674 .addJumpTableIndex(MJTI)
6677 MachineMemOperand *JTMMOLd =
6678 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6679 MachineMemOperand::MOLoad, 4, 4);
6680 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6682 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6683 .addReg(NewVReg3, RegState::Kill)
6686 .addMemOperand(JTMMOLd));
6688 if (RelocM == Reloc::PIC_) {
6689 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6690 .addReg(NewVReg5, RegState::Kill)
6692 .addJumpTableIndex(MJTI)
6695 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6696 .addReg(NewVReg5, RegState::Kill)
6697 .addJumpTableIndex(MJTI)
6702 // Add the jump table entries as successors to the MBB.
6703 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6704 for (std::vector<MachineBasicBlock*>::iterator
6705 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6706 MachineBasicBlock *CurMBB = *I;
6707 if (SeenMBBs.insert(CurMBB))
6708 DispContBB->addSuccessor(CurMBB);
6711 // N.B. the order the invoke BBs are processed in doesn't matter here.
6712 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6713 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6714 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6715 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6716 MachineBasicBlock *BB = *I;
6718 // Remove the landing pad successor from the invoke block and replace it
6719 // with the new dispatch block.
6720 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6722 while (!Successors.empty()) {
6723 MachineBasicBlock *SMBB = Successors.pop_back_val();
6724 if (SMBB->isLandingPad()) {
6725 BB->removeSuccessor(SMBB);
6726 MBBLPads.push_back(SMBB);
6730 BB->addSuccessor(DispatchBB);
6732 // Find the invoke call and mark all of the callee-saved registers as
6733 // 'implicit defined' so that they're spilled. This prevents code from
6734 // moving instructions to before the EH block, where they will never be
6736 for (MachineBasicBlock::reverse_iterator
6737 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6738 if (!II->isCall()) continue;
6740 DenseMap<unsigned, bool> DefRegs;
6741 for (MachineInstr::mop_iterator
6742 OI = II->operands_begin(), OE = II->operands_end();
6744 if (!OI->isReg()) continue;
6745 DefRegs[OI->getReg()] = true;
6748 MachineInstrBuilder MIB(*MF, &*II);
6750 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6751 unsigned Reg = SavedRegs[i];
6752 if (Subtarget->isThumb2() &&
6753 !ARM::tGPRRegClass.contains(Reg) &&
6754 !ARM::hGPRRegClass.contains(Reg))
6756 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6758 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6761 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6768 // Mark all former landing pads as non-landing pads. The dispatch is the only
6770 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6771 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6772 (*I)->setIsLandingPad(false);
6774 // The instruction is gone now.
6775 MI->eraseFromParent();
6781 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6782 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6783 E = MBB->succ_end(); I != E; ++I)
6786 llvm_unreachable("Expecting a BB with two successors!");
6789 /// Return the load opcode for a given load size. If load size >= 8,
6790 /// neon opcode will be returned.
6791 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6793 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6794 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6796 return LdSize == 4 ? ARM::tLDRi
6797 : LdSize == 2 ? ARM::tLDRHi
6798 : LdSize == 1 ? ARM::tLDRBi : 0;
6800 return LdSize == 4 ? ARM::t2LDR_POST
6801 : LdSize == 2 ? ARM::t2LDRH_POST
6802 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6803 return LdSize == 4 ? ARM::LDR_POST_IMM
6804 : LdSize == 2 ? ARM::LDRH_POST
6805 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6808 /// Return the store opcode for a given store size. If store size >= 8,
6809 /// neon opcode will be returned.
6810 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6812 return StSize == 16 ? ARM::VST1q32wb_fixed
6813 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6815 return StSize == 4 ? ARM::tSTRi
6816 : StSize == 2 ? ARM::tSTRHi
6817 : StSize == 1 ? ARM::tSTRBi : 0;
6819 return StSize == 4 ? ARM::t2STR_POST
6820 : StSize == 2 ? ARM::t2STRH_POST
6821 : StSize == 1 ? ARM::t2STRB_POST : 0;
6822 return StSize == 4 ? ARM::STR_POST_IMM
6823 : StSize == 2 ? ARM::STRH_POST
6824 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6827 /// Emit a post-increment load operation with given size. The instructions
6828 /// will be added to BB at Pos.
6829 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6830 const TargetInstrInfo *TII, DebugLoc dl,
6831 unsigned LdSize, unsigned Data, unsigned AddrIn,
6832 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6833 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6834 assert(LdOpc != 0 && "Should have a load opcode");
6836 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6837 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6839 } else if (IsThumb1) {
6840 // load + update AddrIn
6841 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6842 .addReg(AddrIn).addImm(0));
6843 MachineInstrBuilder MIB =
6844 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6845 MIB = AddDefaultT1CC(MIB);
6846 MIB.addReg(AddrIn).addImm(LdSize);
6847 AddDefaultPred(MIB);
6848 } else if (IsThumb2) {
6849 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6850 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6853 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6854 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6855 .addReg(0).addImm(LdSize));
6859 /// Emit a post-increment store operation with given size. The instructions
6860 /// will be added to BB at Pos.
6861 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6862 const TargetInstrInfo *TII, DebugLoc dl,
6863 unsigned StSize, unsigned Data, unsigned AddrIn,
6864 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6865 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6866 assert(StOpc != 0 && "Should have a store opcode");
6868 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6869 .addReg(AddrIn).addImm(0).addReg(Data));
6870 } else if (IsThumb1) {
6871 // store + update AddrIn
6872 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6873 .addReg(AddrIn).addImm(0));
6874 MachineInstrBuilder MIB =
6875 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6876 MIB = AddDefaultT1CC(MIB);
6877 MIB.addReg(AddrIn).addImm(StSize);
6878 AddDefaultPred(MIB);
6879 } else if (IsThumb2) {
6880 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6881 .addReg(Data).addReg(AddrIn).addImm(StSize));
6883 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6884 .addReg(Data).addReg(AddrIn).addReg(0)
6890 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6891 MachineBasicBlock *BB) const {
6892 // This pseudo instruction has 3 operands: dst, src, size
6893 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6894 // Otherwise, we will generate unrolled scalar copies.
6895 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6896 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6897 MachineFunction::iterator It = BB;
6900 unsigned dest = MI->getOperand(0).getReg();
6901 unsigned src = MI->getOperand(1).getReg();
6902 unsigned SizeVal = MI->getOperand(2).getImm();
6903 unsigned Align = MI->getOperand(3).getImm();
6904 DebugLoc dl = MI->getDebugLoc();
6906 MachineFunction *MF = BB->getParent();
6907 MachineRegisterInfo &MRI = MF->getRegInfo();
6908 unsigned UnitSize = 0;
6909 const TargetRegisterClass *TRC = nullptr;
6910 const TargetRegisterClass *VecTRC = nullptr;
6912 bool IsThumb1 = Subtarget->isThumb1Only();
6913 bool IsThumb2 = Subtarget->isThumb2();
6917 } else if (Align & 2) {
6920 // Check whether we can use NEON instructions.
6921 if (!MF->getFunction()->getAttributes().
6922 hasAttribute(AttributeSet::FunctionIndex,
6923 Attribute::NoImplicitFloat) &&
6924 Subtarget->hasNEON()) {
6925 if ((Align % 16 == 0) && SizeVal >= 16)
6927 else if ((Align % 8 == 0) && SizeVal >= 8)
6930 // Can't use NEON instructions.
6935 // Select the correct opcode and register class for unit size load/store
6936 bool IsNeon = UnitSize >= 8;
6937 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6938 : (const TargetRegisterClass *)&ARM::GPRRegClass;
6940 VecTRC = UnitSize == 16
6941 ? (const TargetRegisterClass *)&ARM::DPairRegClass
6943 ? (const TargetRegisterClass *)&ARM::DPRRegClass
6946 unsigned BytesLeft = SizeVal % UnitSize;
6947 unsigned LoopSize = SizeVal - BytesLeft;
6949 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6950 // Use LDR and STR to copy.
6951 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6952 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6953 unsigned srcIn = src;
6954 unsigned destIn = dest;
6955 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6956 unsigned srcOut = MRI.createVirtualRegister(TRC);
6957 unsigned destOut = MRI.createVirtualRegister(TRC);
6958 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6959 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6960 IsThumb1, IsThumb2);
6961 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6962 IsThumb1, IsThumb2);
6967 // Handle the leftover bytes with LDRB and STRB.
6968 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6969 // [destOut] = STRB_POST(scratch, destIn, 1)
6970 for (unsigned i = 0; i < BytesLeft; i++) {
6971 unsigned srcOut = MRI.createVirtualRegister(TRC);
6972 unsigned destOut = MRI.createVirtualRegister(TRC);
6973 unsigned scratch = MRI.createVirtualRegister(TRC);
6974 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6975 IsThumb1, IsThumb2);
6976 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6977 IsThumb1, IsThumb2);
6981 MI->eraseFromParent(); // The instruction is gone now.
6985 // Expand the pseudo op to a loop.
6988 // movw varEnd, # --> with thumb2
6990 // ldrcp varEnd, idx --> without thumb2
6991 // fallthrough --> loopMBB
6993 // PHI varPhi, varEnd, varLoop
6994 // PHI srcPhi, src, srcLoop
6995 // PHI destPhi, dst, destLoop
6996 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6997 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6998 // subs varLoop, varPhi, #UnitSize
7000 // fallthrough --> exitMBB
7002 // epilogue to handle left-over bytes
7003 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7004 // [destOut] = STRB_POST(scratch, destLoop, 1)
7005 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7006 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7007 MF->insert(It, loopMBB);
7008 MF->insert(It, exitMBB);
7010 // Transfer the remainder of BB and its successor edges to exitMBB.
7011 exitMBB->splice(exitMBB->begin(), BB,
7012 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7013 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7015 // Load an immediate to varEnd.
7016 unsigned varEnd = MRI.createVirtualRegister(TRC);
7018 unsigned Vtmp = varEnd;
7019 if ((LoopSize & 0xFFFF0000) != 0)
7020 Vtmp = MRI.createVirtualRegister(TRC);
7021 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7022 .addImm(LoopSize & 0xFFFF));
7024 if ((LoopSize & 0xFFFF0000) != 0)
7025 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7026 .addReg(Vtmp).addImm(LoopSize >> 16));
7028 MachineConstantPool *ConstantPool = MF->getConstantPool();
7029 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7030 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7032 // MachineConstantPool wants an explicit alignment.
7033 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7035 Align = getDataLayout()->getTypeAllocSize(C->getType());
7036 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7039 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7040 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7042 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7043 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7045 BB->addSuccessor(loopMBB);
7047 // Generate the loop body:
7048 // varPhi = PHI(varLoop, varEnd)
7049 // srcPhi = PHI(srcLoop, src)
7050 // destPhi = PHI(destLoop, dst)
7051 MachineBasicBlock *entryBB = BB;
7053 unsigned varLoop = MRI.createVirtualRegister(TRC);
7054 unsigned varPhi = MRI.createVirtualRegister(TRC);
7055 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7056 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7057 unsigned destLoop = MRI.createVirtualRegister(TRC);
7058 unsigned destPhi = MRI.createVirtualRegister(TRC);
7060 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7061 .addReg(varLoop).addMBB(loopMBB)
7062 .addReg(varEnd).addMBB(entryBB);
7063 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7064 .addReg(srcLoop).addMBB(loopMBB)
7065 .addReg(src).addMBB(entryBB);
7066 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7067 .addReg(destLoop).addMBB(loopMBB)
7068 .addReg(dest).addMBB(entryBB);
7070 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7071 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7072 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7073 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7074 IsThumb1, IsThumb2);
7075 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7076 IsThumb1, IsThumb2);
7078 // Decrement loop variable by UnitSize.
7080 MachineInstrBuilder MIB =
7081 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7082 MIB = AddDefaultT1CC(MIB);
7083 MIB.addReg(varPhi).addImm(UnitSize);
7084 AddDefaultPred(MIB);
7086 MachineInstrBuilder MIB =
7087 BuildMI(*BB, BB->end(), dl,
7088 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7089 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7090 MIB->getOperand(5).setReg(ARM::CPSR);
7091 MIB->getOperand(5).setIsDef(true);
7093 BuildMI(*BB, BB->end(), dl,
7094 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7095 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7097 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7098 BB->addSuccessor(loopMBB);
7099 BB->addSuccessor(exitMBB);
7101 // Add epilogue to handle BytesLeft.
7103 MachineInstr *StartOfExit = exitMBB->begin();
7105 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7106 // [destOut] = STRB_POST(scratch, destLoop, 1)
7107 unsigned srcIn = srcLoop;
7108 unsigned destIn = destLoop;
7109 for (unsigned i = 0; i < BytesLeft; i++) {
7110 unsigned srcOut = MRI.createVirtualRegister(TRC);
7111 unsigned destOut = MRI.createVirtualRegister(TRC);
7112 unsigned scratch = MRI.createVirtualRegister(TRC);
7113 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7114 IsThumb1, IsThumb2);
7115 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7116 IsThumb1, IsThumb2);
7121 MI->eraseFromParent(); // The instruction is gone now.
7126 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7127 MachineBasicBlock *MBB) const {
7128 const TargetMachine &TM = getTargetMachine();
7129 const TargetInstrInfo &TII = *TM.getInstrInfo();
7130 DebugLoc DL = MI->getDebugLoc();
7132 assert(Subtarget->isTargetWindows() &&
7133 "__chkstk is only supported on Windows");
7134 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7136 // __chkstk takes the number of words to allocate on the stack in R4, and
7137 // returns the stack adjustment in number of bytes in R4. This will not
7138 // clober any other registers (other than the obvious lr).
7140 // Although, technically, IP should be considered a register which may be
7141 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7142 // thumb-2 environment, so there is no interworking required. As a result, we
7143 // do not expect a veneer to be emitted by the linker, clobbering IP.
7145 // Each module recieves its own copy of __chkstk, so no import thunk is
7146 // required, again, ensuring that IP is not clobbered.
7148 // Finally, although some linkers may theoretically provide a trampoline for
7149 // out of range calls (which is quite common due to a 32M range limitation of
7150 // branches for Thumb), we can generate the long-call version via
7151 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7154 switch (TM.getCodeModel()) {
7155 case CodeModel::Small:
7156 case CodeModel::Medium:
7157 case CodeModel::Default:
7158 case CodeModel::Kernel:
7159 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7160 .addImm((unsigned)ARMCC::AL).addReg(0)
7161 .addExternalSymbol("__chkstk")
7162 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7163 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7164 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7166 case CodeModel::Large:
7167 case CodeModel::JITDefault: {
7168 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7169 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7171 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7172 .addExternalSymbol("__chkstk");
7173 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7174 .addImm((unsigned)ARMCC::AL).addReg(0)
7175 .addReg(Reg, RegState::Kill)
7176 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7177 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7178 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7183 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7185 .addReg(ARM::SP, RegState::Define)
7186 .addReg(ARM::R4, RegState::Kill)));
7188 MI->eraseFromParent();
7193 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7194 MachineBasicBlock *BB) const {
7195 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7196 DebugLoc dl = MI->getDebugLoc();
7197 bool isThumb2 = Subtarget->isThumb2();
7198 switch (MI->getOpcode()) {
7201 llvm_unreachable("Unexpected instr type to insert");
7203 // The Thumb2 pre-indexed stores have the same MI operands, they just
7204 // define them differently in the .td files from the isel patterns, so
7205 // they need pseudos.
7206 case ARM::t2STR_preidx:
7207 MI->setDesc(TII->get(ARM::t2STR_PRE));
7209 case ARM::t2STRB_preidx:
7210 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7212 case ARM::t2STRH_preidx:
7213 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7216 case ARM::STRi_preidx:
7217 case ARM::STRBi_preidx: {
7218 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7219 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7220 // Decode the offset.
7221 unsigned Offset = MI->getOperand(4).getImm();
7222 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7223 Offset = ARM_AM::getAM2Offset(Offset);
7227 MachineMemOperand *MMO = *MI->memoperands_begin();
7228 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7229 .addOperand(MI->getOperand(0)) // Rn_wb
7230 .addOperand(MI->getOperand(1)) // Rt
7231 .addOperand(MI->getOperand(2)) // Rn
7232 .addImm(Offset) // offset (skip GPR==zero_reg)
7233 .addOperand(MI->getOperand(5)) // pred
7234 .addOperand(MI->getOperand(6))
7235 .addMemOperand(MMO);
7236 MI->eraseFromParent();
7239 case ARM::STRr_preidx:
7240 case ARM::STRBr_preidx:
7241 case ARM::STRH_preidx: {
7243 switch (MI->getOpcode()) {
7244 default: llvm_unreachable("unexpected opcode!");
7245 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7246 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7247 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7249 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7250 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7251 MIB.addOperand(MI->getOperand(i));
7252 MI->eraseFromParent();
7256 case ARM::tMOVCCr_pseudo: {
7257 // To "insert" a SELECT_CC instruction, we actually have to insert the
7258 // diamond control-flow pattern. The incoming instruction knows the
7259 // destination vreg to set, the condition code register to branch on, the
7260 // true/false values to select between, and a branch opcode to use.
7261 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7262 MachineFunction::iterator It = BB;
7268 // cmpTY ccX, r1, r2
7270 // fallthrough --> copy0MBB
7271 MachineBasicBlock *thisMBB = BB;
7272 MachineFunction *F = BB->getParent();
7273 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7274 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7275 F->insert(It, copy0MBB);
7276 F->insert(It, sinkMBB);
7278 // Transfer the remainder of BB and its successor edges to sinkMBB.
7279 sinkMBB->splice(sinkMBB->begin(), BB,
7280 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7281 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7283 BB->addSuccessor(copy0MBB);
7284 BB->addSuccessor(sinkMBB);
7286 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7287 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7290 // %FalseValue = ...
7291 // # fallthrough to sinkMBB
7294 // Update machine-CFG edges
7295 BB->addSuccessor(sinkMBB);
7298 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7301 BuildMI(*BB, BB->begin(), dl,
7302 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7303 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7304 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7306 MI->eraseFromParent(); // The pseudo instruction is gone now.
7311 case ARM::BCCZi64: {
7312 // If there is an unconditional branch to the other successor, remove it.
7313 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7315 // Compare both parts that make up the double comparison separately for
7317 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7319 unsigned LHS1 = MI->getOperand(1).getReg();
7320 unsigned LHS2 = MI->getOperand(2).getReg();
7322 AddDefaultPred(BuildMI(BB, dl,
7323 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7324 .addReg(LHS1).addImm(0));
7325 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7326 .addReg(LHS2).addImm(0)
7327 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7329 unsigned RHS1 = MI->getOperand(3).getReg();
7330 unsigned RHS2 = MI->getOperand(4).getReg();
7331 AddDefaultPred(BuildMI(BB, dl,
7332 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7333 .addReg(LHS1).addReg(RHS1));
7334 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7335 .addReg(LHS2).addReg(RHS2)
7336 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7339 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7340 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7341 if (MI->getOperand(0).getImm() == ARMCC::NE)
7342 std::swap(destMBB, exitMBB);
7344 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7345 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7347 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7349 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7351 MI->eraseFromParent(); // The pseudo instruction is gone now.
7355 case ARM::Int_eh_sjlj_setjmp:
7356 case ARM::Int_eh_sjlj_setjmp_nofp:
7357 case ARM::tInt_eh_sjlj_setjmp:
7358 case ARM::t2Int_eh_sjlj_setjmp:
7359 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7360 EmitSjLjDispatchBlock(MI, BB);
7365 // To insert an ABS instruction, we have to insert the
7366 // diamond control-flow pattern. The incoming instruction knows the
7367 // source vreg to test against 0, the destination vreg to set,
7368 // the condition code register to branch on, the
7369 // true/false values to select between, and a branch opcode to use.
7374 // BCC (branch to SinkBB if V0 >= 0)
7375 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7376 // SinkBB: V1 = PHI(V2, V3)
7377 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7378 MachineFunction::iterator BBI = BB;
7380 MachineFunction *Fn = BB->getParent();
7381 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7382 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7383 Fn->insert(BBI, RSBBB);
7384 Fn->insert(BBI, SinkBB);
7386 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7387 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7388 bool isThumb2 = Subtarget->isThumb2();
7389 MachineRegisterInfo &MRI = Fn->getRegInfo();
7390 // In Thumb mode S must not be specified if source register is the SP or
7391 // PC and if destination register is the SP, so restrict register class
7392 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7393 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7394 (const TargetRegisterClass*)&ARM::GPRRegClass);
7396 // Transfer the remainder of BB and its successor edges to sinkMBB.
7397 SinkBB->splice(SinkBB->begin(), BB,
7398 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7399 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7401 BB->addSuccessor(RSBBB);
7402 BB->addSuccessor(SinkBB);
7404 // fall through to SinkMBB
7405 RSBBB->addSuccessor(SinkBB);
7407 // insert a cmp at the end of BB
7408 AddDefaultPred(BuildMI(BB, dl,
7409 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7410 .addReg(ABSSrcReg).addImm(0));
7412 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7414 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7415 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7417 // insert rsbri in RSBBB
7418 // Note: BCC and rsbri will be converted into predicated rsbmi
7419 // by if-conversion pass
7420 BuildMI(*RSBBB, RSBBB->begin(), dl,
7421 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7422 .addReg(ABSSrcReg, RegState::Kill)
7423 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7425 // insert PHI in SinkBB,
7426 // reuse ABSDstReg to not change uses of ABS instruction
7427 BuildMI(*SinkBB, SinkBB->begin(), dl,
7428 TII->get(ARM::PHI), ABSDstReg)
7429 .addReg(NewRsbDstReg).addMBB(RSBBB)
7430 .addReg(ABSSrcReg).addMBB(BB);
7432 // remove ABS instruction
7433 MI->eraseFromParent();
7435 // return last added BB
7438 case ARM::COPY_STRUCT_BYVAL_I32:
7440 return EmitStructByval(MI, BB);
7441 case ARM::WIN__CHKSTK:
7442 return EmitLowered__chkstk(MI, BB);
7446 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7447 SDNode *Node) const {
7448 if (!MI->hasPostISelHook()) {
7449 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7450 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7454 const MCInstrDesc *MCID = &MI->getDesc();
7455 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7456 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7457 // operand is still set to noreg. If needed, set the optional operand's
7458 // register to CPSR, and remove the redundant implicit def.
7460 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7462 // Rename pseudo opcodes.
7463 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7465 const ARMBaseInstrInfo *TII =
7466 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7467 MCID = &TII->get(NewOpc);
7469 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7470 "converted opcode should be the same except for cc_out");
7474 // Add the optional cc_out operand
7475 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7477 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7479 // Any ARM instruction that sets the 's' bit should specify an optional
7480 // "cc_out" operand in the last operand position.
7481 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7482 assert(!NewOpc && "Optional cc_out operand required");
7485 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7486 // since we already have an optional CPSR def.
7487 bool definesCPSR = false;
7488 bool deadCPSR = false;
7489 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7491 const MachineOperand &MO = MI->getOperand(i);
7492 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7496 MI->RemoveOperand(i);
7501 assert(!NewOpc && "Optional cc_out operand required");
7504 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7506 assert(!MI->getOperand(ccOutIdx).getReg() &&
7507 "expect uninitialized optional cc_out operand");
7511 // If this instruction was defined with an optional CPSR def and its dag node
7512 // had a live implicit CPSR def, then activate the optional CPSR def.
7513 MachineOperand &MO = MI->getOperand(ccOutIdx);
7514 MO.setReg(ARM::CPSR);
7518 //===----------------------------------------------------------------------===//
7519 // ARM Optimization Hooks
7520 //===----------------------------------------------------------------------===//
7522 // Helper function that checks if N is a null or all ones constant.
7523 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7524 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7527 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7530 // Return true if N is conditionally 0 or all ones.
7531 // Detects these expressions where cc is an i1 value:
7533 // (select cc 0, y) [AllOnes=0]
7534 // (select cc y, 0) [AllOnes=0]
7535 // (zext cc) [AllOnes=0]
7536 // (sext cc) [AllOnes=0/1]
7537 // (select cc -1, y) [AllOnes=1]
7538 // (select cc y, -1) [AllOnes=1]
7540 // Invert is set when N is the null/all ones constant when CC is false.
7541 // OtherOp is set to the alternative value of N.
7542 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7543 SDValue &CC, bool &Invert,
7545 SelectionDAG &DAG) {
7546 switch (N->getOpcode()) {
7547 default: return false;
7549 CC = N->getOperand(0);
7550 SDValue N1 = N->getOperand(1);
7551 SDValue N2 = N->getOperand(2);
7552 if (isZeroOrAllOnes(N1, AllOnes)) {
7557 if (isZeroOrAllOnes(N2, AllOnes)) {
7564 case ISD::ZERO_EXTEND:
7565 // (zext cc) can never be the all ones value.
7569 case ISD::SIGN_EXTEND: {
7570 EVT VT = N->getValueType(0);
7571 CC = N->getOperand(0);
7572 if (CC.getValueType() != MVT::i1)
7576 // When looking for an AllOnes constant, N is an sext, and the 'other'
7578 OtherOp = DAG.getConstant(0, VT);
7579 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7580 // When looking for a 0 constant, N can be zext or sext.
7581 OtherOp = DAG.getConstant(1, VT);
7583 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7589 // Combine a constant select operand into its use:
7591 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7592 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7593 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7594 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7595 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7597 // The transform is rejected if the select doesn't have a constant operand that
7598 // is null, or all ones when AllOnes is set.
7600 // Also recognize sext/zext from i1:
7602 // (add (zext cc), x) -> (select cc (add x, 1), x)
7603 // (add (sext cc), x) -> (select cc (add x, -1), x)
7605 // These transformations eventually create predicated instructions.
7607 // @param N The node to transform.
7608 // @param Slct The N operand that is a select.
7609 // @param OtherOp The other N operand (x above).
7610 // @param DCI Context.
7611 // @param AllOnes Require the select constant to be all ones instead of null.
7612 // @returns The new node, or SDValue() on failure.
7614 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7615 TargetLowering::DAGCombinerInfo &DCI,
7616 bool AllOnes = false) {
7617 SelectionDAG &DAG = DCI.DAG;
7618 EVT VT = N->getValueType(0);
7619 SDValue NonConstantVal;
7622 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7623 NonConstantVal, DAG))
7626 // Slct is now know to be the desired identity constant when CC is true.
7627 SDValue TrueVal = OtherOp;
7628 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7629 OtherOp, NonConstantVal);
7630 // Unless SwapSelectOps says CC should be false.
7632 std::swap(TrueVal, FalseVal);
7634 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7635 CCOp, TrueVal, FalseVal);
7638 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7640 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7641 TargetLowering::DAGCombinerInfo &DCI) {
7642 SDValue N0 = N->getOperand(0);
7643 SDValue N1 = N->getOperand(1);
7644 if (N0.getNode()->hasOneUse()) {
7645 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7646 if (Result.getNode())
7649 if (N1.getNode()->hasOneUse()) {
7650 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7651 if (Result.getNode())
7657 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7658 // (only after legalization).
7659 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7660 TargetLowering::DAGCombinerInfo &DCI,
7661 const ARMSubtarget *Subtarget) {
7663 // Only perform optimization if after legalize, and if NEON is available. We
7664 // also expected both operands to be BUILD_VECTORs.
7665 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7666 || N0.getOpcode() != ISD::BUILD_VECTOR
7667 || N1.getOpcode() != ISD::BUILD_VECTOR)
7670 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7671 EVT VT = N->getValueType(0);
7672 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7675 // Check that the vector operands are of the right form.
7676 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7677 // operands, where N is the size of the formed vector.
7678 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7679 // index such that we have a pair wise add pattern.
7681 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7682 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7684 SDValue Vec = N0->getOperand(0)->getOperand(0);
7685 SDNode *V = Vec.getNode();
7686 unsigned nextIndex = 0;
7688 // For each operands to the ADD which are BUILD_VECTORs,
7689 // check to see if each of their operands are an EXTRACT_VECTOR with
7690 // the same vector and appropriate index.
7691 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7692 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7693 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7695 SDValue ExtVec0 = N0->getOperand(i);
7696 SDValue ExtVec1 = N1->getOperand(i);
7698 // First operand is the vector, verify its the same.
7699 if (V != ExtVec0->getOperand(0).getNode() ||
7700 V != ExtVec1->getOperand(0).getNode())
7703 // Second is the constant, verify its correct.
7704 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7705 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7707 // For the constant, we want to see all the even or all the odd.
7708 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7709 || C1->getZExtValue() != nextIndex+1)
7718 // Create VPADDL node.
7719 SelectionDAG &DAG = DCI.DAG;
7720 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7722 // Build operand list.
7723 SmallVector<SDValue, 8> Ops;
7724 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7725 TLI.getPointerTy()));
7727 // Input is the vector.
7730 // Get widened type and narrowed type.
7732 unsigned numElem = VT.getVectorNumElements();
7734 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7735 switch (inputLaneType.getSimpleVT().SimpleTy) {
7736 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7737 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7738 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7740 llvm_unreachable("Invalid vector element type for padd optimization.");
7743 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7744 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7745 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7748 static SDValue findMUL_LOHI(SDValue V) {
7749 if (V->getOpcode() == ISD::UMUL_LOHI ||
7750 V->getOpcode() == ISD::SMUL_LOHI)
7755 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7756 TargetLowering::DAGCombinerInfo &DCI,
7757 const ARMSubtarget *Subtarget) {
7759 if (Subtarget->isThumb1Only()) return SDValue();
7761 // Only perform the checks after legalize when the pattern is available.
7762 if (DCI.isBeforeLegalize()) return SDValue();
7764 // Look for multiply add opportunities.
7765 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7766 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7767 // a glue link from the first add to the second add.
7768 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7769 // a S/UMLAL instruction.
7772 // \ / \ [no multiline comment]
7778 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7779 SDValue AddcOp0 = AddcNode->getOperand(0);
7780 SDValue AddcOp1 = AddcNode->getOperand(1);
7782 // Check if the two operands are from the same mul_lohi node.
7783 if (AddcOp0.getNode() == AddcOp1.getNode())
7786 assert(AddcNode->getNumValues() == 2 &&
7787 AddcNode->getValueType(0) == MVT::i32 &&
7788 "Expect ADDC with two result values. First: i32");
7790 // Check that we have a glued ADDC node.
7791 if (AddcNode->getValueType(1) != MVT::Glue)
7794 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7795 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7796 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7797 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7798 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7801 // Look for the glued ADDE.
7802 SDNode* AddeNode = AddcNode->getGluedUser();
7806 // Make sure it is really an ADDE.
7807 if (AddeNode->getOpcode() != ISD::ADDE)
7810 assert(AddeNode->getNumOperands() == 3 &&
7811 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7812 "ADDE node has the wrong inputs");
7814 // Check for the triangle shape.
7815 SDValue AddeOp0 = AddeNode->getOperand(0);
7816 SDValue AddeOp1 = AddeNode->getOperand(1);
7818 // Make sure that the ADDE operands are not coming from the same node.
7819 if (AddeOp0.getNode() == AddeOp1.getNode())
7822 // Find the MUL_LOHI node walking up ADDE's operands.
7823 bool IsLeftOperandMUL = false;
7824 SDValue MULOp = findMUL_LOHI(AddeOp0);
7825 if (MULOp == SDValue())
7826 MULOp = findMUL_LOHI(AddeOp1);
7828 IsLeftOperandMUL = true;
7829 if (MULOp == SDValue())
7832 // Figure out the right opcode.
7833 unsigned Opc = MULOp->getOpcode();
7834 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7836 // Figure out the high and low input values to the MLAL node.
7837 SDValue* HiMul = &MULOp;
7838 SDValue* HiAdd = nullptr;
7839 SDValue* LoMul = nullptr;
7840 SDValue* LowAdd = nullptr;
7842 if (IsLeftOperandMUL)
7848 if (AddcOp0->getOpcode() == Opc) {
7852 if (AddcOp1->getOpcode() == Opc) {
7860 if (LoMul->getNode() != HiMul->getNode())
7863 // Create the merged node.
7864 SelectionDAG &DAG = DCI.DAG;
7866 // Build operand list.
7867 SmallVector<SDValue, 8> Ops;
7868 Ops.push_back(LoMul->getOperand(0));
7869 Ops.push_back(LoMul->getOperand(1));
7870 Ops.push_back(*LowAdd);
7871 Ops.push_back(*HiAdd);
7873 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7874 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7876 // Replace the ADDs' nodes uses by the MLA node's values.
7877 SDValue HiMLALResult(MLALNode.getNode(), 1);
7878 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7880 SDValue LoMLALResult(MLALNode.getNode(), 0);
7881 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7883 // Return original node to notify the driver to stop replacing.
7884 SDValue resNode(AddcNode, 0);
7888 /// PerformADDCCombine - Target-specific dag combine transform from
7889 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7890 static SDValue PerformADDCCombine(SDNode *N,
7891 TargetLowering::DAGCombinerInfo &DCI,
7892 const ARMSubtarget *Subtarget) {
7894 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7898 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7899 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7900 /// called with the default operands, and if that fails, with commuted
7902 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7903 TargetLowering::DAGCombinerInfo &DCI,
7904 const ARMSubtarget *Subtarget){
7906 // Attempt to create vpaddl for this add.
7907 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7908 if (Result.getNode())
7911 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7912 if (N0.getNode()->hasOneUse()) {
7913 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7914 if (Result.getNode()) return Result;
7919 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7921 static SDValue PerformADDCombine(SDNode *N,
7922 TargetLowering::DAGCombinerInfo &DCI,
7923 const ARMSubtarget *Subtarget) {
7924 SDValue N0 = N->getOperand(0);
7925 SDValue N1 = N->getOperand(1);
7927 // First try with the default operand order.
7928 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7929 if (Result.getNode())
7932 // If that didn't work, try again with the operands commuted.
7933 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7936 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7938 static SDValue PerformSUBCombine(SDNode *N,
7939 TargetLowering::DAGCombinerInfo &DCI) {
7940 SDValue N0 = N->getOperand(0);
7941 SDValue N1 = N->getOperand(1);
7943 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7944 if (N1.getNode()->hasOneUse()) {
7945 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7946 if (Result.getNode()) return Result;
7952 /// PerformVMULCombine
7953 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7954 /// special multiplier accumulator forwarding.
7960 // However, for (A + B) * (A + B),
7967 static SDValue PerformVMULCombine(SDNode *N,
7968 TargetLowering::DAGCombinerInfo &DCI,
7969 const ARMSubtarget *Subtarget) {
7970 if (!Subtarget->hasVMLxForwarding())
7973 SelectionDAG &DAG = DCI.DAG;
7974 SDValue N0 = N->getOperand(0);
7975 SDValue N1 = N->getOperand(1);
7976 unsigned Opcode = N0.getOpcode();
7977 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7978 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7979 Opcode = N1.getOpcode();
7980 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7981 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7989 EVT VT = N->getValueType(0);
7991 SDValue N00 = N0->getOperand(0);
7992 SDValue N01 = N0->getOperand(1);
7993 return DAG.getNode(Opcode, DL, VT,
7994 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7995 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7998 static SDValue PerformMULCombine(SDNode *N,
7999 TargetLowering::DAGCombinerInfo &DCI,
8000 const ARMSubtarget *Subtarget) {
8001 SelectionDAG &DAG = DCI.DAG;
8003 if (Subtarget->isThumb1Only())
8006 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8009 EVT VT = N->getValueType(0);
8010 if (VT.is64BitVector() || VT.is128BitVector())
8011 return PerformVMULCombine(N, DCI, Subtarget);
8015 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8019 int64_t MulAmt = C->getSExtValue();
8020 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8022 ShiftAmt = ShiftAmt & (32 - 1);
8023 SDValue V = N->getOperand(0);
8027 MulAmt >>= ShiftAmt;
8030 if (isPowerOf2_32(MulAmt - 1)) {
8031 // (mul x, 2^N + 1) => (add (shl x, N), x)
8032 Res = DAG.getNode(ISD::ADD, DL, VT,
8034 DAG.getNode(ISD::SHL, DL, VT,
8036 DAG.getConstant(Log2_32(MulAmt - 1),
8038 } else if (isPowerOf2_32(MulAmt + 1)) {
8039 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8040 Res = DAG.getNode(ISD::SUB, DL, VT,
8041 DAG.getNode(ISD::SHL, DL, VT,
8043 DAG.getConstant(Log2_32(MulAmt + 1),
8049 uint64_t MulAmtAbs = -MulAmt;
8050 if (isPowerOf2_32(MulAmtAbs + 1)) {
8051 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8052 Res = DAG.getNode(ISD::SUB, DL, VT,
8054 DAG.getNode(ISD::SHL, DL, VT,
8056 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8058 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8059 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8060 Res = DAG.getNode(ISD::ADD, DL, VT,
8062 DAG.getNode(ISD::SHL, DL, VT,
8064 DAG.getConstant(Log2_32(MulAmtAbs-1),
8066 Res = DAG.getNode(ISD::SUB, DL, VT,
8067 DAG.getConstant(0, MVT::i32),Res);
8074 Res = DAG.getNode(ISD::SHL, DL, VT,
8075 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8077 // Do not add new nodes to DAG combiner worklist.
8078 DCI.CombineTo(N, Res, false);
8082 static SDValue PerformANDCombine(SDNode *N,
8083 TargetLowering::DAGCombinerInfo &DCI,
8084 const ARMSubtarget *Subtarget) {
8086 // Attempt to use immediate-form VBIC
8087 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8089 EVT VT = N->getValueType(0);
8090 SelectionDAG &DAG = DCI.DAG;
8092 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8095 APInt SplatBits, SplatUndef;
8096 unsigned SplatBitSize;
8099 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8100 if (SplatBitSize <= 64) {
8102 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8103 SplatUndef.getZExtValue(), SplatBitSize,
8104 DAG, VbicVT, VT.is128BitVector(),
8106 if (Val.getNode()) {
8108 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8109 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8110 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8115 if (!Subtarget->isThumb1Only()) {
8116 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8117 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8118 if (Result.getNode())
8125 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8126 static SDValue PerformORCombine(SDNode *N,
8127 TargetLowering::DAGCombinerInfo &DCI,
8128 const ARMSubtarget *Subtarget) {
8129 // Attempt to use immediate-form VORR
8130 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8132 EVT VT = N->getValueType(0);
8133 SelectionDAG &DAG = DCI.DAG;
8135 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8138 APInt SplatBits, SplatUndef;
8139 unsigned SplatBitSize;
8141 if (BVN && Subtarget->hasNEON() &&
8142 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8143 if (SplatBitSize <= 64) {
8145 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8146 SplatUndef.getZExtValue(), SplatBitSize,
8147 DAG, VorrVT, VT.is128BitVector(),
8149 if (Val.getNode()) {
8151 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8152 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8153 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8158 if (!Subtarget->isThumb1Only()) {
8159 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8160 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8161 if (Result.getNode())
8165 // The code below optimizes (or (and X, Y), Z).
8166 // The AND operand needs to have a single user to make these optimizations
8168 SDValue N0 = N->getOperand(0);
8169 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8171 SDValue N1 = N->getOperand(1);
8173 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8174 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8175 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8177 unsigned SplatBitSize;
8180 APInt SplatBits0, SplatBits1;
8181 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8182 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8183 // Ensure that the second operand of both ands are constants
8184 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8185 HasAnyUndefs) && !HasAnyUndefs) {
8186 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8187 HasAnyUndefs) && !HasAnyUndefs) {
8188 // Ensure that the bit width of the constants are the same and that
8189 // the splat arguments are logical inverses as per the pattern we
8190 // are trying to simplify.
8191 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8192 SplatBits0 == ~SplatBits1) {
8193 // Canonicalize the vector type to make instruction selection
8195 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8196 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8200 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8206 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8209 // BFI is only available on V6T2+
8210 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8214 // 1) or (and A, mask), val => ARMbfi A, val, mask
8215 // iff (val & mask) == val
8217 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8218 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8219 // && mask == ~mask2
8220 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8221 // && ~mask == mask2
8222 // (i.e., copy a bitfield value into another bitfield of the same width)
8227 SDValue N00 = N0.getOperand(0);
8229 // The value and the mask need to be constants so we can verify this is
8230 // actually a bitfield set. If the mask is 0xffff, we can do better
8231 // via a movt instruction, so don't use BFI in that case.
8232 SDValue MaskOp = N0.getOperand(1);
8233 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8236 unsigned Mask = MaskC->getZExtValue();
8240 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8241 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8243 unsigned Val = N1C->getZExtValue();
8244 if ((Val & ~Mask) != Val)
8247 if (ARM::isBitFieldInvertedMask(Mask)) {
8248 Val >>= countTrailingZeros(~Mask);
8250 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8251 DAG.getConstant(Val, MVT::i32),
8252 DAG.getConstant(Mask, MVT::i32));
8254 // Do not add new nodes to DAG combiner worklist.
8255 DCI.CombineTo(N, Res, false);
8258 } else if (N1.getOpcode() == ISD::AND) {
8259 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8260 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8263 unsigned Mask2 = N11C->getZExtValue();
8265 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8267 if (ARM::isBitFieldInvertedMask(Mask) &&
8269 // The pack halfword instruction works better for masks that fit it,
8270 // so use that when it's available.
8271 if (Subtarget->hasT2ExtractPack() &&
8272 (Mask == 0xffff || Mask == 0xffff0000))
8275 unsigned amt = countTrailingZeros(Mask2);
8276 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8277 DAG.getConstant(amt, MVT::i32));
8278 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8279 DAG.getConstant(Mask, MVT::i32));
8280 // Do not add new nodes to DAG combiner worklist.
8281 DCI.CombineTo(N, Res, false);
8283 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8285 // The pack halfword instruction works better for masks that fit it,
8286 // so use that when it's available.
8287 if (Subtarget->hasT2ExtractPack() &&
8288 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8291 unsigned lsb = countTrailingZeros(Mask);
8292 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8293 DAG.getConstant(lsb, MVT::i32));
8294 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8295 DAG.getConstant(Mask2, MVT::i32));
8296 // Do not add new nodes to DAG combiner worklist.
8297 DCI.CombineTo(N, Res, false);
8302 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8303 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8304 ARM::isBitFieldInvertedMask(~Mask)) {
8305 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8306 // where lsb(mask) == #shamt and masked bits of B are known zero.
8307 SDValue ShAmt = N00.getOperand(1);
8308 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8309 unsigned LSB = countTrailingZeros(Mask);
8313 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8314 DAG.getConstant(~Mask, MVT::i32));
8316 // Do not add new nodes to DAG combiner worklist.
8317 DCI.CombineTo(N, Res, false);
8323 static SDValue PerformXORCombine(SDNode *N,
8324 TargetLowering::DAGCombinerInfo &DCI,
8325 const ARMSubtarget *Subtarget) {
8326 EVT VT = N->getValueType(0);
8327 SelectionDAG &DAG = DCI.DAG;
8329 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8332 if (!Subtarget->isThumb1Only()) {
8333 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8334 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8335 if (Result.getNode())
8342 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8343 /// the bits being cleared by the AND are not demanded by the BFI.
8344 static SDValue PerformBFICombine(SDNode *N,
8345 TargetLowering::DAGCombinerInfo &DCI) {
8346 SDValue N1 = N->getOperand(1);
8347 if (N1.getOpcode() == ISD::AND) {
8348 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8351 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8352 unsigned LSB = countTrailingZeros(~InvMask);
8353 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8354 unsigned Mask = (1 << Width)-1;
8355 unsigned Mask2 = N11C->getZExtValue();
8356 if ((Mask & (~Mask2)) == 0)
8357 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8358 N->getOperand(0), N1.getOperand(0),
8364 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8365 /// ARMISD::VMOVRRD.
8366 static SDValue PerformVMOVRRDCombine(SDNode *N,
8367 TargetLowering::DAGCombinerInfo &DCI) {
8368 // vmovrrd(vmovdrr x, y) -> x,y
8369 SDValue InDouble = N->getOperand(0);
8370 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8371 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8373 // vmovrrd(load f64) -> (load i32), (load i32)
8374 SDNode *InNode = InDouble.getNode();
8375 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8376 InNode->getValueType(0) == MVT::f64 &&
8377 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8378 !cast<LoadSDNode>(InNode)->isVolatile()) {
8379 // TODO: Should this be done for non-FrameIndex operands?
8380 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8382 SelectionDAG &DAG = DCI.DAG;
8384 SDValue BasePtr = LD->getBasePtr();
8385 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8386 LD->getPointerInfo(), LD->isVolatile(),
8387 LD->isNonTemporal(), LD->isInvariant(),
8388 LD->getAlignment());
8390 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8391 DAG.getConstant(4, MVT::i32));
8392 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8393 LD->getPointerInfo(), LD->isVolatile(),
8394 LD->isNonTemporal(), LD->isInvariant(),
8395 std::min(4U, LD->getAlignment() / 2));
8397 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8398 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8399 std::swap (NewLD1, NewLD2);
8400 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8401 DCI.RemoveFromWorklist(LD);
8409 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8410 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8411 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8412 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8413 SDValue Op0 = N->getOperand(0);
8414 SDValue Op1 = N->getOperand(1);
8415 if (Op0.getOpcode() == ISD::BITCAST)
8416 Op0 = Op0.getOperand(0);
8417 if (Op1.getOpcode() == ISD::BITCAST)
8418 Op1 = Op1.getOperand(0);
8419 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8420 Op0.getNode() == Op1.getNode() &&
8421 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8422 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8423 N->getValueType(0), Op0.getOperand(0));
8427 /// PerformSTORECombine - Target-specific dag combine xforms for
8429 static SDValue PerformSTORECombine(SDNode *N,
8430 TargetLowering::DAGCombinerInfo &DCI) {
8431 StoreSDNode *St = cast<StoreSDNode>(N);
8432 if (St->isVolatile())
8435 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8436 // pack all of the elements in one place. Next, store to memory in fewer
8438 SDValue StVal = St->getValue();
8439 EVT VT = StVal.getValueType();
8440 if (St->isTruncatingStore() && VT.isVector()) {
8441 SelectionDAG &DAG = DCI.DAG;
8442 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8443 EVT StVT = St->getMemoryVT();
8444 unsigned NumElems = VT.getVectorNumElements();
8445 assert(StVT != VT && "Cannot truncate to the same type");
8446 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8447 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8449 // From, To sizes and ElemCount must be pow of two
8450 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8452 // We are going to use the original vector elt for storing.
8453 // Accumulated smaller vector elements must be a multiple of the store size.
8454 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8456 unsigned SizeRatio = FromEltSz / ToEltSz;
8457 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8459 // Create a type on which we perform the shuffle.
8460 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8461 NumElems*SizeRatio);
8462 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8465 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8466 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8467 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8469 // Can't shuffle using an illegal type.
8470 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8472 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8473 DAG.getUNDEF(WideVec.getValueType()),
8475 // At this point all of the data is stored at the bottom of the
8476 // register. We now need to save it to mem.
8478 // Find the largest store unit
8479 MVT StoreType = MVT::i8;
8480 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8481 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8482 MVT Tp = (MVT::SimpleValueType)tp;
8483 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8486 // Didn't find a legal store type.
8487 if (!TLI.isTypeLegal(StoreType))
8490 // Bitcast the original vector into a vector of store-size units
8491 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8492 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8493 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8494 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8495 SmallVector<SDValue, 8> Chains;
8496 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8497 TLI.getPointerTy());
8498 SDValue BasePtr = St->getBasePtr();
8500 // Perform one or more big stores into memory.
8501 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8502 for (unsigned I = 0; I < E; I++) {
8503 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8504 StoreType, ShuffWide,
8505 DAG.getIntPtrConstant(I));
8506 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8507 St->getPointerInfo(), St->isVolatile(),
8508 St->isNonTemporal(), St->getAlignment());
8509 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8511 Chains.push_back(Ch);
8513 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8516 if (!ISD::isNormalStore(St))
8519 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8520 // ARM stores of arguments in the same cache line.
8521 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8522 StVal.getNode()->hasOneUse()) {
8523 SelectionDAG &DAG = DCI.DAG;
8524 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8526 SDValue BasePtr = St->getBasePtr();
8527 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8528 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8529 BasePtr, St->getPointerInfo(), St->isVolatile(),
8530 St->isNonTemporal(), St->getAlignment());
8532 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8533 DAG.getConstant(4, MVT::i32));
8534 return DAG.getStore(NewST1.getValue(0), DL,
8535 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8536 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8537 St->isNonTemporal(),
8538 std::min(4U, St->getAlignment() / 2));
8541 if (StVal.getValueType() != MVT::i64 ||
8542 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8545 // Bitcast an i64 store extracted from a vector to f64.
8546 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8547 SelectionDAG &DAG = DCI.DAG;
8549 SDValue IntVec = StVal.getOperand(0);
8550 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8551 IntVec.getValueType().getVectorNumElements());
8552 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8553 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8554 Vec, StVal.getOperand(1));
8556 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8557 // Make the DAGCombiner fold the bitcasts.
8558 DCI.AddToWorklist(Vec.getNode());
8559 DCI.AddToWorklist(ExtElt.getNode());
8560 DCI.AddToWorklist(V.getNode());
8561 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8562 St->getPointerInfo(), St->isVolatile(),
8563 St->isNonTemporal(), St->getAlignment(),
8567 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8568 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8569 /// i64 vector to have f64 elements, since the value can then be loaded
8570 /// directly into a VFP register.
8571 static bool hasNormalLoadOperand(SDNode *N) {
8572 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8573 for (unsigned i = 0; i < NumElts; ++i) {
8574 SDNode *Elt = N->getOperand(i).getNode();
8575 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8581 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8582 /// ISD::BUILD_VECTOR.
8583 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8584 TargetLowering::DAGCombinerInfo &DCI){
8585 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8586 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8587 // into a pair of GPRs, which is fine when the value is used as a scalar,
8588 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8589 SelectionDAG &DAG = DCI.DAG;
8590 if (N->getNumOperands() == 2) {
8591 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8596 // Load i64 elements as f64 values so that type legalization does not split
8597 // them up into i32 values.
8598 EVT VT = N->getValueType(0);
8599 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8602 SmallVector<SDValue, 8> Ops;
8603 unsigned NumElts = VT.getVectorNumElements();
8604 for (unsigned i = 0; i < NumElts; ++i) {
8605 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8607 // Make the DAGCombiner fold the bitcast.
8608 DCI.AddToWorklist(V.getNode());
8610 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8611 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8612 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8615 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8617 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8618 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8619 // At that time, we may have inserted bitcasts from integer to float.
8620 // If these bitcasts have survived DAGCombine, change the lowering of this
8621 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8622 // force to use floating point types.
8624 // Make sure we can change the type of the vector.
8625 // This is possible iff:
8626 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8627 // 1.1. Vector is used only once.
8628 // 1.2. Use is a bit convert to an integer type.
8629 // 2. The size of its operands are 32-bits (64-bits are not legal).
8630 EVT VT = N->getValueType(0);
8631 EVT EltVT = VT.getVectorElementType();
8633 // Check 1.1. and 2.
8634 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8637 // By construction, the input type must be float.
8638 assert(EltVT == MVT::f32 && "Unexpected type!");
8641 SDNode *Use = *N->use_begin();
8642 if (Use->getOpcode() != ISD::BITCAST ||
8643 Use->getValueType(0).isFloatingPoint())
8646 // Check profitability.
8647 // Model is, if more than half of the relevant operands are bitcast from
8648 // i32, turn the build_vector into a sequence of insert_vector_elt.
8649 // Relevant operands are everything that is not statically
8650 // (i.e., at compile time) bitcasted.
8651 unsigned NumOfBitCastedElts = 0;
8652 unsigned NumElts = VT.getVectorNumElements();
8653 unsigned NumOfRelevantElts = NumElts;
8654 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8655 SDValue Elt = N->getOperand(Idx);
8656 if (Elt->getOpcode() == ISD::BITCAST) {
8657 // Assume only bit cast to i32 will go away.
8658 if (Elt->getOperand(0).getValueType() == MVT::i32)
8659 ++NumOfBitCastedElts;
8660 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8661 // Constants are statically casted, thus do not count them as
8662 // relevant operands.
8663 --NumOfRelevantElts;
8666 // Check if more than half of the elements require a non-free bitcast.
8667 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8670 SelectionDAG &DAG = DCI.DAG;
8671 // Create the new vector type.
8672 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8673 // Check if the type is legal.
8674 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8675 if (!TLI.isTypeLegal(VecVT))
8679 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8680 // => BITCAST INSERT_VECTOR_ELT
8681 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8683 SDValue Vec = DAG.getUNDEF(VecVT);
8685 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8686 SDValue V = N->getOperand(Idx);
8687 if (V.getOpcode() == ISD::UNDEF)
8689 if (V.getOpcode() == ISD::BITCAST &&
8690 V->getOperand(0).getValueType() == MVT::i32)
8691 // Fold obvious case.
8692 V = V.getOperand(0);
8694 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8695 // Make the DAGCombiner fold the bitcasts.
8696 DCI.AddToWorklist(V.getNode());
8698 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8699 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8701 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8702 // Make the DAGCombiner fold the bitcasts.
8703 DCI.AddToWorklist(Vec.getNode());
8707 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8708 /// ISD::INSERT_VECTOR_ELT.
8709 static SDValue PerformInsertEltCombine(SDNode *N,
8710 TargetLowering::DAGCombinerInfo &DCI) {
8711 // Bitcast an i64 load inserted into a vector to f64.
8712 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8713 EVT VT = N->getValueType(0);
8714 SDNode *Elt = N->getOperand(1).getNode();
8715 if (VT.getVectorElementType() != MVT::i64 ||
8716 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8719 SelectionDAG &DAG = DCI.DAG;
8721 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8722 VT.getVectorNumElements());
8723 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8724 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8725 // Make the DAGCombiner fold the bitcasts.
8726 DCI.AddToWorklist(Vec.getNode());
8727 DCI.AddToWorklist(V.getNode());
8728 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8729 Vec, V, N->getOperand(2));
8730 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8733 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8734 /// ISD::VECTOR_SHUFFLE.
8735 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8736 // The LLVM shufflevector instruction does not require the shuffle mask
8737 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8738 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8739 // operands do not match the mask length, they are extended by concatenating
8740 // them with undef vectors. That is probably the right thing for other
8741 // targets, but for NEON it is better to concatenate two double-register
8742 // size vector operands into a single quad-register size vector. Do that
8743 // transformation here:
8744 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8745 // shuffle(concat(v1, v2), undef)
8746 SDValue Op0 = N->getOperand(0);
8747 SDValue Op1 = N->getOperand(1);
8748 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8749 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8750 Op0.getNumOperands() != 2 ||
8751 Op1.getNumOperands() != 2)
8753 SDValue Concat0Op1 = Op0.getOperand(1);
8754 SDValue Concat1Op1 = Op1.getOperand(1);
8755 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8756 Concat1Op1.getOpcode() != ISD::UNDEF)
8758 // Skip the transformation if any of the types are illegal.
8759 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8760 EVT VT = N->getValueType(0);
8761 if (!TLI.isTypeLegal(VT) ||
8762 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8763 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8766 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8767 Op0.getOperand(0), Op1.getOperand(0));
8768 // Translate the shuffle mask.
8769 SmallVector<int, 16> NewMask;
8770 unsigned NumElts = VT.getVectorNumElements();
8771 unsigned HalfElts = NumElts/2;
8772 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8773 for (unsigned n = 0; n < NumElts; ++n) {
8774 int MaskElt = SVN->getMaskElt(n);
8776 if (MaskElt < (int)HalfElts)
8778 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8779 NewElt = HalfElts + MaskElt - NumElts;
8780 NewMask.push_back(NewElt);
8782 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8783 DAG.getUNDEF(VT), NewMask.data());
8786 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8787 /// NEON load/store intrinsics to merge base address updates.
8788 static SDValue CombineBaseUpdate(SDNode *N,
8789 TargetLowering::DAGCombinerInfo &DCI) {
8790 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8793 SelectionDAG &DAG = DCI.DAG;
8794 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8795 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8796 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8797 SDValue Addr = N->getOperand(AddrOpIdx);
8799 // Search for a use of the address operand that is an increment.
8800 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8801 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8803 if (User->getOpcode() != ISD::ADD ||
8804 UI.getUse().getResNo() != Addr.getResNo())
8807 // Check that the add is independent of the load/store. Otherwise, folding
8808 // it would create a cycle.
8809 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8812 // Find the new opcode for the updating load/store.
8814 bool isLaneOp = false;
8815 unsigned NewOpc = 0;
8816 unsigned NumVecs = 0;
8818 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8820 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8821 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8823 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8825 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8827 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8829 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8830 NumVecs = 2; isLaneOp = true; break;
8831 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8832 NumVecs = 3; isLaneOp = true; break;
8833 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8834 NumVecs = 4; isLaneOp = true; break;
8835 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8836 NumVecs = 1; isLoad = false; break;
8837 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8838 NumVecs = 2; isLoad = false; break;
8839 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8840 NumVecs = 3; isLoad = false; break;
8841 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8842 NumVecs = 4; isLoad = false; break;
8843 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8844 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8845 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8846 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8847 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8848 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8852 switch (N->getOpcode()) {
8853 default: llvm_unreachable("unexpected opcode for Neon base update");
8854 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8855 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8856 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8860 // Find the size of memory referenced by the load/store.
8863 VecTy = N->getValueType(0);
8865 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8866 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8868 NumBytes /= VecTy.getVectorNumElements();
8870 // If the increment is a constant, it must match the memory ref size.
8871 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8872 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8873 uint64_t IncVal = CInc->getZExtValue();
8874 if (IncVal != NumBytes)
8876 } else if (NumBytes >= 3 * 16) {
8877 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8878 // separate instructions that make it harder to use a non-constant update.
8882 // Create the new updating load/store node.
8884 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8886 for (n = 0; n < NumResultVecs; ++n)
8888 Tys[n++] = MVT::i32;
8889 Tys[n] = MVT::Other;
8890 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8891 SmallVector<SDValue, 8> Ops;
8892 Ops.push_back(N->getOperand(0)); // incoming chain
8893 Ops.push_back(N->getOperand(AddrOpIdx));
8895 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8896 Ops.push_back(N->getOperand(i));
8898 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8899 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8900 Ops, MemInt->getMemoryVT(),
8901 MemInt->getMemOperand());
8904 std::vector<SDValue> NewResults;
8905 for (unsigned i = 0; i < NumResultVecs; ++i) {
8906 NewResults.push_back(SDValue(UpdN.getNode(), i));
8908 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8909 DCI.CombineTo(N, NewResults);
8910 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8917 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8918 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8919 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8921 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8922 SelectionDAG &DAG = DCI.DAG;
8923 EVT VT = N->getValueType(0);
8924 // vldN-dup instructions only support 64-bit vectors for N > 1.
8925 if (!VT.is64BitVector())
8928 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8929 SDNode *VLD = N->getOperand(0).getNode();
8930 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8932 unsigned NumVecs = 0;
8933 unsigned NewOpc = 0;
8934 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8935 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8937 NewOpc = ARMISD::VLD2DUP;
8938 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8940 NewOpc = ARMISD::VLD3DUP;
8941 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8943 NewOpc = ARMISD::VLD4DUP;
8948 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8949 // numbers match the load.
8950 unsigned VLDLaneNo =
8951 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8952 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8954 // Ignore uses of the chain result.
8955 if (UI.getUse().getResNo() == NumVecs)
8958 if (User->getOpcode() != ARMISD::VDUPLANE ||
8959 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8963 // Create the vldN-dup node.
8966 for (n = 0; n < NumVecs; ++n)
8968 Tys[n] = MVT::Other;
8969 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8970 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8971 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8972 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8973 Ops, VLDMemInt->getMemoryVT(),
8974 VLDMemInt->getMemOperand());
8977 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8979 unsigned ResNo = UI.getUse().getResNo();
8980 // Ignore uses of the chain result.
8981 if (ResNo == NumVecs)
8984 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8987 // Now the vldN-lane intrinsic is dead except for its chain result.
8988 // Update uses of the chain.
8989 std::vector<SDValue> VLDDupResults;
8990 for (unsigned n = 0; n < NumVecs; ++n)
8991 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8992 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8993 DCI.CombineTo(VLD, VLDDupResults);
8998 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8999 /// ARMISD::VDUPLANE.
9000 static SDValue PerformVDUPLANECombine(SDNode *N,
9001 TargetLowering::DAGCombinerInfo &DCI) {
9002 SDValue Op = N->getOperand(0);
9004 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9005 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9006 if (CombineVLDDUP(N, DCI))
9007 return SDValue(N, 0);
9009 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9010 // redundant. Ignore bit_converts for now; element sizes are checked below.
9011 while (Op.getOpcode() == ISD::BITCAST)
9012 Op = Op.getOperand(0);
9013 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9016 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9017 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9018 // The canonical VMOV for a zero vector uses a 32-bit element size.
9019 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9021 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9023 EVT VT = N->getValueType(0);
9024 if (EltSize > VT.getVectorElementType().getSizeInBits())
9027 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9030 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9031 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9032 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9036 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9038 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9043 APFloat APF = C->getValueAPF();
9044 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9045 != APFloat::opOK || !isExact)
9048 c0 = (I == 0) ? cN : c0;
9049 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9056 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9057 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9058 /// when the VMUL has a constant operand that is a power of 2.
9060 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9061 /// vmul.f32 d16, d17, d16
9062 /// vcvt.s32.f32 d16, d16
9064 /// vcvt.s32.f32 d16, d16, #3
9065 static SDValue PerformVCVTCombine(SDNode *N,
9066 TargetLowering::DAGCombinerInfo &DCI,
9067 const ARMSubtarget *Subtarget) {
9068 SelectionDAG &DAG = DCI.DAG;
9069 SDValue Op = N->getOperand(0);
9071 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9072 Op.getOpcode() != ISD::FMUL)
9076 SDValue N0 = Op->getOperand(0);
9077 SDValue ConstVec = Op->getOperand(1);
9078 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9080 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9081 !isConstVecPow2(ConstVec, isSigned, C))
9084 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9085 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9086 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9087 // These instructions only exist converting from f32 to i32. We can handle
9088 // smaller integers by generating an extra truncate, but larger ones would
9093 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9094 Intrinsic::arm_neon_vcvtfp2fxu;
9095 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9096 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9097 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9098 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9099 DAG.getConstant(Log2_64(C), MVT::i32));
9101 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9102 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9107 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9108 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9109 /// when the VDIV has a constant operand that is a power of 2.
9111 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9112 /// vcvt.f32.s32 d16, d16
9113 /// vdiv.f32 d16, d17, d16
9115 /// vcvt.f32.s32 d16, d16, #3
9116 static SDValue PerformVDIVCombine(SDNode *N,
9117 TargetLowering::DAGCombinerInfo &DCI,
9118 const ARMSubtarget *Subtarget) {
9119 SelectionDAG &DAG = DCI.DAG;
9120 SDValue Op = N->getOperand(0);
9121 unsigned OpOpcode = Op.getNode()->getOpcode();
9123 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9124 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9128 SDValue ConstVec = N->getOperand(1);
9129 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9131 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9132 !isConstVecPow2(ConstVec, isSigned, C))
9135 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9136 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9137 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9138 // These instructions only exist converting from i32 to f32. We can handle
9139 // smaller integers by generating an extra extend, but larger ones would
9144 SDValue ConvInput = Op.getOperand(0);
9145 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9146 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9147 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9148 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9151 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9152 Intrinsic::arm_neon_vcvtfxu2fp;
9153 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9155 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9156 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9159 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9160 /// operand of a vector shift operation, where all the elements of the
9161 /// build_vector must have the same constant integer value.
9162 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9163 // Ignore bit_converts.
9164 while (Op.getOpcode() == ISD::BITCAST)
9165 Op = Op.getOperand(0);
9166 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9167 APInt SplatBits, SplatUndef;
9168 unsigned SplatBitSize;
9170 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9171 HasAnyUndefs, ElementBits) ||
9172 SplatBitSize > ElementBits)
9174 Cnt = SplatBits.getSExtValue();
9178 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9179 /// operand of a vector shift left operation. That value must be in the range:
9180 /// 0 <= Value < ElementBits for a left shift; or
9181 /// 0 <= Value <= ElementBits for a long left shift.
9182 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9183 assert(VT.isVector() && "vector shift count is not a vector type");
9184 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9185 if (! getVShiftImm(Op, ElementBits, Cnt))
9187 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9190 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9191 /// operand of a vector shift right operation. For a shift opcode, the value
9192 /// is positive, but for an intrinsic the value count must be negative. The
9193 /// absolute value must be in the range:
9194 /// 1 <= |Value| <= ElementBits for a right shift; or
9195 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9196 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9198 assert(VT.isVector() && "vector shift count is not a vector type");
9199 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9200 if (! getVShiftImm(Op, ElementBits, Cnt))
9204 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9207 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9208 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9209 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9212 // Don't do anything for most intrinsics.
9215 // Vector shifts: check for immediate versions and lower them.
9216 // Note: This is done during DAG combining instead of DAG legalizing because
9217 // the build_vectors for 64-bit vector element shift counts are generally
9218 // not legal, and it is hard to see their values after they get legalized to
9219 // loads from a constant pool.
9220 case Intrinsic::arm_neon_vshifts:
9221 case Intrinsic::arm_neon_vshiftu:
9222 case Intrinsic::arm_neon_vrshifts:
9223 case Intrinsic::arm_neon_vrshiftu:
9224 case Intrinsic::arm_neon_vrshiftn:
9225 case Intrinsic::arm_neon_vqshifts:
9226 case Intrinsic::arm_neon_vqshiftu:
9227 case Intrinsic::arm_neon_vqshiftsu:
9228 case Intrinsic::arm_neon_vqshiftns:
9229 case Intrinsic::arm_neon_vqshiftnu:
9230 case Intrinsic::arm_neon_vqshiftnsu:
9231 case Intrinsic::arm_neon_vqrshiftns:
9232 case Intrinsic::arm_neon_vqrshiftnu:
9233 case Intrinsic::arm_neon_vqrshiftnsu: {
9234 EVT VT = N->getOperand(1).getValueType();
9236 unsigned VShiftOpc = 0;
9239 case Intrinsic::arm_neon_vshifts:
9240 case Intrinsic::arm_neon_vshiftu:
9241 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9242 VShiftOpc = ARMISD::VSHL;
9245 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9246 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9247 ARMISD::VSHRs : ARMISD::VSHRu);
9252 case Intrinsic::arm_neon_vrshifts:
9253 case Intrinsic::arm_neon_vrshiftu:
9254 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9258 case Intrinsic::arm_neon_vqshifts:
9259 case Intrinsic::arm_neon_vqshiftu:
9260 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9264 case Intrinsic::arm_neon_vqshiftsu:
9265 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9267 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9269 case Intrinsic::arm_neon_vrshiftn:
9270 case Intrinsic::arm_neon_vqshiftns:
9271 case Intrinsic::arm_neon_vqshiftnu:
9272 case Intrinsic::arm_neon_vqshiftnsu:
9273 case Intrinsic::arm_neon_vqrshiftns:
9274 case Intrinsic::arm_neon_vqrshiftnu:
9275 case Intrinsic::arm_neon_vqrshiftnsu:
9276 // Narrowing shifts require an immediate right shift.
9277 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9279 llvm_unreachable("invalid shift count for narrowing vector shift "
9283 llvm_unreachable("unhandled vector shift");
9287 case Intrinsic::arm_neon_vshifts:
9288 case Intrinsic::arm_neon_vshiftu:
9289 // Opcode already set above.
9291 case Intrinsic::arm_neon_vrshifts:
9292 VShiftOpc = ARMISD::VRSHRs; break;
9293 case Intrinsic::arm_neon_vrshiftu:
9294 VShiftOpc = ARMISD::VRSHRu; break;
9295 case Intrinsic::arm_neon_vrshiftn:
9296 VShiftOpc = ARMISD::VRSHRN; break;
9297 case Intrinsic::arm_neon_vqshifts:
9298 VShiftOpc = ARMISD::VQSHLs; break;
9299 case Intrinsic::arm_neon_vqshiftu:
9300 VShiftOpc = ARMISD::VQSHLu; break;
9301 case Intrinsic::arm_neon_vqshiftsu:
9302 VShiftOpc = ARMISD::VQSHLsu; break;
9303 case Intrinsic::arm_neon_vqshiftns:
9304 VShiftOpc = ARMISD::VQSHRNs; break;
9305 case Intrinsic::arm_neon_vqshiftnu:
9306 VShiftOpc = ARMISD::VQSHRNu; break;
9307 case Intrinsic::arm_neon_vqshiftnsu:
9308 VShiftOpc = ARMISD::VQSHRNsu; break;
9309 case Intrinsic::arm_neon_vqrshiftns:
9310 VShiftOpc = ARMISD::VQRSHRNs; break;
9311 case Intrinsic::arm_neon_vqrshiftnu:
9312 VShiftOpc = ARMISD::VQRSHRNu; break;
9313 case Intrinsic::arm_neon_vqrshiftnsu:
9314 VShiftOpc = ARMISD::VQRSHRNsu; break;
9317 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9318 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9321 case Intrinsic::arm_neon_vshiftins: {
9322 EVT VT = N->getOperand(1).getValueType();
9324 unsigned VShiftOpc = 0;
9326 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9327 VShiftOpc = ARMISD::VSLI;
9328 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9329 VShiftOpc = ARMISD::VSRI;
9331 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9334 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9335 N->getOperand(1), N->getOperand(2),
9336 DAG.getConstant(Cnt, MVT::i32));
9339 case Intrinsic::arm_neon_vqrshifts:
9340 case Intrinsic::arm_neon_vqrshiftu:
9341 // No immediate versions of these to check for.
9348 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9349 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9350 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9351 /// vector element shift counts are generally not legal, and it is hard to see
9352 /// their values after they get legalized to loads from a constant pool.
9353 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9354 const ARMSubtarget *ST) {
9355 EVT VT = N->getValueType(0);
9356 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9357 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9358 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9359 SDValue N1 = N->getOperand(1);
9360 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9361 SDValue N0 = N->getOperand(0);
9362 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9363 DAG.MaskedValueIsZero(N0.getOperand(0),
9364 APInt::getHighBitsSet(32, 16)))
9365 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9369 // Nothing to be done for scalar shifts.
9370 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9371 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9374 assert(ST->hasNEON() && "unexpected vector shift");
9377 switch (N->getOpcode()) {
9378 default: llvm_unreachable("unexpected shift opcode");
9381 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9382 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9383 DAG.getConstant(Cnt, MVT::i32));
9388 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9389 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9390 ARMISD::VSHRs : ARMISD::VSHRu);
9391 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9392 DAG.getConstant(Cnt, MVT::i32));
9398 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9399 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9400 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9401 const ARMSubtarget *ST) {
9402 SDValue N0 = N->getOperand(0);
9404 // Check for sign- and zero-extensions of vector extract operations of 8-
9405 // and 16-bit vector elements. NEON supports these directly. They are
9406 // handled during DAG combining because type legalization will promote them
9407 // to 32-bit types and it is messy to recognize the operations after that.
9408 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9409 SDValue Vec = N0.getOperand(0);
9410 SDValue Lane = N0.getOperand(1);
9411 EVT VT = N->getValueType(0);
9412 EVT EltVT = N0.getValueType();
9413 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9415 if (VT == MVT::i32 &&
9416 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9417 TLI.isTypeLegal(Vec.getValueType()) &&
9418 isa<ConstantSDNode>(Lane)) {
9421 switch (N->getOpcode()) {
9422 default: llvm_unreachable("unexpected opcode");
9423 case ISD::SIGN_EXTEND:
9424 Opc = ARMISD::VGETLANEs;
9426 case ISD::ZERO_EXTEND:
9427 case ISD::ANY_EXTEND:
9428 Opc = ARMISD::VGETLANEu;
9431 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9438 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9439 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9440 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9441 const ARMSubtarget *ST) {
9442 // If the target supports NEON, try to use vmax/vmin instructions for f32
9443 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9444 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9445 // a NaN; only do the transformation when it matches that behavior.
9447 // For now only do this when using NEON for FP operations; if using VFP, it
9448 // is not obvious that the benefit outweighs the cost of switching to the
9450 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9451 N->getValueType(0) != MVT::f32)
9454 SDValue CondLHS = N->getOperand(0);
9455 SDValue CondRHS = N->getOperand(1);
9456 SDValue LHS = N->getOperand(2);
9457 SDValue RHS = N->getOperand(3);
9458 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9460 unsigned Opcode = 0;
9462 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9463 IsReversed = false; // x CC y ? x : y
9464 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9465 IsReversed = true ; // x CC y ? y : x
9479 // If LHS is NaN, an ordered comparison will be false and the result will
9480 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9481 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9482 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9483 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9485 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9486 // will return -0, so vmin can only be used for unsafe math or if one of
9487 // the operands is known to be nonzero.
9488 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9489 !DAG.getTarget().Options.UnsafeFPMath &&
9490 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9492 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9501 // If LHS is NaN, an ordered comparison will be false and the result will
9502 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9503 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9504 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9505 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9507 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9508 // will return +0, so vmax can only be used for unsafe math or if one of
9509 // the operands is known to be nonzero.
9510 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9511 !DAG.getTarget().Options.UnsafeFPMath &&
9512 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9514 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9520 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9523 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9525 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9526 SDValue Cmp = N->getOperand(4);
9527 if (Cmp.getOpcode() != ARMISD::CMPZ)
9528 // Only looking at EQ and NE cases.
9531 EVT VT = N->getValueType(0);
9533 SDValue LHS = Cmp.getOperand(0);
9534 SDValue RHS = Cmp.getOperand(1);
9535 SDValue FalseVal = N->getOperand(0);
9536 SDValue TrueVal = N->getOperand(1);
9537 SDValue ARMcc = N->getOperand(2);
9538 ARMCC::CondCodes CC =
9539 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9557 /// FIXME: Turn this into a target neutral optimization?
9559 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9560 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9561 N->getOperand(3), Cmp);
9562 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9564 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9565 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9566 N->getOperand(3), NewCmp);
9569 if (Res.getNode()) {
9570 APInt KnownZero, KnownOne;
9571 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9572 // Capture demanded bits information that would be otherwise lost.
9573 if (KnownZero == 0xfffffffe)
9574 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9575 DAG.getValueType(MVT::i1));
9576 else if (KnownZero == 0xffffff00)
9577 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9578 DAG.getValueType(MVT::i8));
9579 else if (KnownZero == 0xffff0000)
9580 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9581 DAG.getValueType(MVT::i16));
9587 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9588 DAGCombinerInfo &DCI) const {
9589 switch (N->getOpcode()) {
9591 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9592 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9593 case ISD::SUB: return PerformSUBCombine(N, DCI);
9594 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9595 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9596 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9597 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9598 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9599 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9600 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9601 case ISD::STORE: return PerformSTORECombine(N, DCI);
9602 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9603 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9604 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9605 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9606 case ISD::FP_TO_SINT:
9607 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9608 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9609 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9612 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9613 case ISD::SIGN_EXTEND:
9614 case ISD::ZERO_EXTEND:
9615 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9616 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9617 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9618 case ARMISD::VLD2DUP:
9619 case ARMISD::VLD3DUP:
9620 case ARMISD::VLD4DUP:
9621 return CombineBaseUpdate(N, DCI);
9622 case ARMISD::BUILD_VECTOR:
9623 return PerformARMBUILD_VECTORCombine(N, DCI);
9624 case ISD::INTRINSIC_VOID:
9625 case ISD::INTRINSIC_W_CHAIN:
9626 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9627 case Intrinsic::arm_neon_vld1:
9628 case Intrinsic::arm_neon_vld2:
9629 case Intrinsic::arm_neon_vld3:
9630 case Intrinsic::arm_neon_vld4:
9631 case Intrinsic::arm_neon_vld2lane:
9632 case Intrinsic::arm_neon_vld3lane:
9633 case Intrinsic::arm_neon_vld4lane:
9634 case Intrinsic::arm_neon_vst1:
9635 case Intrinsic::arm_neon_vst2:
9636 case Intrinsic::arm_neon_vst3:
9637 case Intrinsic::arm_neon_vst4:
9638 case Intrinsic::arm_neon_vst2lane:
9639 case Intrinsic::arm_neon_vst3lane:
9640 case Intrinsic::arm_neon_vst4lane:
9641 return CombineBaseUpdate(N, DCI);
9649 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9651 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9654 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9656 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9657 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9659 switch (VT.getSimpleVT().SimpleTy) {
9665 // Unaligned access can use (for example) LRDB, LRDH, LDR
9666 if (AllowsUnaligned) {
9668 *Fast = Subtarget->hasV7Ops();
9675 // For any little-endian targets with neon, we can support unaligned ld/st
9676 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9677 // A big-endian target may also explicitly support unaligned accesses
9678 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9688 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9689 unsigned AlignCheck) {
9690 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9691 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9694 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9695 unsigned DstAlign, unsigned SrcAlign,
9696 bool IsMemset, bool ZeroMemset,
9698 MachineFunction &MF) const {
9699 const Function *F = MF.getFunction();
9701 // See if we can use NEON instructions for this...
9702 if ((!IsMemset || ZeroMemset) &&
9703 Subtarget->hasNEON() &&
9704 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9705 Attribute::NoImplicitFloat)) {
9708 (memOpAlign(SrcAlign, DstAlign, 16) ||
9709 (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9711 } else if (Size >= 8 &&
9712 (memOpAlign(SrcAlign, DstAlign, 8) ||
9713 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9718 // Lowering to i32/i16 if the size permits.
9724 // Let the target-independent logic figure it out.
9728 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9729 if (Val.getOpcode() != ISD::LOAD)
9732 EVT VT1 = Val.getValueType();
9733 if (!VT1.isSimple() || !VT1.isInteger() ||
9734 !VT2.isSimple() || !VT2.isInteger())
9737 switch (VT1.getSimpleVT().SimpleTy) {
9742 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9749 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9750 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9753 if (!isTypeLegal(EVT::getEVT(Ty1)))
9756 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9758 // Assuming the caller doesn't have a zeroext or signext return parameter,
9759 // truncation all the way down to i1 is valid.
9764 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9769 switch (VT.getSimpleVT().SimpleTy) {
9770 default: return false;
9785 if ((V & (Scale - 1)) != 0)
9788 return V == (V & ((1LL << 5) - 1));
9791 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9792 const ARMSubtarget *Subtarget) {
9799 switch (VT.getSimpleVT().SimpleTy) {
9800 default: return false;
9805 // + imm12 or - imm8
9807 return V == (V & ((1LL << 8) - 1));
9808 return V == (V & ((1LL << 12) - 1));
9811 // Same as ARM mode. FIXME: NEON?
9812 if (!Subtarget->hasVFP2())
9817 return V == (V & ((1LL << 8) - 1));
9821 /// isLegalAddressImmediate - Return true if the integer value can be used
9822 /// as the offset of the target addressing mode for load / store of the
9824 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9825 const ARMSubtarget *Subtarget) {
9832 if (Subtarget->isThumb1Only())
9833 return isLegalT1AddressImmediate(V, VT);
9834 else if (Subtarget->isThumb2())
9835 return isLegalT2AddressImmediate(V, VT, Subtarget);
9840 switch (VT.getSimpleVT().SimpleTy) {
9841 default: return false;
9846 return V == (V & ((1LL << 12) - 1));
9849 return V == (V & ((1LL << 8) - 1));
9852 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9857 return V == (V & ((1LL << 8) - 1));
9861 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9863 int Scale = AM.Scale;
9867 switch (VT.getSimpleVT().SimpleTy) {
9868 default: return false;
9877 return Scale == 2 || Scale == 4 || Scale == 8;
9880 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9884 // Note, we allow "void" uses (basically, uses that aren't loads or
9885 // stores), because arm allows folding a scale into many arithmetic
9886 // operations. This should be made more precise and revisited later.
9888 // Allow r << imm, but the imm has to be a multiple of two.
9889 if (Scale & 1) return false;
9890 return isPowerOf2_32(Scale);
9894 /// isLegalAddressingMode - Return true if the addressing mode represented
9895 /// by AM is legal for this target, for a load/store of the specified type.
9896 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9898 EVT VT = getValueType(Ty, true);
9899 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9902 // Can never fold addr of global into load/store.
9907 case 0: // no scale reg, must be "r+i" or "r", or "i".
9910 if (Subtarget->isThumb1Only())
9914 // ARM doesn't support any R+R*scale+imm addr modes.
9921 if (Subtarget->isThumb2())
9922 return isLegalT2ScaledAddressingMode(AM, VT);
9924 int Scale = AM.Scale;
9925 switch (VT.getSimpleVT().SimpleTy) {
9926 default: return false;
9930 if (Scale < 0) Scale = -Scale;
9934 return isPowerOf2_32(Scale & ~1);
9938 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9943 // Note, we allow "void" uses (basically, uses that aren't loads or
9944 // stores), because arm allows folding a scale into many arithmetic
9945 // operations. This should be made more precise and revisited later.
9947 // Allow r << imm, but the imm has to be a multiple of two.
9948 if (Scale & 1) return false;
9949 return isPowerOf2_32(Scale);
9955 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9956 /// icmp immediate, that is the target has icmp instructions which can compare
9957 /// a register against the immediate without having to materialize the
9958 /// immediate into a register.
9959 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9960 // Thumb2 and ARM modes can use cmn for negative immediates.
9961 if (!Subtarget->isThumb())
9962 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9963 if (Subtarget->isThumb2())
9964 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9965 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9966 return Imm >= 0 && Imm <= 255;
9969 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9970 /// *or sub* immediate, that is the target has add or sub instructions which can
9971 /// add a register with the immediate without having to materialize the
9972 /// immediate into a register.
9973 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9974 // Same encoding for add/sub, just flip the sign.
9975 int64_t AbsImm = llvm::abs64(Imm);
9976 if (!Subtarget->isThumb())
9977 return ARM_AM::getSOImmVal(AbsImm) != -1;
9978 if (Subtarget->isThumb2())
9979 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9980 // Thumb1 only has 8-bit unsigned immediate.
9981 return AbsImm >= 0 && AbsImm <= 255;
9984 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9985 bool isSEXTLoad, SDValue &Base,
9986 SDValue &Offset, bool &isInc,
9987 SelectionDAG &DAG) {
9988 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9991 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9993 Base = Ptr->getOperand(0);
9994 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9995 int RHSC = (int)RHS->getZExtValue();
9996 if (RHSC < 0 && RHSC > -256) {
9997 assert(Ptr->getOpcode() == ISD::ADD);
9999 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10003 isInc = (Ptr->getOpcode() == ISD::ADD);
10004 Offset = Ptr->getOperand(1);
10006 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10007 // AddressingMode 2
10008 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10009 int RHSC = (int)RHS->getZExtValue();
10010 if (RHSC < 0 && RHSC > -0x1000) {
10011 assert(Ptr->getOpcode() == ISD::ADD);
10013 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10014 Base = Ptr->getOperand(0);
10019 if (Ptr->getOpcode() == ISD::ADD) {
10021 ARM_AM::ShiftOpc ShOpcVal=
10022 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10023 if (ShOpcVal != ARM_AM::no_shift) {
10024 Base = Ptr->getOperand(1);
10025 Offset = Ptr->getOperand(0);
10027 Base = Ptr->getOperand(0);
10028 Offset = Ptr->getOperand(1);
10033 isInc = (Ptr->getOpcode() == ISD::ADD);
10034 Base = Ptr->getOperand(0);
10035 Offset = Ptr->getOperand(1);
10039 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10043 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10044 bool isSEXTLoad, SDValue &Base,
10045 SDValue &Offset, bool &isInc,
10046 SelectionDAG &DAG) {
10047 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10050 Base = Ptr->getOperand(0);
10051 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10052 int RHSC = (int)RHS->getZExtValue();
10053 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10054 assert(Ptr->getOpcode() == ISD::ADD);
10056 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10058 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10059 isInc = Ptr->getOpcode() == ISD::ADD;
10060 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10068 /// getPreIndexedAddressParts - returns true by value, base pointer and
10069 /// offset pointer and addressing mode by reference if the node's address
10070 /// can be legally represented as pre-indexed load / store address.
10072 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10074 ISD::MemIndexedMode &AM,
10075 SelectionDAG &DAG) const {
10076 if (Subtarget->isThumb1Only())
10081 bool isSEXTLoad = false;
10082 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10083 Ptr = LD->getBasePtr();
10084 VT = LD->getMemoryVT();
10085 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10086 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10087 Ptr = ST->getBasePtr();
10088 VT = ST->getMemoryVT();
10093 bool isLegal = false;
10094 if (Subtarget->isThumb2())
10095 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10096 Offset, isInc, DAG);
10098 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10099 Offset, isInc, DAG);
10103 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10107 /// getPostIndexedAddressParts - returns true by value, base pointer and
10108 /// offset pointer and addressing mode by reference if this node can be
10109 /// combined with a load / store to form a post-indexed load / store.
10110 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10113 ISD::MemIndexedMode &AM,
10114 SelectionDAG &DAG) const {
10115 if (Subtarget->isThumb1Only())
10120 bool isSEXTLoad = false;
10121 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10122 VT = LD->getMemoryVT();
10123 Ptr = LD->getBasePtr();
10124 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10125 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10126 VT = ST->getMemoryVT();
10127 Ptr = ST->getBasePtr();
10132 bool isLegal = false;
10133 if (Subtarget->isThumb2())
10134 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10137 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10143 // Swap base ptr and offset to catch more post-index load / store when
10144 // it's legal. In Thumb2 mode, offset must be an immediate.
10145 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10146 !Subtarget->isThumb2())
10147 std::swap(Base, Offset);
10149 // Post-indexed load / store update the base pointer.
10154 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10158 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10161 const SelectionDAG &DAG,
10162 unsigned Depth) const {
10163 unsigned BitWidth = KnownOne.getBitWidth();
10164 KnownZero = KnownOne = APInt(BitWidth, 0);
10165 switch (Op.getOpcode()) {
10171 // These nodes' second result is a boolean
10172 if (Op.getResNo() == 0)
10174 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10176 case ARMISD::CMOV: {
10177 // Bits are known zero/one if known on the LHS and RHS.
10178 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10179 if (KnownZero == 0 && KnownOne == 0) return;
10181 APInt KnownZeroRHS, KnownOneRHS;
10182 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10183 KnownZero &= KnownZeroRHS;
10184 KnownOne &= KnownOneRHS;
10187 case ISD::INTRINSIC_W_CHAIN: {
10188 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10189 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10192 case Intrinsic::arm_ldaex:
10193 case Intrinsic::arm_ldrex: {
10194 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10195 unsigned MemBits = VT.getScalarType().getSizeInBits();
10196 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10204 //===----------------------------------------------------------------------===//
10205 // ARM Inline Assembly Support
10206 //===----------------------------------------------------------------------===//
10208 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10209 // Looking for "rev" which is V6+.
10210 if (!Subtarget->hasV6Ops())
10213 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10214 std::string AsmStr = IA->getAsmString();
10215 SmallVector<StringRef, 4> AsmPieces;
10216 SplitString(AsmStr, AsmPieces, ";\n");
10218 switch (AsmPieces.size()) {
10219 default: return false;
10221 AsmStr = AsmPieces[0];
10223 SplitString(AsmStr, AsmPieces, " \t,");
10226 if (AsmPieces.size() == 3 &&
10227 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10228 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10229 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10230 if (Ty && Ty->getBitWidth() == 32)
10231 return IntrinsicLowering::LowerToByteSwap(CI);
10239 /// getConstraintType - Given a constraint letter, return the type of
10240 /// constraint it is for this target.
10241 ARMTargetLowering::ConstraintType
10242 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10243 if (Constraint.size() == 1) {
10244 switch (Constraint[0]) {
10246 case 'l': return C_RegisterClass;
10247 case 'w': return C_RegisterClass;
10248 case 'h': return C_RegisterClass;
10249 case 'x': return C_RegisterClass;
10250 case 't': return C_RegisterClass;
10251 case 'j': return C_Other; // Constant for movw.
10252 // An address with a single base register. Due to the way we
10253 // currently handle addresses it is the same as an 'r' memory constraint.
10254 case 'Q': return C_Memory;
10256 } else if (Constraint.size() == 2) {
10257 switch (Constraint[0]) {
10259 // All 'U+' constraints are addresses.
10260 case 'U': return C_Memory;
10263 return TargetLowering::getConstraintType(Constraint);
10266 /// Examine constraint type and operand type and determine a weight value.
10267 /// This object must already have been set up with the operand type
10268 /// and the current alternative constraint selected.
10269 TargetLowering::ConstraintWeight
10270 ARMTargetLowering::getSingleConstraintMatchWeight(
10271 AsmOperandInfo &info, const char *constraint) const {
10272 ConstraintWeight weight = CW_Invalid;
10273 Value *CallOperandVal = info.CallOperandVal;
10274 // If we don't have a value, we can't do a match,
10275 // but allow it at the lowest weight.
10276 if (!CallOperandVal)
10278 Type *type = CallOperandVal->getType();
10279 // Look at the constraint type.
10280 switch (*constraint) {
10282 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10285 if (type->isIntegerTy()) {
10286 if (Subtarget->isThumb())
10287 weight = CW_SpecificReg;
10289 weight = CW_Register;
10293 if (type->isFloatingPointTy())
10294 weight = CW_Register;
10300 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10302 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10304 if (Constraint.size() == 1) {
10305 // GCC ARM Constraint Letters
10306 switch (Constraint[0]) {
10307 case 'l': // Low regs or general regs.
10308 if (Subtarget->isThumb())
10309 return RCPair(0U, &ARM::tGPRRegClass);
10310 return RCPair(0U, &ARM::GPRRegClass);
10311 case 'h': // High regs or no regs.
10312 if (Subtarget->isThumb())
10313 return RCPair(0U, &ARM::hGPRRegClass);
10316 return RCPair(0U, &ARM::GPRRegClass);
10318 if (VT == MVT::Other)
10320 if (VT == MVT::f32)
10321 return RCPair(0U, &ARM::SPRRegClass);
10322 if (VT.getSizeInBits() == 64)
10323 return RCPair(0U, &ARM::DPRRegClass);
10324 if (VT.getSizeInBits() == 128)
10325 return RCPair(0U, &ARM::QPRRegClass);
10328 if (VT == MVT::Other)
10330 if (VT == MVT::f32)
10331 return RCPair(0U, &ARM::SPR_8RegClass);
10332 if (VT.getSizeInBits() == 64)
10333 return RCPair(0U, &ARM::DPR_8RegClass);
10334 if (VT.getSizeInBits() == 128)
10335 return RCPair(0U, &ARM::QPR_8RegClass);
10338 if (VT == MVT::f32)
10339 return RCPair(0U, &ARM::SPRRegClass);
10343 if (StringRef("{cc}").equals_lower(Constraint))
10344 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10346 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10349 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10350 /// vector. If it is invalid, don't add anything to Ops.
10351 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10352 std::string &Constraint,
10353 std::vector<SDValue>&Ops,
10354 SelectionDAG &DAG) const {
10357 // Currently only support length 1 constraints.
10358 if (Constraint.length() != 1) return;
10360 char ConstraintLetter = Constraint[0];
10361 switch (ConstraintLetter) {
10364 case 'I': case 'J': case 'K': case 'L':
10365 case 'M': case 'N': case 'O':
10366 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10370 int64_t CVal64 = C->getSExtValue();
10371 int CVal = (int) CVal64;
10372 // None of these constraints allow values larger than 32 bits. Check
10373 // that the value fits in an int.
10374 if (CVal != CVal64)
10377 switch (ConstraintLetter) {
10379 // Constant suitable for movw, must be between 0 and
10381 if (Subtarget->hasV6T2Ops())
10382 if (CVal >= 0 && CVal <= 65535)
10386 if (Subtarget->isThumb1Only()) {
10387 // This must be a constant between 0 and 255, for ADD
10389 if (CVal >= 0 && CVal <= 255)
10391 } else if (Subtarget->isThumb2()) {
10392 // A constant that can be used as an immediate value in a
10393 // data-processing instruction.
10394 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10397 // A constant that can be used as an immediate value in a
10398 // data-processing instruction.
10399 if (ARM_AM::getSOImmVal(CVal) != -1)
10405 if (Subtarget->isThumb()) { // FIXME thumb2
10406 // This must be a constant between -255 and -1, for negated ADD
10407 // immediates. This can be used in GCC with an "n" modifier that
10408 // prints the negated value, for use with SUB instructions. It is
10409 // not useful otherwise but is implemented for compatibility.
10410 if (CVal >= -255 && CVal <= -1)
10413 // This must be a constant between -4095 and 4095. It is not clear
10414 // what this constraint is intended for. Implemented for
10415 // compatibility with GCC.
10416 if (CVal >= -4095 && CVal <= 4095)
10422 if (Subtarget->isThumb1Only()) {
10423 // A 32-bit value where only one byte has a nonzero value. Exclude
10424 // zero to match GCC. This constraint is used by GCC internally for
10425 // constants that can be loaded with a move/shift combination.
10426 // It is not useful otherwise but is implemented for compatibility.
10427 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10429 } else if (Subtarget->isThumb2()) {
10430 // A constant whose bitwise inverse can be used as an immediate
10431 // value in a data-processing instruction. This can be used in GCC
10432 // with a "B" modifier that prints the inverted value, for use with
10433 // BIC and MVN instructions. It is not useful otherwise but is
10434 // implemented for compatibility.
10435 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10438 // A constant whose bitwise inverse can be used as an immediate
10439 // value in a data-processing instruction. This can be used in GCC
10440 // with a "B" modifier that prints the inverted value, for use with
10441 // BIC and MVN instructions. It is not useful otherwise but is
10442 // implemented for compatibility.
10443 if (ARM_AM::getSOImmVal(~CVal) != -1)
10449 if (Subtarget->isThumb1Only()) {
10450 // This must be a constant between -7 and 7,
10451 // for 3-operand ADD/SUB immediate instructions.
10452 if (CVal >= -7 && CVal < 7)
10454 } else if (Subtarget->isThumb2()) {
10455 // A constant whose negation can be used as an immediate value in a
10456 // data-processing instruction. This can be used in GCC with an "n"
10457 // modifier that prints the negated value, for use with SUB
10458 // instructions. It is not useful otherwise but is implemented for
10460 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10463 // A constant whose negation can be used as an immediate value in a
10464 // data-processing instruction. This can be used in GCC with an "n"
10465 // modifier that prints the negated value, for use with SUB
10466 // instructions. It is not useful otherwise but is implemented for
10468 if (ARM_AM::getSOImmVal(-CVal) != -1)
10474 if (Subtarget->isThumb()) { // FIXME thumb2
10475 // This must be a multiple of 4 between 0 and 1020, for
10476 // ADD sp + immediate.
10477 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10480 // A power of two or a constant between 0 and 32. This is used in
10481 // GCC for the shift amount on shifted register operands, but it is
10482 // useful in general for any shift amounts.
10483 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10489 if (Subtarget->isThumb()) { // FIXME thumb2
10490 // This must be a constant between 0 and 31, for shift amounts.
10491 if (CVal >= 0 && CVal <= 31)
10497 if (Subtarget->isThumb()) { // FIXME thumb2
10498 // This must be a multiple of 4 between -508 and 508, for
10499 // ADD/SUB sp = sp + immediate.
10500 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10505 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10509 if (Result.getNode()) {
10510 Ops.push_back(Result);
10513 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10516 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10517 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10518 unsigned Opcode = Op->getOpcode();
10519 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10520 "Invalid opcode for Div/Rem lowering");
10521 bool isSigned = (Opcode == ISD::SDIVREM);
10522 EVT VT = Op->getValueType(0);
10523 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10526 switch (VT.getSimpleVT().SimpleTy) {
10527 default: llvm_unreachable("Unexpected request for libcall!");
10528 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10529 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10530 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10531 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10534 SDValue InChain = DAG.getEntryNode();
10536 TargetLowering::ArgListTy Args;
10537 TargetLowering::ArgListEntry Entry;
10538 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10539 EVT ArgVT = Op->getOperand(i).getValueType();
10540 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10541 Entry.Node = Op->getOperand(i);
10543 Entry.isSExt = isSigned;
10544 Entry.isZExt = !isSigned;
10545 Args.push_back(Entry);
10548 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10551 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10554 TargetLowering::CallLoweringInfo CLI(DAG);
10555 CLI.setDebugLoc(dl).setChain(InChain)
10556 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, &Args, 0)
10557 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10559 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10560 return CallInfo.first;
10564 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10565 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10569 SDValue Chain = Op.getOperand(0);
10570 SDValue Size = Op.getOperand(1);
10572 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10573 DAG.getConstant(2, MVT::i32));
10576 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10577 Flag = Chain.getValue(1);
10579 SDVTList NodeTys = DAG.getVTList(MVT::i32, MVT::Glue);
10580 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10582 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10583 Chain = NewSP.getValue(1);
10585 SDValue Ops[2] = { NewSP, Chain };
10586 return DAG.getMergeValues(Ops, DL);
10590 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10591 // The ARM target isn't yet aware of offsets.
10595 bool ARM::isBitFieldInvertedMask(unsigned v) {
10596 if (v == 0xffffffff)
10599 // there can be 1's on either or both "outsides", all the "inside"
10600 // bits must be 0's
10601 unsigned TO = CountTrailingOnes_32(v);
10602 unsigned LO = CountLeadingOnes_32(v);
10603 v = (v >> TO) << TO;
10604 v = (v << LO) >> LO;
10608 /// isFPImmLegal - Returns true if the target can instruction select the
10609 /// specified FP immediate natively. If false, the legalizer will
10610 /// materialize the FP immediate as a load from a constant pool.
10611 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10612 if (!Subtarget->hasVFP3())
10614 if (VT == MVT::f32)
10615 return ARM_AM::getFP32Imm(Imm) != -1;
10616 if (VT == MVT::f64)
10617 return ARM_AM::getFP64Imm(Imm) != -1;
10621 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10622 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10623 /// specified in the intrinsic calls.
10624 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10626 unsigned Intrinsic) const {
10627 switch (Intrinsic) {
10628 case Intrinsic::arm_neon_vld1:
10629 case Intrinsic::arm_neon_vld2:
10630 case Intrinsic::arm_neon_vld3:
10631 case Intrinsic::arm_neon_vld4:
10632 case Intrinsic::arm_neon_vld2lane:
10633 case Intrinsic::arm_neon_vld3lane:
10634 case Intrinsic::arm_neon_vld4lane: {
10635 Info.opc = ISD::INTRINSIC_W_CHAIN;
10636 // Conservatively set memVT to the entire set of vectors loaded.
10637 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10638 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10639 Info.ptrVal = I.getArgOperand(0);
10641 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10642 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10643 Info.vol = false; // volatile loads with NEON intrinsics not supported
10644 Info.readMem = true;
10645 Info.writeMem = false;
10648 case Intrinsic::arm_neon_vst1:
10649 case Intrinsic::arm_neon_vst2:
10650 case Intrinsic::arm_neon_vst3:
10651 case Intrinsic::arm_neon_vst4:
10652 case Intrinsic::arm_neon_vst2lane:
10653 case Intrinsic::arm_neon_vst3lane:
10654 case Intrinsic::arm_neon_vst4lane: {
10655 Info.opc = ISD::INTRINSIC_VOID;
10656 // Conservatively set memVT to the entire set of vectors stored.
10657 unsigned NumElts = 0;
10658 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10659 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10660 if (!ArgTy->isVectorTy())
10662 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10664 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10665 Info.ptrVal = I.getArgOperand(0);
10667 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10668 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10669 Info.vol = false; // volatile stores with NEON intrinsics not supported
10670 Info.readMem = false;
10671 Info.writeMem = true;
10674 case Intrinsic::arm_ldaex:
10675 case Intrinsic::arm_ldrex: {
10676 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10677 Info.opc = ISD::INTRINSIC_W_CHAIN;
10678 Info.memVT = MVT::getVT(PtrTy->getElementType());
10679 Info.ptrVal = I.getArgOperand(0);
10681 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10683 Info.readMem = true;
10684 Info.writeMem = false;
10687 case Intrinsic::arm_stlex:
10688 case Intrinsic::arm_strex: {
10689 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10690 Info.opc = ISD::INTRINSIC_W_CHAIN;
10691 Info.memVT = MVT::getVT(PtrTy->getElementType());
10692 Info.ptrVal = I.getArgOperand(1);
10694 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10696 Info.readMem = false;
10697 Info.writeMem = true;
10700 case Intrinsic::arm_stlexd:
10701 case Intrinsic::arm_strexd: {
10702 Info.opc = ISD::INTRINSIC_W_CHAIN;
10703 Info.memVT = MVT::i64;
10704 Info.ptrVal = I.getArgOperand(2);
10708 Info.readMem = false;
10709 Info.writeMem = true;
10712 case Intrinsic::arm_ldaexd:
10713 case Intrinsic::arm_ldrexd: {
10714 Info.opc = ISD::INTRINSIC_W_CHAIN;
10715 Info.memVT = MVT::i64;
10716 Info.ptrVal = I.getArgOperand(0);
10720 Info.readMem = true;
10721 Info.writeMem = false;
10731 /// \brief Returns true if it is beneficial to convert a load of a constant
10732 /// to just the constant itself.
10733 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10735 assert(Ty->isIntegerTy());
10737 unsigned Bits = Ty->getPrimitiveSizeInBits();
10738 if (Bits == 0 || Bits > 32)
10743 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10744 // Loads and stores less than 64-bits are already atomic; ones above that
10745 // are doomed anyway, so defer to the default libcall and blame the OS when
10746 // things go wrong:
10747 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10748 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10749 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10750 return LI->getType()->getPrimitiveSizeInBits() == 64;
10752 // For the real atomic operations, we have ldrex/strex up to 64 bits.
10753 return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10756 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10757 AtomicOrdering Ord) const {
10758 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10759 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10761 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10763 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10764 // intrinsic must return {i32, i32} and we have to recombine them into a
10765 // single i64 here.
10766 if (ValTy->getPrimitiveSizeInBits() == 64) {
10767 Intrinsic::ID Int =
10768 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10769 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10771 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10772 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10774 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10775 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10776 if (!Subtarget->isLittle())
10777 std::swap (Lo, Hi);
10778 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10779 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10780 return Builder.CreateOr(
10781 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10784 Type *Tys[] = { Addr->getType() };
10785 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10786 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10788 return Builder.CreateTruncOrBitCast(
10789 Builder.CreateCall(Ldrex, Addr),
10790 cast<PointerType>(Addr->getType())->getElementType());
10793 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10795 AtomicOrdering Ord) const {
10796 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10798 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10800 // Since the intrinsics must have legal type, the i64 intrinsics take two
10801 // parameters: "i32, i32". We must marshal Val into the appropriate form
10802 // before the call.
10803 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10804 Intrinsic::ID Int =
10805 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10806 Function *Strex = Intrinsic::getDeclaration(M, Int);
10807 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10809 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10810 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10811 if (!Subtarget->isLittle())
10812 std::swap (Lo, Hi);
10813 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10814 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10817 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10818 Type *Tys[] = { Addr->getType() };
10819 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10821 return Builder.CreateCall2(
10822 Strex, Builder.CreateZExtOrBitCast(
10823 Val, Strex->getFunctionType()->getParamType(0)),
10835 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10836 uint64_t &Members) {
10837 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10838 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10839 uint64_t SubMembers = 0;
10840 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10842 Members += SubMembers;
10844 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10845 uint64_t SubMembers = 0;
10846 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10848 Members += SubMembers * AT->getNumElements();
10849 } else if (Ty->isFloatTy()) {
10850 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10854 } else if (Ty->isDoubleTy()) {
10855 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10859 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10866 return VT->getBitWidth() == 64;
10868 return VT->getBitWidth() == 128;
10870 switch (VT->getBitWidth()) {
10883 return (Members > 0 && Members <= 4);
10886 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10887 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10888 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10889 if (getEffectiveCallingConv(CallConv, isVarArg) !=
10890 CallingConv::ARM_AAPCS_VFP)
10893 HABaseType Base = HA_UNKNOWN;
10894 uint64_t Members = 0;
10895 bool result = isHomogeneousAggregate(Ty, Base, Members);
10896 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");