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 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
714 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
715 // the default expansion.
716 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
717 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
718 // to ldrex/strex loops already.
719 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
721 // On v8, we have particularly efficient implementations of atomic fences
722 // if they can be combined with nearby atomic loads and stores.
723 if (!Subtarget->hasV8Ops()) {
724 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
725 setInsertFencesForAtomic(true);
728 // If there's anything we can use as a barrier, go through custom lowering
730 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
731 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
733 // Set them all for expansion, which will force libcalls.
734 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
735 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
736 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
737 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
738 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
739 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
740 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
741 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
742 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
743 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
744 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
745 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
746 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
747 // Unordered/Monotonic case.
748 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
749 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
752 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
754 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
755 if (!Subtarget->hasV6Ops()) {
756 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
757 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
759 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
761 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
762 !Subtarget->isThumb1Only()) {
763 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
764 // iff target supports vfp2.
765 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
766 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
769 // We want to custom lower some of our intrinsics.
770 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
771 if (Subtarget->isTargetDarwin()) {
772 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
773 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
774 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
777 setOperationAction(ISD::SETCC, MVT::i32, Expand);
778 setOperationAction(ISD::SETCC, MVT::f32, Expand);
779 setOperationAction(ISD::SETCC, MVT::f64, Expand);
780 setOperationAction(ISD::SELECT, MVT::i32, Custom);
781 setOperationAction(ISD::SELECT, MVT::f32, Custom);
782 setOperationAction(ISD::SELECT, MVT::f64, Custom);
783 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
784 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
785 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
787 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
788 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
789 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
790 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
791 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
793 // We don't support sin/cos/fmod/copysign/pow
794 setOperationAction(ISD::FSIN, MVT::f64, Expand);
795 setOperationAction(ISD::FSIN, MVT::f32, Expand);
796 setOperationAction(ISD::FCOS, MVT::f32, Expand);
797 setOperationAction(ISD::FCOS, MVT::f64, Expand);
798 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
799 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
800 setOperationAction(ISD::FREM, MVT::f64, Expand);
801 setOperationAction(ISD::FREM, MVT::f32, Expand);
802 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
803 !Subtarget->isThumb1Only()) {
804 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
805 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
807 setOperationAction(ISD::FPOW, MVT::f64, Expand);
808 setOperationAction(ISD::FPOW, MVT::f32, Expand);
810 if (!Subtarget->hasVFP4()) {
811 setOperationAction(ISD::FMA, MVT::f64, Expand);
812 setOperationAction(ISD::FMA, MVT::f32, Expand);
815 // Various VFP goodness
816 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
817 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
818 if (Subtarget->hasVFP2()) {
819 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
820 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
821 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
822 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
824 // Special handling for half-precision FP.
825 if (!Subtarget->hasFP16()) {
826 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
827 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
831 // Combine sin / cos into one node or libcall if possible.
832 if (Subtarget->hasSinCos()) {
833 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
834 setLibcallName(RTLIB::SINCOS_F64, "sincos");
835 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
836 // For iOS, we don't want to the normal expansion of a libcall to
837 // sincos. We want to issue a libcall to __sincos_stret.
838 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
839 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
843 // We have target-specific dag combine patterns for the following nodes:
844 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
845 setTargetDAGCombine(ISD::ADD);
846 setTargetDAGCombine(ISD::SUB);
847 setTargetDAGCombine(ISD::MUL);
848 setTargetDAGCombine(ISD::AND);
849 setTargetDAGCombine(ISD::OR);
850 setTargetDAGCombine(ISD::XOR);
852 if (Subtarget->hasV6Ops())
853 setTargetDAGCombine(ISD::SRL);
855 setStackPointerRegisterToSaveRestore(ARM::SP);
857 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
858 !Subtarget->hasVFP2())
859 setSchedulingPreference(Sched::RegPressure);
861 setSchedulingPreference(Sched::Hybrid);
863 //// temporary - rewrite interface to use type
864 MaxStoresPerMemset = 8;
865 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
866 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
867 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
868 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
869 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
871 // On ARM arguments smaller than 4 bytes are extended, so all arguments
872 // are at least 4 bytes aligned.
873 setMinStackArgumentAlignment(4);
875 // Prefer likely predicted branches to selects on out-of-order cores.
876 PredictableSelectIsExpensive = Subtarget->isLikeA9();
878 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
881 // FIXME: It might make sense to define the representative register class as the
882 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
883 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
884 // SPR's representative would be DPR_VFP2. This should work well if register
885 // pressure tracking were modified such that a register use would increment the
886 // pressure of the register class's representative and all of it's super
887 // classes' representatives transitively. We have not implemented this because
888 // of the difficulty prior to coalescing of modeling operand register classes
889 // due to the common occurrence of cross class copies and subregister insertions
891 std::pair<const TargetRegisterClass*, uint8_t>
892 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
893 const TargetRegisterClass *RRC = nullptr;
895 switch (VT.SimpleTy) {
897 return TargetLowering::findRepresentativeClass(VT);
898 // Use DPR as representative register class for all floating point
899 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
900 // the cost is 1 for both f32 and f64.
901 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
902 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
903 RRC = &ARM::DPRRegClass;
904 // When NEON is used for SP, only half of the register file is available
905 // because operations that define both SP and DP results will be constrained
906 // to the VFP2 class (D0-D15). We currently model this constraint prior to
907 // coalescing by double-counting the SP regs. See the FIXME above.
908 if (Subtarget->useNEONForSinglePrecisionFP())
911 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
912 case MVT::v4f32: case MVT::v2f64:
913 RRC = &ARM::DPRRegClass;
917 RRC = &ARM::DPRRegClass;
921 RRC = &ARM::DPRRegClass;
925 return std::make_pair(RRC, Cost);
928 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
930 default: return nullptr;
931 case ARMISD::Wrapper: return "ARMISD::Wrapper";
932 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
933 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
934 case ARMISD::CALL: return "ARMISD::CALL";
935 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
936 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
937 case ARMISD::tCALL: return "ARMISD::tCALL";
938 case ARMISD::BRCOND: return "ARMISD::BRCOND";
939 case ARMISD::BR_JT: return "ARMISD::BR_JT";
940 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
941 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
942 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
943 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
944 case ARMISD::CMP: return "ARMISD::CMP";
945 case ARMISD::CMN: return "ARMISD::CMN";
946 case ARMISD::CMPZ: return "ARMISD::CMPZ";
947 case ARMISD::CMPFP: return "ARMISD::CMPFP";
948 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
949 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
950 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
952 case ARMISD::CMOV: return "ARMISD::CMOV";
954 case ARMISD::RBIT: return "ARMISD::RBIT";
956 case ARMISD::FTOSI: return "ARMISD::FTOSI";
957 case ARMISD::FTOUI: return "ARMISD::FTOUI";
958 case ARMISD::SITOF: return "ARMISD::SITOF";
959 case ARMISD::UITOF: return "ARMISD::UITOF";
961 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
962 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
963 case ARMISD::RRX: return "ARMISD::RRX";
965 case ARMISD::ADDC: return "ARMISD::ADDC";
966 case ARMISD::ADDE: return "ARMISD::ADDE";
967 case ARMISD::SUBC: return "ARMISD::SUBC";
968 case ARMISD::SUBE: return "ARMISD::SUBE";
970 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
971 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
973 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
974 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
976 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
978 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
980 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
982 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
984 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
986 case ARMISD::VCEQ: return "ARMISD::VCEQ";
987 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
988 case ARMISD::VCGE: return "ARMISD::VCGE";
989 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
990 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
991 case ARMISD::VCGEU: return "ARMISD::VCGEU";
992 case ARMISD::VCGT: return "ARMISD::VCGT";
993 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
994 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
995 case ARMISD::VCGTU: return "ARMISD::VCGTU";
996 case ARMISD::VTST: return "ARMISD::VTST";
998 case ARMISD::VSHL: return "ARMISD::VSHL";
999 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1000 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1001 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1002 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1003 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1004 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1005 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1006 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1007 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1008 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1009 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1010 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1011 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1012 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1013 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1014 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1015 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1016 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1017 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1018 case ARMISD::VDUP: return "ARMISD::VDUP";
1019 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1020 case ARMISD::VEXT: return "ARMISD::VEXT";
1021 case ARMISD::VREV64: return "ARMISD::VREV64";
1022 case ARMISD::VREV32: return "ARMISD::VREV32";
1023 case ARMISD::VREV16: return "ARMISD::VREV16";
1024 case ARMISD::VZIP: return "ARMISD::VZIP";
1025 case ARMISD::VUZP: return "ARMISD::VUZP";
1026 case ARMISD::VTRN: return "ARMISD::VTRN";
1027 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1028 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1029 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1030 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1031 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1032 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1033 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1034 case ARMISD::FMAX: return "ARMISD::FMAX";
1035 case ARMISD::FMIN: return "ARMISD::FMIN";
1036 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1037 case ARMISD::VMINNM: return "ARMISD::VMIN";
1038 case ARMISD::BFI: return "ARMISD::BFI";
1039 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1040 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1041 case ARMISD::VBSL: return "ARMISD::VBSL";
1042 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1043 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1044 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1045 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1046 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1047 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1048 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1049 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1050 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1051 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1052 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1053 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1054 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1055 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1056 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1057 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1058 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1059 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1060 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1061 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1065 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1066 if (!VT.isVector()) return getPointerTy();
1067 return VT.changeVectorElementTypeToInteger();
1070 /// getRegClassFor - Return the register class that should be used for the
1071 /// specified value type.
1072 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1073 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1074 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1075 // load / store 4 to 8 consecutive D registers.
1076 if (Subtarget->hasNEON()) {
1077 if (VT == MVT::v4i64)
1078 return &ARM::QQPRRegClass;
1079 if (VT == MVT::v8i64)
1080 return &ARM::QQQQPRRegClass;
1082 return TargetLowering::getRegClassFor(VT);
1085 // Create a fast isel object.
1087 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1088 const TargetLibraryInfo *libInfo) const {
1089 return ARM::createFastISel(funcInfo, libInfo);
1092 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1093 /// be used for loads / stores from the global.
1094 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1095 return (Subtarget->isThumb1Only() ? 127 : 4095);
1098 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1099 unsigned NumVals = N->getNumValues();
1101 return Sched::RegPressure;
1103 for (unsigned i = 0; i != NumVals; ++i) {
1104 EVT VT = N->getValueType(i);
1105 if (VT == MVT::Glue || VT == MVT::Other)
1107 if (VT.isFloatingPoint() || VT.isVector())
1111 if (!N->isMachineOpcode())
1112 return Sched::RegPressure;
1114 // Load are scheduled for latency even if there instruction itinerary
1115 // is not available.
1116 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1117 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1119 if (MCID.getNumDefs() == 0)
1120 return Sched::RegPressure;
1121 if (!Itins->isEmpty() &&
1122 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1125 return Sched::RegPressure;
1128 //===----------------------------------------------------------------------===//
1130 //===----------------------------------------------------------------------===//
1132 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1133 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1135 default: llvm_unreachable("Unknown condition code!");
1136 case ISD::SETNE: return ARMCC::NE;
1137 case ISD::SETEQ: return ARMCC::EQ;
1138 case ISD::SETGT: return ARMCC::GT;
1139 case ISD::SETGE: return ARMCC::GE;
1140 case ISD::SETLT: return ARMCC::LT;
1141 case ISD::SETLE: return ARMCC::LE;
1142 case ISD::SETUGT: return ARMCC::HI;
1143 case ISD::SETUGE: return ARMCC::HS;
1144 case ISD::SETULT: return ARMCC::LO;
1145 case ISD::SETULE: return ARMCC::LS;
1149 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1150 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1151 ARMCC::CondCodes &CondCode2) {
1152 CondCode2 = ARMCC::AL;
1154 default: llvm_unreachable("Unknown FP condition!");
1156 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1158 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1160 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1161 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1162 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1163 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1164 case ISD::SETO: CondCode = ARMCC::VC; break;
1165 case ISD::SETUO: CondCode = ARMCC::VS; break;
1166 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1167 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1168 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1170 case ISD::SETULT: CondCode = ARMCC::LT; break;
1172 case ISD::SETULE: CondCode = ARMCC::LE; break;
1174 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1178 //===----------------------------------------------------------------------===//
1179 // Calling Convention Implementation
1180 //===----------------------------------------------------------------------===//
1182 #include "ARMGenCallingConv.inc"
1184 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1185 /// account presence of floating point hardware and calling convention
1186 /// limitations, such as support for variadic functions.
1188 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1189 bool isVarArg) const {
1192 llvm_unreachable("Unsupported calling convention");
1193 case CallingConv::ARM_AAPCS:
1194 case CallingConv::ARM_APCS:
1195 case CallingConv::GHC:
1197 case CallingConv::ARM_AAPCS_VFP:
1198 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1199 case CallingConv::C:
1200 if (!Subtarget->isAAPCS_ABI())
1201 return CallingConv::ARM_APCS;
1202 else if (Subtarget->hasVFP2() &&
1203 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1205 return CallingConv::ARM_AAPCS_VFP;
1207 return CallingConv::ARM_AAPCS;
1208 case CallingConv::Fast:
1209 if (!Subtarget->isAAPCS_ABI()) {
1210 if (Subtarget->hasVFP2() && !isVarArg)
1211 return CallingConv::Fast;
1212 return CallingConv::ARM_APCS;
1213 } else if (Subtarget->hasVFP2() && !isVarArg)
1214 return CallingConv::ARM_AAPCS_VFP;
1216 return CallingConv::ARM_AAPCS;
1220 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1221 /// CallingConvention.
1222 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1224 bool isVarArg) const {
1225 switch (getEffectiveCallingConv(CC, isVarArg)) {
1227 llvm_unreachable("Unsupported calling convention");
1228 case CallingConv::ARM_APCS:
1229 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1230 case CallingConv::ARM_AAPCS:
1231 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1232 case CallingConv::ARM_AAPCS_VFP:
1233 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1234 case CallingConv::Fast:
1235 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1236 case CallingConv::GHC:
1237 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1241 /// LowerCallResult - Lower the result values of a call into the
1242 /// appropriate copies out of appropriate physical registers.
1244 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1245 CallingConv::ID CallConv, bool isVarArg,
1246 const SmallVectorImpl<ISD::InputArg> &Ins,
1247 SDLoc dl, SelectionDAG &DAG,
1248 SmallVectorImpl<SDValue> &InVals,
1249 bool isThisReturn, SDValue ThisVal) const {
1251 // Assign locations to each value returned by this call.
1252 SmallVector<CCValAssign, 16> RVLocs;
1253 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1254 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1255 CCInfo.AnalyzeCallResult(Ins,
1256 CCAssignFnForNode(CallConv, /* Return*/ true,
1259 // Copy all of the result registers out of their specified physreg.
1260 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1261 CCValAssign VA = RVLocs[i];
1263 // Pass 'this' value directly from the argument to return value, to avoid
1264 // reg unit interference
1265 if (i == 0 && isThisReturn) {
1266 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1267 "unexpected return calling convention register assignment");
1268 InVals.push_back(ThisVal);
1273 if (VA.needsCustom()) {
1274 // Handle f64 or half of a v2f64.
1275 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1277 Chain = Lo.getValue(1);
1278 InFlag = Lo.getValue(2);
1279 VA = RVLocs[++i]; // skip ahead to next loc
1280 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1282 Chain = Hi.getValue(1);
1283 InFlag = Hi.getValue(2);
1284 if (!Subtarget->isLittle())
1286 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1288 if (VA.getLocVT() == MVT::v2f64) {
1289 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1290 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1291 DAG.getConstant(0, MVT::i32));
1293 VA = RVLocs[++i]; // skip ahead to next loc
1294 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1295 Chain = Lo.getValue(1);
1296 InFlag = Lo.getValue(2);
1297 VA = RVLocs[++i]; // skip ahead to next loc
1298 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1299 Chain = Hi.getValue(1);
1300 InFlag = Hi.getValue(2);
1301 if (!Subtarget->isLittle())
1303 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1304 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1305 DAG.getConstant(1, MVT::i32));
1308 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1310 Chain = Val.getValue(1);
1311 InFlag = Val.getValue(2);
1314 switch (VA.getLocInfo()) {
1315 default: llvm_unreachable("Unknown loc info!");
1316 case CCValAssign::Full: break;
1317 case CCValAssign::BCvt:
1318 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1322 InVals.push_back(Val);
1328 /// LowerMemOpCallTo - Store the argument to the stack.
1330 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1331 SDValue StackPtr, SDValue Arg,
1332 SDLoc dl, SelectionDAG &DAG,
1333 const CCValAssign &VA,
1334 ISD::ArgFlagsTy Flags) const {
1335 unsigned LocMemOffset = VA.getLocMemOffset();
1336 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1337 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1338 return DAG.getStore(Chain, dl, Arg, PtrOff,
1339 MachinePointerInfo::getStack(LocMemOffset),
1343 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1344 SDValue Chain, SDValue &Arg,
1345 RegsToPassVector &RegsToPass,
1346 CCValAssign &VA, CCValAssign &NextVA,
1348 SmallVectorImpl<SDValue> &MemOpChains,
1349 ISD::ArgFlagsTy Flags) const {
1351 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1352 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1353 unsigned id = Subtarget->isLittle() ? 0 : 1;
1354 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1356 if (NextVA.isRegLoc())
1357 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1359 assert(NextVA.isMemLoc());
1360 if (!StackPtr.getNode())
1361 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1363 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1369 /// LowerCall - Lowering a call into a callseq_start <-
1370 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1373 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1374 SmallVectorImpl<SDValue> &InVals) const {
1375 SelectionDAG &DAG = CLI.DAG;
1377 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1378 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1379 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1380 SDValue Chain = CLI.Chain;
1381 SDValue Callee = CLI.Callee;
1382 bool &isTailCall = CLI.IsTailCall;
1383 CallingConv::ID CallConv = CLI.CallConv;
1384 bool doesNotRet = CLI.DoesNotReturn;
1385 bool isVarArg = CLI.IsVarArg;
1387 MachineFunction &MF = DAG.getMachineFunction();
1388 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1389 bool isThisReturn = false;
1390 bool isSibCall = false;
1392 // Disable tail calls if they're not supported.
1393 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1397 // Check if it's really possible to do a tail call.
1398 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1399 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1400 Outs, OutVals, Ins, DAG);
1401 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1402 report_fatal_error("failed to perform tail call elimination on a call "
1403 "site marked musttail");
1404 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1405 // detected sibcalls.
1412 // Analyze operands of the call, assigning locations to each operand.
1413 SmallVector<CCValAssign, 16> ArgLocs;
1414 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1415 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1416 CCInfo.AnalyzeCallOperands(Outs,
1417 CCAssignFnForNode(CallConv, /* Return*/ false,
1420 // Get a count of how many bytes are to be pushed on the stack.
1421 unsigned NumBytes = CCInfo.getNextStackOffset();
1423 // For tail calls, memory operands are available in our caller's stack.
1427 // Adjust the stack pointer for the new arguments...
1428 // These operations are automatically eliminated by the prolog/epilog pass
1430 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1433 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1435 RegsToPassVector RegsToPass;
1436 SmallVector<SDValue, 8> MemOpChains;
1438 // Walk the register/memloc assignments, inserting copies/loads. In the case
1439 // of tail call optimization, arguments are handled later.
1440 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1442 ++i, ++realArgIdx) {
1443 CCValAssign &VA = ArgLocs[i];
1444 SDValue Arg = OutVals[realArgIdx];
1445 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1446 bool isByVal = Flags.isByVal();
1448 // Promote the value if needed.
1449 switch (VA.getLocInfo()) {
1450 default: llvm_unreachable("Unknown loc info!");
1451 case CCValAssign::Full: break;
1452 case CCValAssign::SExt:
1453 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1455 case CCValAssign::ZExt:
1456 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1458 case CCValAssign::AExt:
1459 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1461 case CCValAssign::BCvt:
1462 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1466 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1467 if (VA.needsCustom()) {
1468 if (VA.getLocVT() == MVT::v2f64) {
1469 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1470 DAG.getConstant(0, MVT::i32));
1471 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1472 DAG.getConstant(1, MVT::i32));
1474 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1475 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1477 VA = ArgLocs[++i]; // skip ahead to next loc
1478 if (VA.isRegLoc()) {
1479 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1480 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1482 assert(VA.isMemLoc());
1484 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1485 dl, DAG, VA, Flags));
1488 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1489 StackPtr, MemOpChains, Flags);
1491 } else if (VA.isRegLoc()) {
1492 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1493 assert(VA.getLocVT() == MVT::i32 &&
1494 "unexpected calling convention register assignment");
1495 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1496 "unexpected use of 'returned'");
1497 isThisReturn = true;
1499 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1500 } else if (isByVal) {
1501 assert(VA.isMemLoc());
1502 unsigned offset = 0;
1504 // True if this byval aggregate will be split between registers
1506 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1507 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1509 if (CurByValIdx < ByValArgsCount) {
1511 unsigned RegBegin, RegEnd;
1512 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1514 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1516 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1517 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1518 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1519 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1520 MachinePointerInfo(),
1521 false, false, false,
1522 DAG.InferPtrAlignment(AddArg));
1523 MemOpChains.push_back(Load.getValue(1));
1524 RegsToPass.push_back(std::make_pair(j, Load));
1527 // If parameter size outsides register area, "offset" value
1528 // helps us to calculate stack slot for remained part properly.
1529 offset = RegEnd - RegBegin;
1531 CCInfo.nextInRegsParam();
1534 if (Flags.getByValSize() > 4*offset) {
1535 unsigned LocMemOffset = VA.getLocMemOffset();
1536 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1537 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1539 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1540 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1541 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1543 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1545 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1546 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1547 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1550 } else if (!isSibCall) {
1551 assert(VA.isMemLoc());
1553 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1554 dl, DAG, VA, Flags));
1558 if (!MemOpChains.empty())
1559 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1561 // Build a sequence of copy-to-reg nodes chained together with token chain
1562 // and flag operands which copy the outgoing args into the appropriate regs.
1564 // Tail call byval lowering might overwrite argument registers so in case of
1565 // tail call optimization the copies to registers are lowered later.
1567 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1568 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1569 RegsToPass[i].second, InFlag);
1570 InFlag = Chain.getValue(1);
1573 // For tail calls lower the arguments to the 'real' stack slot.
1575 // Force all the incoming stack arguments to be loaded from the stack
1576 // before any new outgoing arguments are stored to the stack, because the
1577 // outgoing stack slots may alias the incoming argument stack slots, and
1578 // the alias isn't otherwise explicit. This is slightly more conservative
1579 // than necessary, because it means that each store effectively depends
1580 // on every argument instead of just those arguments it would clobber.
1582 // Do not flag preceding copytoreg stuff together with the following stuff.
1584 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1585 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1586 RegsToPass[i].second, InFlag);
1587 InFlag = Chain.getValue(1);
1592 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1593 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1594 // node so that legalize doesn't hack it.
1595 bool isDirect = false;
1596 bool isARMFunc = false;
1597 bool isLocalARMFunc = false;
1598 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1600 if (EnableARMLongCalls) {
1601 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1602 && "long-calls with non-static relocation model!");
1603 // Handle a global address or an external symbol. If it's not one of
1604 // those, the target's already in a register, so we don't need to do
1606 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1607 const GlobalValue *GV = G->getGlobal();
1608 // Create a constant pool entry for the callee address
1609 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1610 ARMConstantPoolValue *CPV =
1611 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1613 // Get the address of the callee into a register
1614 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1615 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1616 Callee = DAG.getLoad(getPointerTy(), dl,
1617 DAG.getEntryNode(), CPAddr,
1618 MachinePointerInfo::getConstantPool(),
1619 false, false, false, 0);
1620 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1621 const char *Sym = S->getSymbol();
1623 // Create a constant pool entry for the callee address
1624 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1625 ARMConstantPoolValue *CPV =
1626 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1627 ARMPCLabelIndex, 0);
1628 // Get the address of the callee into a register
1629 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1630 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1631 Callee = DAG.getLoad(getPointerTy(), dl,
1632 DAG.getEntryNode(), CPAddr,
1633 MachinePointerInfo::getConstantPool(),
1634 false, false, false, 0);
1636 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1637 const GlobalValue *GV = G->getGlobal();
1639 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1640 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1641 getTargetMachine().getRelocationModel() != Reloc::Static;
1642 isARMFunc = !Subtarget->isThumb() || isStub;
1643 // ARM call to a local ARM function is predicable.
1644 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1645 // tBX takes a register source operand.
1646 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1647 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1648 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1649 DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1651 // On ELF targets for PIC code, direct calls should go through the PLT
1652 unsigned OpFlags = 0;
1653 if (Subtarget->isTargetELF() &&
1654 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1655 OpFlags = ARMII::MO_PLT;
1656 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1658 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1660 bool isStub = Subtarget->isTargetMachO() &&
1661 getTargetMachine().getRelocationModel() != Reloc::Static;
1662 isARMFunc = !Subtarget->isThumb() || isStub;
1663 // tBX takes a register source operand.
1664 const char *Sym = S->getSymbol();
1665 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1666 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1667 ARMConstantPoolValue *CPV =
1668 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1669 ARMPCLabelIndex, 4);
1670 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1671 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1672 Callee = DAG.getLoad(getPointerTy(), dl,
1673 DAG.getEntryNode(), CPAddr,
1674 MachinePointerInfo::getConstantPool(),
1675 false, false, false, 0);
1676 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1677 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1678 getPointerTy(), Callee, PICLabel);
1680 unsigned OpFlags = 0;
1681 // On ELF targets for PIC code, direct calls should go through the PLT
1682 if (Subtarget->isTargetELF() &&
1683 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1684 OpFlags = ARMII::MO_PLT;
1685 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1689 // FIXME: handle tail calls differently.
1691 bool HasMinSizeAttr = Subtarget->isMinSize();
1692 if (Subtarget->isThumb()) {
1693 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1694 CallOpc = ARMISD::CALL_NOLINK;
1696 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1698 if (!isDirect && !Subtarget->hasV5TOps())
1699 CallOpc = ARMISD::CALL_NOLINK;
1700 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1701 // Emit regular call when code size is the priority
1703 // "mov lr, pc; b _foo" to avoid confusing the RSP
1704 CallOpc = ARMISD::CALL_NOLINK;
1706 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1709 std::vector<SDValue> Ops;
1710 Ops.push_back(Chain);
1711 Ops.push_back(Callee);
1713 // Add argument registers to the end of the list so that they are known live
1715 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1716 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1717 RegsToPass[i].second.getValueType()));
1719 // Add a register mask operand representing the call-preserved registers.
1721 const uint32_t *Mask;
1722 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1723 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1725 // For 'this' returns, use the R0-preserving mask if applicable
1726 Mask = ARI->getThisReturnPreservedMask(CallConv);
1728 // Set isThisReturn to false if the calling convention is not one that
1729 // allows 'returned' to be modeled in this way, so LowerCallResult does
1730 // not try to pass 'this' straight through
1731 isThisReturn = false;
1732 Mask = ARI->getCallPreservedMask(CallConv);
1735 Mask = ARI->getCallPreservedMask(CallConv);
1737 assert(Mask && "Missing call preserved mask for calling convention");
1738 Ops.push_back(DAG.getRegisterMask(Mask));
1741 if (InFlag.getNode())
1742 Ops.push_back(InFlag);
1744 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1746 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1748 // Returns a chain and a flag for retval copy to use.
1749 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1750 InFlag = Chain.getValue(1);
1752 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1753 DAG.getIntPtrConstant(0, true), InFlag, dl);
1755 InFlag = Chain.getValue(1);
1757 // Handle result values, copying them out of physregs into vregs that we
1759 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1760 InVals, isThisReturn,
1761 isThisReturn ? OutVals[0] : SDValue());
1764 /// HandleByVal - Every parameter *after* a byval parameter is passed
1765 /// on the stack. Remember the next parameter register to allocate,
1766 /// and then confiscate the rest of the parameter registers to insure
1769 ARMTargetLowering::HandleByVal(
1770 CCState *State, unsigned &size, unsigned Align) const {
1771 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1772 assert((State->getCallOrPrologue() == Prologue ||
1773 State->getCallOrPrologue() == Call) &&
1774 "unhandled ParmContext");
1776 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1777 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1778 unsigned AlignInRegs = Align / 4;
1779 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1780 for (unsigned i = 0; i < Waste; ++i)
1781 reg = State->AllocateReg(GPRArgRegs, 4);
1784 unsigned excess = 4 * (ARM::R4 - reg);
1786 // Special case when NSAA != SP and parameter size greater than size of
1787 // all remained GPR regs. In that case we can't split parameter, we must
1788 // send it to stack. We also must set NCRN to R4, so waste all
1789 // remained registers.
1790 const unsigned NSAAOffset = State->getNextStackOffset();
1791 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1792 while (State->AllocateReg(GPRArgRegs, 4))
1797 // First register for byval parameter is the first register that wasn't
1798 // allocated before this method call, so it would be "reg".
1799 // If parameter is small enough to be saved in range [reg, r4), then
1800 // the end (first after last) register would be reg + param-size-in-regs,
1801 // else parameter would be splitted between registers and stack,
1802 // end register would be r4 in this case.
1803 unsigned ByValRegBegin = reg;
1804 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1805 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1806 // Note, first register is allocated in the beginning of function already,
1807 // allocate remained amount of registers we need.
1808 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1809 State->AllocateReg(GPRArgRegs, 4);
1810 // A byval parameter that is split between registers and memory needs its
1811 // size truncated here.
1812 // In the case where the entire structure fits in registers, we set the
1813 // size in memory to zero.
1822 /// MatchingStackOffset - Return true if the given stack call argument is
1823 /// already available in the same position (relatively) of the caller's
1824 /// incoming argument stack.
1826 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1827 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1828 const TargetInstrInfo *TII) {
1829 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1831 if (Arg.getOpcode() == ISD::CopyFromReg) {
1832 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1833 if (!TargetRegisterInfo::isVirtualRegister(VR))
1835 MachineInstr *Def = MRI->getVRegDef(VR);
1838 if (!Flags.isByVal()) {
1839 if (!TII->isLoadFromStackSlot(Def, FI))
1844 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1845 if (Flags.isByVal())
1846 // ByVal argument is passed in as a pointer but it's now being
1847 // dereferenced. e.g.
1848 // define @foo(%struct.X* %A) {
1849 // tail call @bar(%struct.X* byval %A)
1852 SDValue Ptr = Ld->getBasePtr();
1853 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1856 FI = FINode->getIndex();
1860 assert(FI != INT_MAX);
1861 if (!MFI->isFixedObjectIndex(FI))
1863 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1866 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1867 /// for tail call optimization. Targets which want to do tail call
1868 /// optimization should implement this function.
1870 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1871 CallingConv::ID CalleeCC,
1873 bool isCalleeStructRet,
1874 bool isCallerStructRet,
1875 const SmallVectorImpl<ISD::OutputArg> &Outs,
1876 const SmallVectorImpl<SDValue> &OutVals,
1877 const SmallVectorImpl<ISD::InputArg> &Ins,
1878 SelectionDAG& DAG) const {
1879 const Function *CallerF = DAG.getMachineFunction().getFunction();
1880 CallingConv::ID CallerCC = CallerF->getCallingConv();
1881 bool CCMatch = CallerCC == CalleeCC;
1883 // Look for obvious safe cases to perform tail call optimization that do not
1884 // require ABI changes. This is what gcc calls sibcall.
1886 // Do not sibcall optimize vararg calls unless the call site is not passing
1888 if (isVarArg && !Outs.empty())
1891 // Exception-handling functions need a special set of instructions to indicate
1892 // a return to the hardware. Tail-calling another function would probably
1894 if (CallerF->hasFnAttribute("interrupt"))
1897 // Also avoid sibcall optimization if either caller or callee uses struct
1898 // return semantics.
1899 if (isCalleeStructRet || isCallerStructRet)
1902 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1903 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1904 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1905 // support in the assembler and linker to be used. This would need to be
1906 // fixed to fully support tail calls in Thumb1.
1908 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1909 // LR. This means if we need to reload LR, it takes an extra instructions,
1910 // which outweighs the value of the tail call; but here we don't know yet
1911 // whether LR is going to be used. Probably the right approach is to
1912 // generate the tail call here and turn it back into CALL/RET in
1913 // emitEpilogue if LR is used.
1915 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1916 // but we need to make sure there are enough registers; the only valid
1917 // registers are the 4 used for parameters. We don't currently do this
1919 if (Subtarget->isThumb1Only())
1922 // If the calling conventions do not match, then we'd better make sure the
1923 // results are returned in the same way as what the caller expects.
1925 SmallVector<CCValAssign, 16> RVLocs1;
1926 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1927 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1928 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1930 SmallVector<CCValAssign, 16> RVLocs2;
1931 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1932 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1933 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1935 if (RVLocs1.size() != RVLocs2.size())
1937 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1938 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1940 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1942 if (RVLocs1[i].isRegLoc()) {
1943 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1946 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1952 // If Caller's vararg or byval argument has been split between registers and
1953 // stack, do not perform tail call, since part of the argument is in caller's
1955 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1956 getInfo<ARMFunctionInfo>();
1957 if (AFI_Caller->getArgRegsSaveSize())
1960 // If the callee takes no arguments then go on to check the results of the
1962 if (!Outs.empty()) {
1963 // Check if stack adjustment is needed. For now, do not do this if any
1964 // argument is passed on the stack.
1965 SmallVector<CCValAssign, 16> ArgLocs;
1966 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1967 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1968 CCInfo.AnalyzeCallOperands(Outs,
1969 CCAssignFnForNode(CalleeCC, false, isVarArg));
1970 if (CCInfo.getNextStackOffset()) {
1971 MachineFunction &MF = DAG.getMachineFunction();
1973 // Check if the arguments are already laid out in the right way as
1974 // the caller's fixed stack objects.
1975 MachineFrameInfo *MFI = MF.getFrameInfo();
1976 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1977 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1978 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1980 ++i, ++realArgIdx) {
1981 CCValAssign &VA = ArgLocs[i];
1982 EVT RegVT = VA.getLocVT();
1983 SDValue Arg = OutVals[realArgIdx];
1984 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1985 if (VA.getLocInfo() == CCValAssign::Indirect)
1987 if (VA.needsCustom()) {
1988 // f64 and vector types are split into multiple registers or
1989 // register/stack-slot combinations. The types will not match
1990 // the registers; give up on memory f64 refs until we figure
1991 // out what to do about this.
1994 if (!ArgLocs[++i].isRegLoc())
1996 if (RegVT == MVT::v2f64) {
1997 if (!ArgLocs[++i].isRegLoc())
1999 if (!ArgLocs[++i].isRegLoc())
2002 } else if (!VA.isRegLoc()) {
2003 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2015 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2016 MachineFunction &MF, bool isVarArg,
2017 const SmallVectorImpl<ISD::OutputArg> &Outs,
2018 LLVMContext &Context) const {
2019 SmallVector<CCValAssign, 16> RVLocs;
2020 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2021 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2025 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2026 SDLoc DL, SelectionDAG &DAG) {
2027 const MachineFunction &MF = DAG.getMachineFunction();
2028 const Function *F = MF.getFunction();
2030 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2032 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2033 // version of the "preferred return address". These offsets affect the return
2034 // instruction if this is a return from PL1 without hypervisor extensions.
2035 // IRQ/FIQ: +4 "subs pc, lr, #4"
2036 // SWI: 0 "subs pc, lr, #0"
2037 // ABORT: +4 "subs pc, lr, #4"
2038 // UNDEF: +4/+2 "subs pc, lr, #0"
2039 // UNDEF varies depending on where the exception came from ARM or Thumb
2040 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2043 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2046 else if (IntKind == "SWI" || IntKind == "UNDEF")
2049 report_fatal_error("Unsupported interrupt attribute. If present, value "
2050 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2052 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2054 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2058 ARMTargetLowering::LowerReturn(SDValue Chain,
2059 CallingConv::ID CallConv, bool isVarArg,
2060 const SmallVectorImpl<ISD::OutputArg> &Outs,
2061 const SmallVectorImpl<SDValue> &OutVals,
2062 SDLoc dl, SelectionDAG &DAG) const {
2064 // CCValAssign - represent the assignment of the return value to a location.
2065 SmallVector<CCValAssign, 16> RVLocs;
2067 // CCState - Info about the registers and stack slots.
2068 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2069 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2071 // Analyze outgoing return values.
2072 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2076 SmallVector<SDValue, 4> RetOps;
2077 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2078 bool isLittleEndian = Subtarget->isLittle();
2080 // Copy the result values into the output registers.
2081 for (unsigned i = 0, realRVLocIdx = 0;
2083 ++i, ++realRVLocIdx) {
2084 CCValAssign &VA = RVLocs[i];
2085 assert(VA.isRegLoc() && "Can only return in registers!");
2087 SDValue Arg = OutVals[realRVLocIdx];
2089 switch (VA.getLocInfo()) {
2090 default: llvm_unreachable("Unknown loc info!");
2091 case CCValAssign::Full: break;
2092 case CCValAssign::BCvt:
2093 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2097 if (VA.needsCustom()) {
2098 if (VA.getLocVT() == MVT::v2f64) {
2099 // Extract the first half and return it in two registers.
2100 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2101 DAG.getConstant(0, MVT::i32));
2102 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2103 DAG.getVTList(MVT::i32, MVT::i32), Half);
2105 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2106 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2108 Flag = Chain.getValue(1);
2109 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2110 VA = RVLocs[++i]; // skip ahead to next loc
2111 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2112 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2114 Flag = Chain.getValue(1);
2115 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2116 VA = RVLocs[++i]; // skip ahead to next loc
2118 // Extract the 2nd half and fall through to handle it as an f64 value.
2119 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2120 DAG.getConstant(1, MVT::i32));
2122 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2124 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2125 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2126 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2127 fmrrd.getValue(isLittleEndian ? 0 : 1),
2129 Flag = Chain.getValue(1);
2130 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2131 VA = RVLocs[++i]; // skip ahead to next loc
2132 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2133 fmrrd.getValue(isLittleEndian ? 1 : 0),
2136 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2138 // Guarantee that all emitted copies are
2139 // stuck together, avoiding something bad.
2140 Flag = Chain.getValue(1);
2141 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2144 // Update chain and glue.
2147 RetOps.push_back(Flag);
2149 // CPUs which aren't M-class use a special sequence to return from
2150 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2151 // though we use "subs pc, lr, #N").
2153 // M-class CPUs actually use a normal return sequence with a special
2154 // (hardware-provided) value in LR, so the normal code path works.
2155 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2156 !Subtarget->isMClass()) {
2157 if (Subtarget->isThumb1Only())
2158 report_fatal_error("interrupt attribute is not supported in Thumb1");
2159 return LowerInterruptReturn(RetOps, dl, DAG);
2162 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2165 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2166 if (N->getNumValues() != 1)
2168 if (!N->hasNUsesOfValue(1, 0))
2171 SDValue TCChain = Chain;
2172 SDNode *Copy = *N->use_begin();
2173 if (Copy->getOpcode() == ISD::CopyToReg) {
2174 // If the copy has a glue operand, we conservatively assume it isn't safe to
2175 // perform a tail call.
2176 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2178 TCChain = Copy->getOperand(0);
2179 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2180 SDNode *VMov = Copy;
2181 // f64 returned in a pair of GPRs.
2182 SmallPtrSet<SDNode*, 2> Copies;
2183 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2185 if (UI->getOpcode() != ISD::CopyToReg)
2189 if (Copies.size() > 2)
2192 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2194 SDValue UseChain = UI->getOperand(0);
2195 if (Copies.count(UseChain.getNode()))
2202 } else if (Copy->getOpcode() == ISD::BITCAST) {
2203 // f32 returned in a single GPR.
2204 if (!Copy->hasOneUse())
2206 Copy = *Copy->use_begin();
2207 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2209 TCChain = Copy->getOperand(0);
2214 bool HasRet = false;
2215 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2217 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2218 UI->getOpcode() != ARMISD::INTRET_FLAG)
2230 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2231 if (!Subtarget->supportsTailCall())
2234 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2237 return !Subtarget->isThumb1Only();
2240 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2241 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2242 // one of the above mentioned nodes. It has to be wrapped because otherwise
2243 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2244 // be used to form addressing mode. These wrapped nodes will be selected
2246 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2247 EVT PtrVT = Op.getValueType();
2248 // FIXME there is no actual debug info here
2250 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2252 if (CP->isMachineConstantPoolEntry())
2253 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2254 CP->getAlignment());
2256 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2257 CP->getAlignment());
2258 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2261 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2262 return MachineJumpTableInfo::EK_Inline;
2265 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2266 SelectionDAG &DAG) const {
2267 MachineFunction &MF = DAG.getMachineFunction();
2268 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2269 unsigned ARMPCLabelIndex = 0;
2271 EVT PtrVT = getPointerTy();
2272 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2273 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2275 if (RelocM == Reloc::Static) {
2276 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2278 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2279 ARMPCLabelIndex = AFI->createPICLabelUId();
2280 ARMConstantPoolValue *CPV =
2281 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2282 ARMCP::CPBlockAddress, PCAdj);
2283 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2285 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2286 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2287 MachinePointerInfo::getConstantPool(),
2288 false, false, false, 0);
2289 if (RelocM == Reloc::Static)
2291 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2292 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2295 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2297 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2298 SelectionDAG &DAG) const {
2300 EVT PtrVT = getPointerTy();
2301 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2302 MachineFunction &MF = DAG.getMachineFunction();
2303 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2304 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2305 ARMConstantPoolValue *CPV =
2306 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2307 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2308 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2309 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2310 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2311 MachinePointerInfo::getConstantPool(),
2312 false, false, false, 0);
2313 SDValue Chain = Argument.getValue(1);
2315 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2316 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2318 // call __tls_get_addr.
2321 Entry.Node = Argument;
2322 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2323 Args.push_back(Entry);
2325 // FIXME: is there useful debug info available here?
2326 TargetLowering::CallLoweringInfo CLI(DAG);
2327 CLI.setDebugLoc(dl).setChain(Chain)
2328 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2329 DAG.getExternalSymbol("__tls_get_addr", PtrVT), &Args, 0);
2331 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2332 return CallResult.first;
2335 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2336 // "local exec" model.
2338 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2340 TLSModel::Model model) const {
2341 const GlobalValue *GV = GA->getGlobal();
2344 SDValue Chain = DAG.getEntryNode();
2345 EVT PtrVT = getPointerTy();
2346 // Get the Thread Pointer
2347 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2349 if (model == TLSModel::InitialExec) {
2350 MachineFunction &MF = DAG.getMachineFunction();
2351 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2352 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2353 // Initial exec model.
2354 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2355 ARMConstantPoolValue *CPV =
2356 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2357 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2359 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2360 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2361 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2362 MachinePointerInfo::getConstantPool(),
2363 false, false, false, 0);
2364 Chain = Offset.getValue(1);
2366 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2367 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2369 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2370 MachinePointerInfo::getConstantPool(),
2371 false, false, false, 0);
2374 assert(model == TLSModel::LocalExec);
2375 ARMConstantPoolValue *CPV =
2376 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2377 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2378 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2379 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2380 MachinePointerInfo::getConstantPool(),
2381 false, false, false, 0);
2384 // The address of the thread local variable is the add of the thread
2385 // pointer with the offset of the variable.
2386 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2390 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2391 // TODO: implement the "local dynamic" model
2392 assert(Subtarget->isTargetELF() &&
2393 "TLS not implemented for non-ELF targets");
2394 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2396 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2399 case TLSModel::GeneralDynamic:
2400 case TLSModel::LocalDynamic:
2401 return LowerToTLSGeneralDynamicModel(GA, DAG);
2402 case TLSModel::InitialExec:
2403 case TLSModel::LocalExec:
2404 return LowerToTLSExecModels(GA, DAG, model);
2406 llvm_unreachable("bogus TLS model");
2409 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2410 SelectionDAG &DAG) const {
2411 EVT PtrVT = getPointerTy();
2413 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2414 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2415 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2416 ARMConstantPoolValue *CPV =
2417 ARMConstantPoolConstant::Create(GV,
2418 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2419 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2420 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2421 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2423 MachinePointerInfo::getConstantPool(),
2424 false, false, false, 0);
2425 SDValue Chain = Result.getValue(1);
2426 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2427 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2429 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2430 MachinePointerInfo::getGOT(),
2431 false, false, false, 0);
2435 // If we have T2 ops, we can materialize the address directly via movt/movw
2436 // pair. This is always cheaper.
2437 if (Subtarget->useMovt()) {
2439 // FIXME: Once remat is capable of dealing with instructions with register
2440 // operands, expand this into two nodes.
2441 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2442 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2444 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2445 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2446 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2447 MachinePointerInfo::getConstantPool(),
2448 false, false, false, 0);
2452 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2453 SelectionDAG &DAG) const {
2454 EVT PtrVT = getPointerTy();
2456 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2457 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2459 if (Subtarget->useMovt())
2462 // FIXME: Once remat is capable of dealing with instructions with register
2463 // operands, expand this into multiple nodes
2465 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2467 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2468 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2470 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2471 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2472 MachinePointerInfo::getGOT(), false, false, false, 0);
2476 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2477 SelectionDAG &DAG) const {
2478 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2479 assert(Subtarget->useMovt() && "Windows on ARM expects to use movw/movt");
2481 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2482 EVT PtrVT = getPointerTy();
2487 // FIXME: Once remat is capable of dealing with instructions with register
2488 // operands, expand this into two nodes.
2489 return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2490 DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2493 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2494 SelectionDAG &DAG) const {
2495 assert(Subtarget->isTargetELF() &&
2496 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2497 MachineFunction &MF = DAG.getMachineFunction();
2498 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2499 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2500 EVT PtrVT = getPointerTy();
2502 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2503 ARMConstantPoolValue *CPV =
2504 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2505 ARMPCLabelIndex, PCAdj);
2506 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2507 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2508 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2509 MachinePointerInfo::getConstantPool(),
2510 false, false, false, 0);
2511 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2512 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2516 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2518 SDValue Val = DAG.getConstant(0, MVT::i32);
2519 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2520 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2521 Op.getOperand(1), Val);
2525 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2527 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2528 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2532 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2533 const ARMSubtarget *Subtarget) const {
2534 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2537 default: return SDValue(); // Don't custom lower most intrinsics.
2538 case Intrinsic::arm_thread_pointer: {
2539 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2540 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2542 case Intrinsic::eh_sjlj_lsda: {
2543 MachineFunction &MF = DAG.getMachineFunction();
2544 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2545 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2546 EVT PtrVT = getPointerTy();
2547 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2549 unsigned PCAdj = (RelocM != Reloc::PIC_)
2550 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2551 ARMConstantPoolValue *CPV =
2552 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2553 ARMCP::CPLSDA, PCAdj);
2554 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2555 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2557 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2558 MachinePointerInfo::getConstantPool(),
2559 false, false, false, 0);
2561 if (RelocM == Reloc::PIC_) {
2562 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2563 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2567 case Intrinsic::arm_neon_vmulls:
2568 case Intrinsic::arm_neon_vmullu: {
2569 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2570 ? ARMISD::VMULLs : ARMISD::VMULLu;
2571 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2572 Op.getOperand(1), Op.getOperand(2));
2577 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2578 const ARMSubtarget *Subtarget) {
2579 // FIXME: handle "fence singlethread" more efficiently.
2581 if (!Subtarget->hasDataBarrier()) {
2582 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2583 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2585 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2586 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2587 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2588 DAG.getConstant(0, MVT::i32));
2591 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2592 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2593 unsigned Domain = ARM_MB::ISH;
2594 if (Subtarget->isMClass()) {
2595 // Only a full system barrier exists in the M-class architectures.
2596 Domain = ARM_MB::SY;
2597 } else if (Subtarget->isSwift() && Ord == Release) {
2598 // Swift happens to implement ISHST barriers in a way that's compatible with
2599 // Release semantics but weaker than ISH so we'd be fools not to use
2600 // it. Beware: other processors probably don't!
2601 Domain = ARM_MB::ISHST;
2604 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2605 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2606 DAG.getConstant(Domain, MVT::i32));
2609 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2610 const ARMSubtarget *Subtarget) {
2611 // ARM pre v5TE and Thumb1 does not have preload instructions.
2612 if (!(Subtarget->isThumb2() ||
2613 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2614 // Just preserve the chain.
2615 return Op.getOperand(0);
2618 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2620 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2621 // ARMv7 with MP extension has PLDW.
2622 return Op.getOperand(0);
2624 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2625 if (Subtarget->isThumb()) {
2627 isRead = ~isRead & 1;
2628 isData = ~isData & 1;
2631 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2632 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2633 DAG.getConstant(isData, MVT::i32));
2636 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2637 MachineFunction &MF = DAG.getMachineFunction();
2638 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2640 // vastart just stores the address of the VarArgsFrameIndex slot into the
2641 // memory location argument.
2643 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2644 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2645 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2646 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2647 MachinePointerInfo(SV), false, false, 0);
2651 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2652 SDValue &Root, SelectionDAG &DAG,
2654 MachineFunction &MF = DAG.getMachineFunction();
2655 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2657 const TargetRegisterClass *RC;
2658 if (AFI->isThumb1OnlyFunction())
2659 RC = &ARM::tGPRRegClass;
2661 RC = &ARM::GPRRegClass;
2663 // Transform the arguments stored in physical registers into virtual ones.
2664 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2665 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2668 if (NextVA.isMemLoc()) {
2669 MachineFrameInfo *MFI = MF.getFrameInfo();
2670 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2672 // Create load node to retrieve arguments from the stack.
2673 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2674 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2675 MachinePointerInfo::getFixedStack(FI),
2676 false, false, false, 0);
2678 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2679 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2681 if (!Subtarget->isLittle())
2682 std::swap (ArgValue, ArgValue2);
2683 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2687 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2688 unsigned InRegsParamRecordIdx,
2690 unsigned &ArgRegsSize,
2691 unsigned &ArgRegsSaveSize)
2694 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2695 unsigned RBegin, REnd;
2696 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2697 NumGPRs = REnd - RBegin;
2699 unsigned int firstUnalloced;
2700 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2701 sizeof(GPRArgRegs) /
2702 sizeof(GPRArgRegs[0]));
2703 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2706 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2707 ArgRegsSize = NumGPRs * 4;
2709 // If parameter is split between stack and GPRs...
2710 if (NumGPRs && Align > 4 &&
2711 (ArgRegsSize < ArgSize ||
2712 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2713 // Add padding for part of param recovered from GPRs. For example,
2714 // if Align == 8, its last byte must be at address K*8 - 1.
2715 // We need to do it, since remained (stack) part of parameter has
2716 // stack alignment, and we need to "attach" "GPRs head" without gaps
2719 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2720 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2722 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2724 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2725 ArgRegsSaveSize = ArgRegsSize + Padding;
2727 // We don't need to extend regs save size for byval parameters if they
2728 // are passed via GPRs only.
2729 ArgRegsSaveSize = ArgRegsSize;
2732 // The remaining GPRs hold either the beginning of variable-argument
2733 // data, or the beginning of an aggregate passed by value (usually
2734 // byval). Either way, we allocate stack slots adjacent to the data
2735 // provided by our caller, and store the unallocated registers there.
2736 // If this is a variadic function, the va_list pointer will begin with
2737 // these values; otherwise, this reassembles a (byval) structure that
2738 // was split between registers and memory.
2739 // Return: The frame index registers were stored into.
2741 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2742 SDLoc dl, SDValue &Chain,
2743 const Value *OrigArg,
2744 unsigned InRegsParamRecordIdx,
2745 unsigned OffsetFromOrigArg,
2749 unsigned ByValStoreOffset,
2750 unsigned TotalArgRegsSaveSize) const {
2752 // Currently, two use-cases possible:
2753 // Case #1. Non-var-args function, and we meet first byval parameter.
2754 // Setup first unallocated register as first byval register;
2755 // eat all remained registers
2756 // (these two actions are performed by HandleByVal method).
2757 // Then, here, we initialize stack frame with
2758 // "store-reg" instructions.
2759 // Case #2. Var-args function, that doesn't contain byval parameters.
2760 // The same: eat all remained unallocated registers,
2761 // initialize stack frame.
2763 MachineFunction &MF = DAG.getMachineFunction();
2764 MachineFrameInfo *MFI = MF.getFrameInfo();
2765 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2766 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2767 unsigned RBegin, REnd;
2768 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2769 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2770 firstRegToSaveIndex = RBegin - ARM::R0;
2771 lastRegToSaveIndex = REnd - ARM::R0;
2773 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2774 (GPRArgRegs, array_lengthof(GPRArgRegs));
2775 lastRegToSaveIndex = 4;
2778 unsigned ArgRegsSize, ArgRegsSaveSize;
2779 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2780 ArgRegsSize, ArgRegsSaveSize);
2782 // Store any by-val regs to their spots on the stack so that they may be
2783 // loaded by deferencing the result of formal parameter pointer or va_next.
2784 // Note: once stack area for byval/varargs registers
2785 // was initialized, it can't be initialized again.
2786 if (ArgRegsSaveSize) {
2787 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2790 assert(AFI->getStoredByValParamsPadding() == 0 &&
2791 "The only parameter may be padded.");
2792 AFI->setStoredByValParamsPadding(Padding);
2795 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2798 (int64_t)TotalArgRegsSaveSize,
2800 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2802 MFI->CreateFixedObject(Padding,
2803 ArgOffset + ByValStoreOffset -
2804 (int64_t)ArgRegsSaveSize,
2808 SmallVector<SDValue, 4> MemOps;
2809 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2810 ++firstRegToSaveIndex, ++i) {
2811 const TargetRegisterClass *RC;
2812 if (AFI->isThumb1OnlyFunction())
2813 RC = &ARM::tGPRRegClass;
2815 RC = &ARM::GPRRegClass;
2817 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2818 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2820 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2821 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2823 MemOps.push_back(Store);
2824 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2825 DAG.getConstant(4, getPointerTy()));
2828 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2830 if (!MemOps.empty())
2831 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2835 // We cannot allocate a zero-byte object for the first variadic argument,
2836 // so just make up a size.
2839 // This will point to the next argument passed via stack.
2840 return MFI->CreateFixedObject(
2841 ArgSize, ArgOffset, !ForceMutable);
2845 // Setup stack frame, the va_list pointer will start from.
2847 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2848 SDLoc dl, SDValue &Chain,
2850 unsigned TotalArgRegsSaveSize,
2851 bool ForceMutable) const {
2852 MachineFunction &MF = DAG.getMachineFunction();
2853 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2855 // Try to store any remaining integer argument regs
2856 // to their spots on the stack so that they may be loaded by deferencing
2857 // the result of va_next.
2858 // If there is no regs to be stored, just point address after last
2859 // argument passed via stack.
2861 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2862 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2863 0, TotalArgRegsSaveSize);
2865 AFI->setVarArgsFrameIndex(FrameIndex);
2869 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2870 CallingConv::ID CallConv, bool isVarArg,
2871 const SmallVectorImpl<ISD::InputArg>
2873 SDLoc dl, SelectionDAG &DAG,
2874 SmallVectorImpl<SDValue> &InVals)
2876 MachineFunction &MF = DAG.getMachineFunction();
2877 MachineFrameInfo *MFI = MF.getFrameInfo();
2879 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2881 // Assign locations to all of the incoming arguments.
2882 SmallVector<CCValAssign, 16> ArgLocs;
2883 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2884 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2885 CCInfo.AnalyzeFormalArguments(Ins,
2886 CCAssignFnForNode(CallConv, /* Return*/ false,
2889 SmallVector<SDValue, 16> ArgValues;
2890 int lastInsIndex = -1;
2892 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2893 unsigned CurArgIdx = 0;
2895 // Initially ArgRegsSaveSize is zero.
2896 // Then we increase this value each time we meet byval parameter.
2897 // We also increase this value in case of varargs function.
2898 AFI->setArgRegsSaveSize(0);
2900 unsigned ByValStoreOffset = 0;
2901 unsigned TotalArgRegsSaveSize = 0;
2902 unsigned ArgRegsSaveSizeMaxAlign = 4;
2904 // Calculate the amount of stack space that we need to allocate to store
2905 // byval and variadic arguments that are passed in registers.
2906 // We need to know this before we allocate the first byval or variadic
2907 // argument, as they will be allocated a stack slot below the CFA (Canonical
2908 // Frame Address, the stack pointer at entry to the function).
2909 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2910 CCValAssign &VA = ArgLocs[i];
2911 if (VA.isMemLoc()) {
2912 int index = VA.getValNo();
2913 if (index != lastInsIndex) {
2914 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2915 if (Flags.isByVal()) {
2916 unsigned ExtraArgRegsSize;
2917 unsigned ExtraArgRegsSaveSize;
2918 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2919 Flags.getByValSize(),
2920 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2922 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2923 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2924 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2925 CCInfo.nextInRegsParam();
2927 lastInsIndex = index;
2931 CCInfo.rewindByValRegsInfo();
2934 unsigned ExtraArgRegsSize;
2935 unsigned ExtraArgRegsSaveSize;
2936 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2937 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2938 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2940 // If the arg regs save area contains N-byte aligned values, the
2941 // bottom of it must be at least N-byte aligned.
2942 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2943 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2945 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2946 CCValAssign &VA = ArgLocs[i];
2947 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2948 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2949 // Arguments stored in registers.
2950 if (VA.isRegLoc()) {
2951 EVT RegVT = VA.getLocVT();
2953 if (VA.needsCustom()) {
2954 // f64 and vector types are split up into multiple registers or
2955 // combinations of registers and stack slots.
2956 if (VA.getLocVT() == MVT::v2f64) {
2957 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2959 VA = ArgLocs[++i]; // skip ahead to next loc
2961 if (VA.isMemLoc()) {
2962 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2963 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2964 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2965 MachinePointerInfo::getFixedStack(FI),
2966 false, false, false, 0);
2968 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2971 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2972 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2973 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2974 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2975 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2977 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2980 const TargetRegisterClass *RC;
2982 if (RegVT == MVT::f32)
2983 RC = &ARM::SPRRegClass;
2984 else if (RegVT == MVT::f64)
2985 RC = &ARM::DPRRegClass;
2986 else if (RegVT == MVT::v2f64)
2987 RC = &ARM::QPRRegClass;
2988 else if (RegVT == MVT::i32)
2989 RC = AFI->isThumb1OnlyFunction() ?
2990 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2991 (const TargetRegisterClass*)&ARM::GPRRegClass;
2993 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2995 // Transform the arguments in physical registers into virtual ones.
2996 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2997 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3000 // If this is an 8 or 16-bit value, it is really passed promoted
3001 // to 32 bits. Insert an assert[sz]ext to capture this, then
3002 // truncate to the right size.
3003 switch (VA.getLocInfo()) {
3004 default: llvm_unreachable("Unknown loc info!");
3005 case CCValAssign::Full: break;
3006 case CCValAssign::BCvt:
3007 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3009 case CCValAssign::SExt:
3010 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3011 DAG.getValueType(VA.getValVT()));
3012 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3014 case CCValAssign::ZExt:
3015 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3016 DAG.getValueType(VA.getValVT()));
3017 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3021 InVals.push_back(ArgValue);
3023 } else { // VA.isRegLoc()
3026 assert(VA.isMemLoc());
3027 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3029 int index = ArgLocs[i].getValNo();
3031 // Some Ins[] entries become multiple ArgLoc[] entries.
3032 // Process them only once.
3033 if (index != lastInsIndex)
3035 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3036 // FIXME: For now, all byval parameter objects are marked mutable.
3037 // This can be changed with more analysis.
3038 // In case of tail call optimization mark all arguments mutable.
3039 // Since they could be overwritten by lowering of arguments in case of
3041 if (Flags.isByVal()) {
3042 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3044 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3045 int FrameIndex = StoreByValRegs(
3046 CCInfo, DAG, dl, Chain, CurOrigArg,
3048 Ins[VA.getValNo()].PartOffset,
3049 VA.getLocMemOffset(),
3050 Flags.getByValSize(),
3051 true /*force mutable frames*/,
3053 TotalArgRegsSaveSize);
3054 ByValStoreOffset += Flags.getByValSize();
3055 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3056 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3057 CCInfo.nextInRegsParam();
3059 unsigned FIOffset = VA.getLocMemOffset();
3060 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3063 // Create load nodes to retrieve arguments from the stack.
3064 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3065 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3066 MachinePointerInfo::getFixedStack(FI),
3067 false, false, false, 0));
3069 lastInsIndex = index;
3076 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3077 CCInfo.getNextStackOffset(),
3078 TotalArgRegsSaveSize);
3080 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3085 /// isFloatingPointZero - Return true if this is +0.0.
3086 static bool isFloatingPointZero(SDValue Op) {
3087 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3088 return CFP->getValueAPF().isPosZero();
3089 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3090 // Maybe this has already been legalized into the constant pool?
3091 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3092 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3093 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3094 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3095 return CFP->getValueAPF().isPosZero();
3101 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3102 /// the given operands.
3104 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3105 SDValue &ARMcc, SelectionDAG &DAG,
3107 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3108 unsigned C = RHSC->getZExtValue();
3109 if (!isLegalICmpImmediate(C)) {
3110 // Constant does not fit, try adjusting it by one?
3115 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3116 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3117 RHS = DAG.getConstant(C-1, MVT::i32);
3122 if (C != 0 && isLegalICmpImmediate(C-1)) {
3123 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3124 RHS = DAG.getConstant(C-1, MVT::i32);
3129 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3130 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3131 RHS = DAG.getConstant(C+1, MVT::i32);
3136 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3137 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3138 RHS = DAG.getConstant(C+1, MVT::i32);
3145 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3146 ARMISD::NodeType CompareType;
3149 CompareType = ARMISD::CMP;
3154 CompareType = ARMISD::CMPZ;
3157 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3158 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3161 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3163 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3166 if (!isFloatingPointZero(RHS))
3167 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3169 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3170 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3173 /// duplicateCmp - Glue values can have only one use, so this function
3174 /// duplicates a comparison node.
3176 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3177 unsigned Opc = Cmp.getOpcode();
3179 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3180 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3182 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3183 Cmp = Cmp.getOperand(0);
3184 Opc = Cmp.getOpcode();
3185 if (Opc == ARMISD::CMPFP)
3186 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3188 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3189 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3191 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3194 std::pair<SDValue, SDValue>
3195 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3196 SDValue &ARMcc) const {
3197 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3199 SDValue Value, OverflowCmp;
3200 SDValue LHS = Op.getOperand(0);
3201 SDValue RHS = Op.getOperand(1);
3204 // FIXME: We are currently always generating CMPs because we don't support
3205 // generating CMN through the backend. This is not as good as the natural
3206 // CMP case because it causes a register dependency and cannot be folded
3209 switch (Op.getOpcode()) {
3211 llvm_unreachable("Unknown overflow instruction!");
3213 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3214 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3215 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3218 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3219 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3220 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3223 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3224 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3225 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3228 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3229 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3230 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3234 return std::make_pair(Value, OverflowCmp);
3239 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3240 // Let legalize expand this if it isn't a legal type yet.
3241 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3244 SDValue Value, OverflowCmp;
3246 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3247 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3248 // We use 0 and 1 as false and true values.
3249 SDValue TVal = DAG.getConstant(1, MVT::i32);
3250 SDValue FVal = DAG.getConstant(0, MVT::i32);
3251 EVT VT = Op.getValueType();
3253 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3254 ARMcc, CCR, OverflowCmp);
3256 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3257 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3261 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3262 SDValue Cond = Op.getOperand(0);
3263 SDValue SelectTrue = Op.getOperand(1);
3264 SDValue SelectFalse = Op.getOperand(2);
3266 unsigned Opc = Cond.getOpcode();
3268 if (Cond.getResNo() == 1 &&
3269 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3270 Opc == ISD::USUBO)) {
3271 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3274 SDValue Value, OverflowCmp;
3276 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3277 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3278 EVT VT = Op.getValueType();
3280 return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3281 ARMcc, CCR, OverflowCmp);
3287 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3288 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3290 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3291 const ConstantSDNode *CMOVTrue =
3292 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3293 const ConstantSDNode *CMOVFalse =
3294 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3296 if (CMOVTrue && CMOVFalse) {
3297 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3298 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3302 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3304 False = SelectFalse;
3305 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3310 if (True.getNode() && False.getNode()) {
3311 EVT VT = Op.getValueType();
3312 SDValue ARMcc = Cond.getOperand(2);
3313 SDValue CCR = Cond.getOperand(3);
3314 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3315 assert(True.getValueType() == VT);
3316 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3321 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3322 // undefined bits before doing a full-word comparison with zero.
3323 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3324 DAG.getConstant(1, Cond.getValueType()));
3326 return DAG.getSelectCC(dl, Cond,
3327 DAG.getConstant(0, Cond.getValueType()),
3328 SelectTrue, SelectFalse, ISD::SETNE);
3331 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3332 if (CC == ISD::SETNE)
3334 return ISD::getSetCCInverse(CC, true);
3337 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3338 bool &swpCmpOps, bool &swpVselOps) {
3339 // Start by selecting the GE condition code for opcodes that return true for
3341 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3343 CondCode = ARMCC::GE;
3345 // and GT for opcodes that return false for 'equality'.
3346 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3348 CondCode = ARMCC::GT;
3350 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3351 // to swap the compare operands.
3352 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3356 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3357 // If we have an unordered opcode, we need to swap the operands to the VSEL
3358 // instruction (effectively negating the condition).
3360 // This also has the effect of swapping which one of 'less' or 'greater'
3361 // returns true, so we also swap the compare operands. It also switches
3362 // whether we return true for 'equality', so we compensate by picking the
3363 // opposite condition code to our original choice.
3364 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3365 CC == ISD::SETUGT) {
3366 swpCmpOps = !swpCmpOps;
3367 swpVselOps = !swpVselOps;
3368 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3371 // 'ordered' is 'anything but unordered', so use the VS condition code and
3372 // swap the VSEL operands.
3373 if (CC == ISD::SETO) {
3374 CondCode = ARMCC::VS;
3378 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3379 // code and swap the VSEL operands.
3380 if (CC == ISD::SETUNE) {
3381 CondCode = ARMCC::EQ;
3386 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3387 EVT VT = Op.getValueType();
3388 SDValue LHS = Op.getOperand(0);
3389 SDValue RHS = Op.getOperand(1);
3390 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3391 SDValue TrueVal = Op.getOperand(2);
3392 SDValue FalseVal = Op.getOperand(3);
3395 if (LHS.getValueType() == MVT::i32) {
3396 // Try to generate VSEL on ARMv8.
3397 // The VSEL instruction can't use all the usual ARM condition
3398 // codes: it only has two bits to select the condition code, so it's
3399 // constrained to use only GE, GT, VS and EQ.
3401 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3402 // swap the operands of the previous compare instruction (effectively
3403 // inverting the compare condition, swapping 'less' and 'greater') and
3404 // sometimes need to swap the operands to the VSEL (which inverts the
3405 // condition in the sense of firing whenever the previous condition didn't)
3406 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3407 TrueVal.getValueType() == MVT::f64)) {
3408 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3409 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3410 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3411 CC = getInverseCCForVSEL(CC);
3412 std::swap(TrueVal, FalseVal);
3417 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3418 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3419 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3423 ARMCC::CondCodes CondCode, CondCode2;
3424 FPCCToARMCC(CC, CondCode, CondCode2);
3426 // Try to generate VSEL on ARMv8.
3427 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3428 TrueVal.getValueType() == MVT::f64)) {
3429 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3430 // same operands, as follows:
3431 // c = fcmp [ogt, olt, ugt, ult] a, b
3433 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3434 // handled differently than the original code sequence.
3435 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3437 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3438 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3439 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3440 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3443 bool swpCmpOps = false;
3444 bool swpVselOps = false;
3445 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3447 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3448 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3450 std::swap(LHS, RHS);
3452 std::swap(TrueVal, FalseVal);
3456 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3457 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3458 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3459 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3461 if (CondCode2 != ARMCC::AL) {
3462 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3463 // FIXME: Needs another CMP because flag can have but one use.
3464 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3465 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3466 Result, TrueVal, ARMcc2, CCR, Cmp2);
3471 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3472 /// to morph to an integer compare sequence.
3473 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3474 const ARMSubtarget *Subtarget) {
3475 SDNode *N = Op.getNode();
3476 if (!N->hasOneUse())
3477 // Otherwise it requires moving the value from fp to integer registers.
3479 if (!N->getNumValues())
3481 EVT VT = Op.getValueType();
3482 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3483 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3484 // vmrs are very slow, e.g. cortex-a8.
3487 if (isFloatingPointZero(Op)) {
3491 return ISD::isNormalLoad(N);
3494 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3495 if (isFloatingPointZero(Op))
3496 return DAG.getConstant(0, MVT::i32);
3498 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3499 return DAG.getLoad(MVT::i32, SDLoc(Op),
3500 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3501 Ld->isVolatile(), Ld->isNonTemporal(),
3502 Ld->isInvariant(), Ld->getAlignment());
3504 llvm_unreachable("Unknown VFP cmp argument!");
3507 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3508 SDValue &RetVal1, SDValue &RetVal2) {
3509 if (isFloatingPointZero(Op)) {
3510 RetVal1 = DAG.getConstant(0, MVT::i32);
3511 RetVal2 = DAG.getConstant(0, MVT::i32);
3515 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3516 SDValue Ptr = Ld->getBasePtr();
3517 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3518 Ld->getChain(), Ptr,
3519 Ld->getPointerInfo(),
3520 Ld->isVolatile(), Ld->isNonTemporal(),
3521 Ld->isInvariant(), Ld->getAlignment());
3523 EVT PtrType = Ptr.getValueType();
3524 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3525 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3526 PtrType, Ptr, DAG.getConstant(4, PtrType));
3527 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3528 Ld->getChain(), NewPtr,
3529 Ld->getPointerInfo().getWithOffset(4),
3530 Ld->isVolatile(), Ld->isNonTemporal(),
3531 Ld->isInvariant(), NewAlign);
3535 llvm_unreachable("Unknown VFP cmp argument!");
3538 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3539 /// f32 and even f64 comparisons to integer ones.
3541 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3542 SDValue Chain = Op.getOperand(0);
3543 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3544 SDValue LHS = Op.getOperand(2);
3545 SDValue RHS = Op.getOperand(3);
3546 SDValue Dest = Op.getOperand(4);
3549 bool LHSSeenZero = false;
3550 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3551 bool RHSSeenZero = false;
3552 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3553 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3554 // If unsafe fp math optimization is enabled and there are no other uses of
3555 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3556 // to an integer comparison.
3557 if (CC == ISD::SETOEQ)
3559 else if (CC == ISD::SETUNE)
3562 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3564 if (LHS.getValueType() == MVT::f32) {
3565 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3566 bitcastf32Toi32(LHS, DAG), Mask);
3567 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3568 bitcastf32Toi32(RHS, DAG), Mask);
3569 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3570 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3571 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3572 Chain, Dest, ARMcc, CCR, Cmp);
3577 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3578 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3579 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3580 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3581 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3582 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3583 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3584 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3585 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3591 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3592 SDValue Chain = Op.getOperand(0);
3593 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3594 SDValue LHS = Op.getOperand(2);
3595 SDValue RHS = Op.getOperand(3);
3596 SDValue Dest = Op.getOperand(4);
3599 if (LHS.getValueType() == MVT::i32) {
3601 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3602 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3603 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3604 Chain, Dest, ARMcc, CCR, Cmp);
3607 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3609 if (getTargetMachine().Options.UnsafeFPMath &&
3610 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3611 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3612 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3613 if (Result.getNode())
3617 ARMCC::CondCodes CondCode, CondCode2;
3618 FPCCToARMCC(CC, CondCode, CondCode2);
3620 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3621 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3622 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3623 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3624 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3625 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3626 if (CondCode2 != ARMCC::AL) {
3627 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3628 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3629 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3634 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3635 SDValue Chain = Op.getOperand(0);
3636 SDValue Table = Op.getOperand(1);
3637 SDValue Index = Op.getOperand(2);
3640 EVT PTy = getPointerTy();
3641 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3642 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3643 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3644 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3645 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3646 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3647 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3648 if (Subtarget->isThumb2()) {
3649 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3650 // which does another jump to the destination. This also makes it easier
3651 // to translate it to TBB / TBH later.
3652 // FIXME: This might not work if the function is extremely large.
3653 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3654 Addr, Op.getOperand(2), JTI, UId);
3656 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3657 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3658 MachinePointerInfo::getJumpTable(),
3659 false, false, false, 0);
3660 Chain = Addr.getValue(1);
3661 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3662 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3664 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3665 MachinePointerInfo::getJumpTable(),
3666 false, false, false, 0);
3667 Chain = Addr.getValue(1);
3668 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3672 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3673 EVT VT = Op.getValueType();
3676 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3677 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3679 return DAG.UnrollVectorOp(Op.getNode());
3682 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3683 "Invalid type for custom lowering!");
3684 if (VT != MVT::v4i16)
3685 return DAG.UnrollVectorOp(Op.getNode());
3687 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3688 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3691 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3692 EVT VT = Op.getValueType();
3694 return LowerVectorFP_TO_INT(Op, DAG);
3699 switch (Op.getOpcode()) {
3700 default: llvm_unreachable("Invalid opcode!");
3701 case ISD::FP_TO_SINT:
3702 Opc = ARMISD::FTOSI;
3704 case ISD::FP_TO_UINT:
3705 Opc = ARMISD::FTOUI;
3708 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3709 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3712 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3713 EVT VT = Op.getValueType();
3716 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3717 if (VT.getVectorElementType() == MVT::f32)
3719 return DAG.UnrollVectorOp(Op.getNode());
3722 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3723 "Invalid type for custom lowering!");
3724 if (VT != MVT::v4f32)
3725 return DAG.UnrollVectorOp(Op.getNode());
3729 switch (Op.getOpcode()) {
3730 default: llvm_unreachable("Invalid opcode!");
3731 case ISD::SINT_TO_FP:
3732 CastOpc = ISD::SIGN_EXTEND;
3733 Opc = ISD::SINT_TO_FP;
3735 case ISD::UINT_TO_FP:
3736 CastOpc = ISD::ZERO_EXTEND;
3737 Opc = ISD::UINT_TO_FP;
3741 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3742 return DAG.getNode(Opc, dl, VT, Op);
3745 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3746 EVT VT = Op.getValueType();
3748 return LowerVectorINT_TO_FP(Op, DAG);
3753 switch (Op.getOpcode()) {
3754 default: llvm_unreachable("Invalid opcode!");
3755 case ISD::SINT_TO_FP:
3756 Opc = ARMISD::SITOF;
3758 case ISD::UINT_TO_FP:
3759 Opc = ARMISD::UITOF;
3763 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3764 return DAG.getNode(Opc, dl, VT, Op);
3767 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3768 // Implement fcopysign with a fabs and a conditional fneg.
3769 SDValue Tmp0 = Op.getOperand(0);
3770 SDValue Tmp1 = Op.getOperand(1);
3772 EVT VT = Op.getValueType();
3773 EVT SrcVT = Tmp1.getValueType();
3774 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3775 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3776 bool UseNEON = !InGPR && Subtarget->hasNEON();
3779 // Use VBSL to copy the sign bit.
3780 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3781 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3782 DAG.getTargetConstant(EncodedVal, MVT::i32));
3783 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3785 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3786 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3787 DAG.getConstant(32, MVT::i32));
3788 else /*if (VT == MVT::f32)*/
3789 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3790 if (SrcVT == MVT::f32) {
3791 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3793 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3794 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3795 DAG.getConstant(32, MVT::i32));
3796 } else if (VT == MVT::f32)
3797 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3798 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3799 DAG.getConstant(32, MVT::i32));
3800 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3801 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3803 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3805 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3806 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3807 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3809 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3810 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3811 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3812 if (VT == MVT::f32) {
3813 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3814 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3815 DAG.getConstant(0, MVT::i32));
3817 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3823 // Bitcast operand 1 to i32.
3824 if (SrcVT == MVT::f64)
3825 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3827 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3829 // Or in the signbit with integer operations.
3830 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3831 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3832 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3833 if (VT == MVT::f32) {
3834 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3835 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3836 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3837 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3840 // f64: Or the high part with signbit and then combine two parts.
3841 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3843 SDValue Lo = Tmp0.getValue(0);
3844 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3845 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3846 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3849 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3850 MachineFunction &MF = DAG.getMachineFunction();
3851 MachineFrameInfo *MFI = MF.getFrameInfo();
3852 MFI->setReturnAddressIsTaken(true);
3854 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3857 EVT VT = Op.getValueType();
3859 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3861 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3862 SDValue Offset = DAG.getConstant(4, MVT::i32);
3863 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3864 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3865 MachinePointerInfo(), false, false, false, 0);
3868 // Return LR, which contains the return address. Mark it an implicit live-in.
3869 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3870 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3873 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3874 const ARMBaseRegisterInfo &ARI =
3875 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3876 MachineFunction &MF = DAG.getMachineFunction();
3877 MachineFrameInfo *MFI = MF.getFrameInfo();
3878 MFI->setFrameAddressIsTaken(true);
3880 EVT VT = Op.getValueType();
3881 SDLoc dl(Op); // FIXME probably not meaningful
3882 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3883 unsigned FrameReg = ARI.getFrameRegister(MF);
3884 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3886 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3887 MachinePointerInfo(),
3888 false, false, false, 0);
3892 // FIXME? Maybe this could be a TableGen attribute on some registers and
3893 // this table could be generated automatically from RegInfo.
3894 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3896 unsigned Reg = StringSwitch<unsigned>(RegName)
3897 .Case("sp", ARM::SP)
3901 report_fatal_error("Invalid register name global variable");
3904 /// ExpandBITCAST - If the target supports VFP, this function is called to
3905 /// expand a bit convert where either the source or destination type is i64 to
3906 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3907 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3908 /// vectors), since the legalizer won't know what to do with that.
3909 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3910 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3912 SDValue Op = N->getOperand(0);
3914 // This function is only supposed to be called for i64 types, either as the
3915 // source or destination of the bit convert.
3916 EVT SrcVT = Op.getValueType();
3917 EVT DstVT = N->getValueType(0);
3918 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3919 "ExpandBITCAST called for non-i64 type");
3921 // Turn i64->f64 into VMOVDRR.
3922 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3923 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3924 DAG.getConstant(0, MVT::i32));
3925 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3926 DAG.getConstant(1, MVT::i32));
3927 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3928 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3931 // Turn f64->i64 into VMOVRRD.
3932 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3934 if (TLI.isBigEndian() && SrcVT.isVector() &&
3935 SrcVT.getVectorNumElements() > 1)
3936 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3937 DAG.getVTList(MVT::i32, MVT::i32),
3938 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3940 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3941 DAG.getVTList(MVT::i32, MVT::i32), Op);
3942 // Merge the pieces into a single i64 value.
3943 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3949 /// getZeroVector - Returns a vector of specified type with all zero elements.
3950 /// Zero vectors are used to represent vector negation and in those cases
3951 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3952 /// not support i64 elements, so sometimes the zero vectors will need to be
3953 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3955 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3956 assert(VT.isVector() && "Expected a vector type");
3957 // The canonical modified immediate encoding of a zero vector is....0!
3958 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3959 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3960 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3961 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3964 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3965 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3966 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3967 SelectionDAG &DAG) const {
3968 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3969 EVT VT = Op.getValueType();
3970 unsigned VTBits = VT.getSizeInBits();
3972 SDValue ShOpLo = Op.getOperand(0);
3973 SDValue ShOpHi = Op.getOperand(1);
3974 SDValue ShAmt = Op.getOperand(2);
3976 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3978 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3980 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3981 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3982 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3983 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3984 DAG.getConstant(VTBits, MVT::i32));
3985 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3986 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3987 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3989 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3990 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3992 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3993 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3996 SDValue Ops[2] = { Lo, Hi };
3997 return DAG.getMergeValues(Ops, dl);
4000 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4001 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4002 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4003 SelectionDAG &DAG) const {
4004 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4005 EVT VT = Op.getValueType();
4006 unsigned VTBits = VT.getSizeInBits();
4008 SDValue ShOpLo = Op.getOperand(0);
4009 SDValue ShOpHi = Op.getOperand(1);
4010 SDValue ShAmt = Op.getOperand(2);
4013 assert(Op.getOpcode() == ISD::SHL_PARTS);
4014 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4015 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4016 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4017 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4018 DAG.getConstant(VTBits, MVT::i32));
4019 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4020 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4022 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4023 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4024 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4026 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4027 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4030 SDValue Ops[2] = { Lo, Hi };
4031 return DAG.getMergeValues(Ops, dl);
4034 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4035 SelectionDAG &DAG) const {
4036 // The rounding mode is in bits 23:22 of the FPSCR.
4037 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4038 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4039 // so that the shift + and get folded into a bitfield extract.
4041 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4042 DAG.getConstant(Intrinsic::arm_get_fpscr,
4044 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4045 DAG.getConstant(1U << 22, MVT::i32));
4046 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4047 DAG.getConstant(22, MVT::i32));
4048 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4049 DAG.getConstant(3, MVT::i32));
4052 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4053 const ARMSubtarget *ST) {
4054 EVT VT = N->getValueType(0);
4057 if (!ST->hasV6T2Ops())
4060 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4061 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4064 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4065 /// for each 16-bit element from operand, repeated. The basic idea is to
4066 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4068 /// Trace for v4i16:
4069 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4070 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4071 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4072 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4073 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4074 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4075 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4076 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4077 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4078 EVT VT = N->getValueType(0);
4081 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4082 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4083 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4084 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4085 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4086 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4089 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4090 /// bit-count for each 16-bit element from the operand. We need slightly
4091 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4092 /// 64/128-bit registers.
4094 /// Trace for v4i16:
4095 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4096 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4097 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4098 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4099 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4100 EVT VT = N->getValueType(0);
4103 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4104 if (VT.is64BitVector()) {
4105 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4106 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4107 DAG.getIntPtrConstant(0));
4109 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4110 BitCounts, DAG.getIntPtrConstant(0));
4111 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4115 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4116 /// bit-count for each 32-bit element from the operand. The idea here is
4117 /// to split the vector into 16-bit elements, leverage the 16-bit count
4118 /// routine, and then combine the results.
4120 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4121 /// input = [v0 v1 ] (vi: 32-bit elements)
4122 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4123 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4124 /// vrev: N0 = [k1 k0 k3 k2 ]
4126 /// N1 =+[k1 k0 k3 k2 ]
4128 /// N2 =+[k1 k3 k0 k2 ]
4130 /// Extended =+[k1 k3 k0 k2 ]
4132 /// Extracted=+[k1 k3 ]
4134 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4135 EVT VT = N->getValueType(0);
4138 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4140 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4141 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4142 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4143 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4144 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4146 if (VT.is64BitVector()) {
4147 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4148 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4149 DAG.getIntPtrConstant(0));
4151 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4152 DAG.getIntPtrConstant(0));
4153 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4157 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4158 const ARMSubtarget *ST) {
4159 EVT VT = N->getValueType(0);
4161 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4162 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4163 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4164 "Unexpected type for custom ctpop lowering");
4166 if (VT.getVectorElementType() == MVT::i32)
4167 return lowerCTPOP32BitElements(N, DAG);
4169 return lowerCTPOP16BitElements(N, DAG);
4172 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4173 const ARMSubtarget *ST) {
4174 EVT VT = N->getValueType(0);
4180 // Lower vector shifts on NEON to use VSHL.
4181 assert(ST->hasNEON() && "unexpected vector shift");
4183 // Left shifts translate directly to the vshiftu intrinsic.
4184 if (N->getOpcode() == ISD::SHL)
4185 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4186 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4187 N->getOperand(0), N->getOperand(1));
4189 assert((N->getOpcode() == ISD::SRA ||
4190 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4192 // NEON uses the same intrinsics for both left and right shifts. For
4193 // right shifts, the shift amounts are negative, so negate the vector of
4195 EVT ShiftVT = N->getOperand(1).getValueType();
4196 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4197 getZeroVector(ShiftVT, DAG, dl),
4199 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4200 Intrinsic::arm_neon_vshifts :
4201 Intrinsic::arm_neon_vshiftu);
4202 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4203 DAG.getConstant(vshiftInt, MVT::i32),
4204 N->getOperand(0), NegatedCount);
4207 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4208 const ARMSubtarget *ST) {
4209 EVT VT = N->getValueType(0);
4212 // We can get here for a node like i32 = ISD::SHL i32, i64
4216 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4217 "Unknown shift to lower!");
4219 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4220 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4221 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4224 // If we are in thumb mode, we don't have RRX.
4225 if (ST->isThumb1Only()) return SDValue();
4227 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4228 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4229 DAG.getConstant(0, MVT::i32));
4230 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4231 DAG.getConstant(1, MVT::i32));
4233 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4234 // captures the result into a carry flag.
4235 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4236 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4238 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4239 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4241 // Merge the pieces into a single i64 value.
4242 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4245 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4246 SDValue TmpOp0, TmpOp1;
4247 bool Invert = false;
4251 SDValue Op0 = Op.getOperand(0);
4252 SDValue Op1 = Op.getOperand(1);
4253 SDValue CC = Op.getOperand(2);
4254 EVT VT = Op.getValueType();
4255 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4258 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4259 switch (SetCCOpcode) {
4260 default: llvm_unreachable("Illegal FP comparison");
4262 case ISD::SETNE: Invert = true; // Fallthrough
4264 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4266 case ISD::SETLT: Swap = true; // Fallthrough
4268 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4270 case ISD::SETLE: Swap = true; // Fallthrough
4272 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4273 case ISD::SETUGE: Swap = true; // Fallthrough
4274 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4275 case ISD::SETUGT: Swap = true; // Fallthrough
4276 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4277 case ISD::SETUEQ: Invert = true; // Fallthrough
4279 // Expand this to (OLT | OGT).
4283 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4284 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4286 case ISD::SETUO: Invert = true; // Fallthrough
4288 // Expand this to (OLT | OGE).
4292 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4293 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4297 // Integer comparisons.
4298 switch (SetCCOpcode) {
4299 default: llvm_unreachable("Illegal integer comparison");
4300 case ISD::SETNE: Invert = true;
4301 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4302 case ISD::SETLT: Swap = true;
4303 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4304 case ISD::SETLE: Swap = true;
4305 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4306 case ISD::SETULT: Swap = true;
4307 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4308 case ISD::SETULE: Swap = true;
4309 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4312 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4313 if (Opc == ARMISD::VCEQ) {
4316 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4318 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4321 // Ignore bitconvert.
4322 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4323 AndOp = AndOp.getOperand(0);
4325 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4327 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4328 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4335 std::swap(Op0, Op1);
4337 // If one of the operands is a constant vector zero, attempt to fold the
4338 // comparison to a specialized compare-against-zero form.
4340 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4342 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4343 if (Opc == ARMISD::VCGE)
4344 Opc = ARMISD::VCLEZ;
4345 else if (Opc == ARMISD::VCGT)
4346 Opc = ARMISD::VCLTZ;
4351 if (SingleOp.getNode()) {
4354 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4356 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4358 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4360 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4362 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4364 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4367 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4371 Result = DAG.getNOT(dl, Result, VT);
4376 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4377 /// valid vector constant for a NEON instruction with a "modified immediate"
4378 /// operand (e.g., VMOV). If so, return the encoded value.
4379 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4380 unsigned SplatBitSize, SelectionDAG &DAG,
4381 EVT &VT, bool is128Bits, NEONModImmType type) {
4382 unsigned OpCmode, Imm;
4384 // SplatBitSize is set to the smallest size that splats the vector, so a
4385 // zero vector will always have SplatBitSize == 8. However, NEON modified
4386 // immediate instructions others than VMOV do not support the 8-bit encoding
4387 // of a zero vector, and the default encoding of zero is supposed to be the
4392 switch (SplatBitSize) {
4394 if (type != VMOVModImm)
4396 // Any 1-byte value is OK. Op=0, Cmode=1110.
4397 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4400 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4404 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4405 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4406 if ((SplatBits & ~0xff) == 0) {
4407 // Value = 0x00nn: Op=x, Cmode=100x.
4412 if ((SplatBits & ~0xff00) == 0) {
4413 // Value = 0xnn00: Op=x, Cmode=101x.
4415 Imm = SplatBits >> 8;
4421 // NEON's 32-bit VMOV supports splat values where:
4422 // * only one byte is nonzero, or
4423 // * the least significant byte is 0xff and the second byte is nonzero, or
4424 // * the least significant 2 bytes are 0xff and the third is nonzero.
4425 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4426 if ((SplatBits & ~0xff) == 0) {
4427 // Value = 0x000000nn: Op=x, Cmode=000x.
4432 if ((SplatBits & ~0xff00) == 0) {
4433 // Value = 0x0000nn00: Op=x, Cmode=001x.
4435 Imm = SplatBits >> 8;
4438 if ((SplatBits & ~0xff0000) == 0) {
4439 // Value = 0x00nn0000: Op=x, Cmode=010x.
4441 Imm = SplatBits >> 16;
4444 if ((SplatBits & ~0xff000000) == 0) {
4445 // Value = 0xnn000000: Op=x, Cmode=011x.
4447 Imm = SplatBits >> 24;
4451 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4452 if (type == OtherModImm) return SDValue();
4454 if ((SplatBits & ~0xffff) == 0 &&
4455 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4456 // Value = 0x0000nnff: Op=x, Cmode=1100.
4458 Imm = SplatBits >> 8;
4462 if ((SplatBits & ~0xffffff) == 0 &&
4463 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4464 // Value = 0x00nnffff: Op=x, Cmode=1101.
4466 Imm = SplatBits >> 16;
4470 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4471 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4472 // VMOV.I32. A (very) minor optimization would be to replicate the value
4473 // and fall through here to test for a valid 64-bit splat. But, then the
4474 // caller would also need to check and handle the change in size.
4478 if (type != VMOVModImm)
4480 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4481 uint64_t BitMask = 0xff;
4483 unsigned ImmMask = 1;
4485 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4486 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4489 } else if ((SplatBits & BitMask) != 0) {
4495 // Op=1, Cmode=1110.
4497 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4502 llvm_unreachable("unexpected size for isNEONModifiedImm");
4505 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4506 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4509 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4510 const ARMSubtarget *ST) const {
4514 bool IsDouble = Op.getValueType() == MVT::f64;
4515 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4517 // Try splatting with a VMOV.f32...
4518 APFloat FPVal = CFP->getValueAPF();
4519 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4522 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4523 // We have code in place to select a valid ConstantFP already, no need to
4528 // It's a float and we are trying to use NEON operations where
4529 // possible. Lower it to a splat followed by an extract.
4531 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4532 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4534 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4535 DAG.getConstant(0, MVT::i32));
4538 // The rest of our options are NEON only, make sure that's allowed before
4540 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4544 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4546 // It wouldn't really be worth bothering for doubles except for one very
4547 // important value, which does happen to match: 0.0. So make sure we don't do
4549 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4552 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4553 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4555 if (NewVal != SDValue()) {
4557 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4560 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4562 // It's a float: cast and extract a vector element.
4563 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4565 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4566 DAG.getConstant(0, MVT::i32));
4569 // Finally, try a VMVN.i32
4570 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4572 if (NewVal != SDValue()) {
4574 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4577 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4579 // It's a float: cast and extract a vector element.
4580 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4582 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4583 DAG.getConstant(0, MVT::i32));
4589 // check if an VEXT instruction can handle the shuffle mask when the
4590 // vector sources of the shuffle are the same.
4591 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4592 unsigned NumElts = VT.getVectorNumElements();
4594 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4600 // If this is a VEXT shuffle, the immediate value is the index of the first
4601 // element. The other shuffle indices must be the successive elements after
4603 unsigned ExpectedElt = Imm;
4604 for (unsigned i = 1; i < NumElts; ++i) {
4605 // Increment the expected index. If it wraps around, just follow it
4606 // back to index zero and keep going.
4608 if (ExpectedElt == NumElts)
4611 if (M[i] < 0) continue; // ignore UNDEF indices
4612 if (ExpectedElt != static_cast<unsigned>(M[i]))
4620 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4621 bool &ReverseVEXT, unsigned &Imm) {
4622 unsigned NumElts = VT.getVectorNumElements();
4623 ReverseVEXT = false;
4625 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4631 // If this is a VEXT shuffle, the immediate value is the index of the first
4632 // element. The other shuffle indices must be the successive elements after
4634 unsigned ExpectedElt = Imm;
4635 for (unsigned i = 1; i < NumElts; ++i) {
4636 // Increment the expected index. If it wraps around, it may still be
4637 // a VEXT but the source vectors must be swapped.
4639 if (ExpectedElt == NumElts * 2) {
4644 if (M[i] < 0) continue; // ignore UNDEF indices
4645 if (ExpectedElt != static_cast<unsigned>(M[i]))
4649 // Adjust the index value if the source operands will be swapped.
4656 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4657 /// instruction with the specified blocksize. (The order of the elements
4658 /// within each block of the vector is reversed.)
4659 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4660 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4661 "Only possible block sizes for VREV are: 16, 32, 64");
4663 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4667 unsigned NumElts = VT.getVectorNumElements();
4668 unsigned BlockElts = M[0] + 1;
4669 // If the first shuffle index is UNDEF, be optimistic.
4671 BlockElts = BlockSize / EltSz;
4673 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4676 for (unsigned i = 0; i < NumElts; ++i) {
4677 if (M[i] < 0) continue; // ignore UNDEF indices
4678 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4685 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4686 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4687 // range, then 0 is placed into the resulting vector. So pretty much any mask
4688 // of 8 elements can work here.
4689 return VT == MVT::v8i8 && M.size() == 8;
4692 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4693 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4697 unsigned NumElts = VT.getVectorNumElements();
4698 WhichResult = (M[0] == 0 ? 0 : 1);
4699 for (unsigned i = 0; i < NumElts; i += 2) {
4700 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4701 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4707 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4708 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4709 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4710 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4711 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4715 unsigned NumElts = VT.getVectorNumElements();
4716 WhichResult = (M[0] == 0 ? 0 : 1);
4717 for (unsigned i = 0; i < NumElts; i += 2) {
4718 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4719 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4725 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4726 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4730 unsigned NumElts = VT.getVectorNumElements();
4731 WhichResult = (M[0] == 0 ? 0 : 1);
4732 for (unsigned i = 0; i != NumElts; ++i) {
4733 if (M[i] < 0) continue; // ignore UNDEF indices
4734 if ((unsigned) M[i] != 2 * i + WhichResult)
4738 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4739 if (VT.is64BitVector() && EltSz == 32)
4745 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4746 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4747 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4748 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4749 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4753 unsigned Half = VT.getVectorNumElements() / 2;
4754 WhichResult = (M[0] == 0 ? 0 : 1);
4755 for (unsigned j = 0; j != 2; ++j) {
4756 unsigned Idx = WhichResult;
4757 for (unsigned i = 0; i != Half; ++i) {
4758 int MIdx = M[i + j * Half];
4759 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4765 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4766 if (VT.is64BitVector() && EltSz == 32)
4772 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4773 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4777 unsigned NumElts = VT.getVectorNumElements();
4778 WhichResult = (M[0] == 0 ? 0 : 1);
4779 unsigned Idx = WhichResult * NumElts / 2;
4780 for (unsigned i = 0; i != NumElts; i += 2) {
4781 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4782 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4787 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4788 if (VT.is64BitVector() && EltSz == 32)
4794 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4795 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4796 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4797 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4798 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4802 unsigned NumElts = VT.getVectorNumElements();
4803 WhichResult = (M[0] == 0 ? 0 : 1);
4804 unsigned Idx = WhichResult * NumElts / 2;
4805 for (unsigned i = 0; i != NumElts; i += 2) {
4806 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4807 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4812 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4813 if (VT.is64BitVector() && EltSz == 32)
4819 /// \return true if this is a reverse operation on an vector.
4820 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4821 unsigned NumElts = VT.getVectorNumElements();
4822 // Make sure the mask has the right size.
4823 if (NumElts != M.size())
4826 // Look for <15, ..., 3, -1, 1, 0>.
4827 for (unsigned i = 0; i != NumElts; ++i)
4828 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4834 // If N is an integer constant that can be moved into a register in one
4835 // instruction, return an SDValue of such a constant (will become a MOV
4836 // instruction). Otherwise return null.
4837 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4838 const ARMSubtarget *ST, SDLoc dl) {
4840 if (!isa<ConstantSDNode>(N))
4842 Val = cast<ConstantSDNode>(N)->getZExtValue();
4844 if (ST->isThumb1Only()) {
4845 if (Val <= 255 || ~Val <= 255)
4846 return DAG.getConstant(Val, MVT::i32);
4848 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4849 return DAG.getConstant(Val, MVT::i32);
4854 // If this is a case we can't handle, return null and let the default
4855 // expansion code take care of it.
4856 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4857 const ARMSubtarget *ST) const {
4858 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4860 EVT VT = Op.getValueType();
4862 APInt SplatBits, SplatUndef;
4863 unsigned SplatBitSize;
4865 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4866 if (SplatBitSize <= 64) {
4867 // Check if an immediate VMOV works.
4869 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4870 SplatUndef.getZExtValue(), SplatBitSize,
4871 DAG, VmovVT, VT.is128BitVector(),
4873 if (Val.getNode()) {
4874 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4875 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4878 // Try an immediate VMVN.
4879 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4880 Val = isNEONModifiedImm(NegatedImm,
4881 SplatUndef.getZExtValue(), SplatBitSize,
4882 DAG, VmovVT, VT.is128BitVector(),
4884 if (Val.getNode()) {
4885 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4886 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4889 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4890 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4891 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4893 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4894 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4900 // Scan through the operands to see if only one value is used.
4902 // As an optimisation, even if more than one value is used it may be more
4903 // profitable to splat with one value then change some lanes.
4905 // Heuristically we decide to do this if the vector has a "dominant" value,
4906 // defined as splatted to more than half of the lanes.
4907 unsigned NumElts = VT.getVectorNumElements();
4908 bool isOnlyLowElement = true;
4909 bool usesOnlyOneValue = true;
4910 bool hasDominantValue = false;
4911 bool isConstant = true;
4913 // Map of the number of times a particular SDValue appears in the
4915 DenseMap<SDValue, unsigned> ValueCounts;
4917 for (unsigned i = 0; i < NumElts; ++i) {
4918 SDValue V = Op.getOperand(i);
4919 if (V.getOpcode() == ISD::UNDEF)
4922 isOnlyLowElement = false;
4923 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4926 ValueCounts.insert(std::make_pair(V, 0));
4927 unsigned &Count = ValueCounts[V];
4929 // Is this value dominant? (takes up more than half of the lanes)
4930 if (++Count > (NumElts / 2)) {
4931 hasDominantValue = true;
4935 if (ValueCounts.size() != 1)
4936 usesOnlyOneValue = false;
4937 if (!Value.getNode() && ValueCounts.size() > 0)
4938 Value = ValueCounts.begin()->first;
4940 if (ValueCounts.size() == 0)
4941 return DAG.getUNDEF(VT);
4943 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4944 // Keep going if we are hitting this case.
4945 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4946 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4948 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4950 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4951 // i32 and try again.
4952 if (hasDominantValue && EltSize <= 32) {
4956 // If we are VDUPing a value that comes directly from a vector, that will
4957 // cause an unnecessary move to and from a GPR, where instead we could
4958 // just use VDUPLANE. We can only do this if the lane being extracted
4959 // is at a constant index, as the VDUP from lane instructions only have
4960 // constant-index forms.
4961 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4962 isa<ConstantSDNode>(Value->getOperand(1))) {
4963 // We need to create a new undef vector to use for the VDUPLANE if the
4964 // size of the vector from which we get the value is different than the
4965 // size of the vector that we need to create. We will insert the element
4966 // such that the register coalescer will remove unnecessary copies.
4967 if (VT != Value->getOperand(0).getValueType()) {
4968 ConstantSDNode *constIndex;
4969 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4970 assert(constIndex && "The index is not a constant!");
4971 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4972 VT.getVectorNumElements();
4973 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4974 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4975 Value, DAG.getConstant(index, MVT::i32)),
4976 DAG.getConstant(index, MVT::i32));
4978 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4979 Value->getOperand(0), Value->getOperand(1));
4981 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4983 if (!usesOnlyOneValue) {
4984 // The dominant value was splatted as 'N', but we now have to insert
4985 // all differing elements.
4986 for (unsigned I = 0; I < NumElts; ++I) {
4987 if (Op.getOperand(I) == Value)
4989 SmallVector<SDValue, 3> Ops;
4991 Ops.push_back(Op.getOperand(I));
4992 Ops.push_back(DAG.getConstant(I, MVT::i32));
4993 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
4998 if (VT.getVectorElementType().isFloatingPoint()) {
4999 SmallVector<SDValue, 8> Ops;
5000 for (unsigned i = 0; i < NumElts; ++i)
5001 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5003 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5004 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5005 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5007 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5009 if (usesOnlyOneValue) {
5010 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5011 if (isConstant && Val.getNode())
5012 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5016 // If all elements are constants and the case above didn't get hit, fall back
5017 // to the default expansion, which will generate a load from the constant
5022 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5024 SDValue shuffle = ReconstructShuffle(Op, DAG);
5025 if (shuffle != SDValue())
5029 // Vectors with 32- or 64-bit elements can be built by directly assigning
5030 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5031 // will be legalized.
5032 if (EltSize >= 32) {
5033 // Do the expansion with floating-point types, since that is what the VFP
5034 // registers are defined to use, and since i64 is not legal.
5035 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5036 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5037 SmallVector<SDValue, 8> Ops;
5038 for (unsigned i = 0; i < NumElts; ++i)
5039 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5040 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5041 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5044 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5045 // know the default expansion would otherwise fall back on something even
5046 // worse. For a vector with one or two non-undef values, that's
5047 // scalar_to_vector for the elements followed by a shuffle (provided the
5048 // shuffle is valid for the target) and materialization element by element
5049 // on the stack followed by a load for everything else.
5050 if (!isConstant && !usesOnlyOneValue) {
5051 SDValue Vec = DAG.getUNDEF(VT);
5052 for (unsigned i = 0 ; i < NumElts; ++i) {
5053 SDValue V = Op.getOperand(i);
5054 if (V.getOpcode() == ISD::UNDEF)
5056 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5057 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5065 // Gather data to see if the operation can be modelled as a
5066 // shuffle in combination with VEXTs.
5067 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5068 SelectionDAG &DAG) const {
5070 EVT VT = Op.getValueType();
5071 unsigned NumElts = VT.getVectorNumElements();
5073 SmallVector<SDValue, 2> SourceVecs;
5074 SmallVector<unsigned, 2> MinElts;
5075 SmallVector<unsigned, 2> MaxElts;
5077 for (unsigned i = 0; i < NumElts; ++i) {
5078 SDValue V = Op.getOperand(i);
5079 if (V.getOpcode() == ISD::UNDEF)
5081 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5082 // A shuffle can only come from building a vector from various
5083 // elements of other vectors.
5085 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5086 VT.getVectorElementType()) {
5087 // This code doesn't know how to handle shuffles where the vector
5088 // element types do not match (this happens because type legalization
5089 // promotes the return type of EXTRACT_VECTOR_ELT).
5090 // FIXME: It might be appropriate to extend this code to handle
5091 // mismatched types.
5095 // Record this extraction against the appropriate vector if possible...
5096 SDValue SourceVec = V.getOperand(0);
5097 // If the element number isn't a constant, we can't effectively
5098 // analyze what's going on.
5099 if (!isa<ConstantSDNode>(V.getOperand(1)))
5101 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5102 bool FoundSource = false;
5103 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5104 if (SourceVecs[j] == SourceVec) {
5105 if (MinElts[j] > EltNo)
5107 if (MaxElts[j] < EltNo)
5114 // Or record a new source if not...
5116 SourceVecs.push_back(SourceVec);
5117 MinElts.push_back(EltNo);
5118 MaxElts.push_back(EltNo);
5122 // Currently only do something sane when at most two source vectors
5124 if (SourceVecs.size() > 2)
5127 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5128 int VEXTOffsets[2] = {0, 0};
5130 // This loop extracts the usage patterns of the source vectors
5131 // and prepares appropriate SDValues for a shuffle if possible.
5132 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5133 if (SourceVecs[i].getValueType() == VT) {
5134 // No VEXT necessary
5135 ShuffleSrcs[i] = SourceVecs[i];
5138 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5139 // It probably isn't worth padding out a smaller vector just to
5140 // break it down again in a shuffle.
5144 // Since only 64-bit and 128-bit vectors are legal on ARM and
5145 // we've eliminated the other cases...
5146 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5147 "unexpected vector sizes in ReconstructShuffle");
5149 if (MaxElts[i] - MinElts[i] >= NumElts) {
5150 // Span too large for a VEXT to cope
5154 if (MinElts[i] >= NumElts) {
5155 // The extraction can just take the second half
5156 VEXTOffsets[i] = NumElts;
5157 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5159 DAG.getIntPtrConstant(NumElts));
5160 } else if (MaxElts[i] < NumElts) {
5161 // The extraction can just take the first half
5163 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5165 DAG.getIntPtrConstant(0));
5167 // An actual VEXT is needed
5168 VEXTOffsets[i] = MinElts[i];
5169 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5171 DAG.getIntPtrConstant(0));
5172 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5174 DAG.getIntPtrConstant(NumElts));
5175 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5176 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5180 SmallVector<int, 8> Mask;
5182 for (unsigned i = 0; i < NumElts; ++i) {
5183 SDValue Entry = Op.getOperand(i);
5184 if (Entry.getOpcode() == ISD::UNDEF) {
5189 SDValue ExtractVec = Entry.getOperand(0);
5190 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5191 .getOperand(1))->getSExtValue();
5192 if (ExtractVec == SourceVecs[0]) {
5193 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5195 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5199 // Final check before we try to produce nonsense...
5200 if (isShuffleMaskLegal(Mask, VT))
5201 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5207 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5208 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5209 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5210 /// are assumed to be legal.
5212 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5214 if (VT.getVectorNumElements() == 4 &&
5215 (VT.is128BitVector() || VT.is64BitVector())) {
5216 unsigned PFIndexes[4];
5217 for (unsigned i = 0; i != 4; ++i) {
5221 PFIndexes[i] = M[i];
5224 // Compute the index in the perfect shuffle table.
5225 unsigned PFTableIndex =
5226 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5227 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5228 unsigned Cost = (PFEntry >> 30);
5235 unsigned Imm, WhichResult;
5237 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5238 return (EltSize >= 32 ||
5239 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5240 isVREVMask(M, VT, 64) ||
5241 isVREVMask(M, VT, 32) ||
5242 isVREVMask(M, VT, 16) ||
5243 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5244 isVTBLMask(M, VT) ||
5245 isVTRNMask(M, VT, WhichResult) ||
5246 isVUZPMask(M, VT, WhichResult) ||
5247 isVZIPMask(M, VT, WhichResult) ||
5248 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5249 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5250 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5251 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5254 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5255 /// the specified operations to build the shuffle.
5256 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5257 SDValue RHS, SelectionDAG &DAG,
5259 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5260 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5261 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5264 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5273 OP_VUZPL, // VUZP, left result
5274 OP_VUZPR, // VUZP, right result
5275 OP_VZIPL, // VZIP, left result
5276 OP_VZIPR, // VZIP, right result
5277 OP_VTRNL, // VTRN, left result
5278 OP_VTRNR // VTRN, right result
5281 if (OpNum == OP_COPY) {
5282 if (LHSID == (1*9+2)*9+3) return LHS;
5283 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5287 SDValue OpLHS, OpRHS;
5288 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5289 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5290 EVT VT = OpLHS.getValueType();
5293 default: llvm_unreachable("Unknown shuffle opcode!");
5295 // VREV divides the vector in half and swaps within the half.
5296 if (VT.getVectorElementType() == MVT::i32 ||
5297 VT.getVectorElementType() == MVT::f32)
5298 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5299 // vrev <4 x i16> -> VREV32
5300 if (VT.getVectorElementType() == MVT::i16)
5301 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5302 // vrev <4 x i8> -> VREV16
5303 assert(VT.getVectorElementType() == MVT::i8);
5304 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5309 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5310 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5314 return DAG.getNode(ARMISD::VEXT, dl, VT,
5316 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5319 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5320 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5323 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5324 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5327 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5328 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5332 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5333 ArrayRef<int> ShuffleMask,
5334 SelectionDAG &DAG) {
5335 // Check to see if we can use the VTBL instruction.
5336 SDValue V1 = Op.getOperand(0);
5337 SDValue V2 = Op.getOperand(1);
5340 SmallVector<SDValue, 8> VTBLMask;
5341 for (ArrayRef<int>::iterator
5342 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5343 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5345 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5346 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5347 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5349 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5350 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5353 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5354 SelectionDAG &DAG) {
5356 SDValue OpLHS = Op.getOperand(0);
5357 EVT VT = OpLHS.getValueType();
5359 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5360 "Expect an v8i16/v16i8 type");
5361 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5362 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5363 // extract the first 8 bytes into the top double word and the last 8 bytes
5364 // into the bottom double word. The v8i16 case is similar.
5365 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5366 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5367 DAG.getConstant(ExtractNum, MVT::i32));
5370 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5371 SDValue V1 = Op.getOperand(0);
5372 SDValue V2 = Op.getOperand(1);
5374 EVT VT = Op.getValueType();
5375 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5377 // Convert shuffles that are directly supported on NEON to target-specific
5378 // DAG nodes, instead of keeping them as shuffles and matching them again
5379 // during code selection. This is more efficient and avoids the possibility
5380 // of inconsistencies between legalization and selection.
5381 // FIXME: floating-point vectors should be canonicalized to integer vectors
5382 // of the same time so that they get CSEd properly.
5383 ArrayRef<int> ShuffleMask = SVN->getMask();
5385 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5386 if (EltSize <= 32) {
5387 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5388 int Lane = SVN->getSplatIndex();
5389 // If this is undef splat, generate it via "just" vdup, if possible.
5390 if (Lane == -1) Lane = 0;
5392 // Test if V1 is a SCALAR_TO_VECTOR.
5393 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5394 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5396 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5397 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5399 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5400 !isa<ConstantSDNode>(V1.getOperand(0))) {
5401 bool IsScalarToVector = true;
5402 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5403 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5404 IsScalarToVector = false;
5407 if (IsScalarToVector)
5408 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5410 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5411 DAG.getConstant(Lane, MVT::i32));
5416 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5419 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5420 DAG.getConstant(Imm, MVT::i32));
5423 if (isVREVMask(ShuffleMask, VT, 64))
5424 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5425 if (isVREVMask(ShuffleMask, VT, 32))
5426 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5427 if (isVREVMask(ShuffleMask, VT, 16))
5428 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5430 if (V2->getOpcode() == ISD::UNDEF &&
5431 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5432 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5433 DAG.getConstant(Imm, MVT::i32));
5436 // Check for Neon shuffles that modify both input vectors in place.
5437 // If both results are used, i.e., if there are two shuffles with the same
5438 // source operands and with masks corresponding to both results of one of
5439 // these operations, DAG memoization will ensure that a single node is
5440 // used for both shuffles.
5441 unsigned WhichResult;
5442 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5443 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5444 V1, V2).getValue(WhichResult);
5445 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5446 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5447 V1, V2).getValue(WhichResult);
5448 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5449 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5450 V1, V2).getValue(WhichResult);
5452 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5453 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5454 V1, V1).getValue(WhichResult);
5455 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5456 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5457 V1, V1).getValue(WhichResult);
5458 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5459 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5460 V1, V1).getValue(WhichResult);
5463 // If the shuffle is not directly supported and it has 4 elements, use
5464 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5465 unsigned NumElts = VT.getVectorNumElements();
5467 unsigned PFIndexes[4];
5468 for (unsigned i = 0; i != 4; ++i) {
5469 if (ShuffleMask[i] < 0)
5472 PFIndexes[i] = ShuffleMask[i];
5475 // Compute the index in the perfect shuffle table.
5476 unsigned PFTableIndex =
5477 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5478 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5479 unsigned Cost = (PFEntry >> 30);
5482 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5485 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5486 if (EltSize >= 32) {
5487 // Do the expansion with floating-point types, since that is what the VFP
5488 // registers are defined to use, and since i64 is not legal.
5489 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5490 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5491 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5492 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5493 SmallVector<SDValue, 8> Ops;
5494 for (unsigned i = 0; i < NumElts; ++i) {
5495 if (ShuffleMask[i] < 0)
5496 Ops.push_back(DAG.getUNDEF(EltVT));
5498 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5499 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5500 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5503 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5504 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5507 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5508 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5510 if (VT == MVT::v8i8) {
5511 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5512 if (NewOp.getNode())
5519 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5520 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5521 SDValue Lane = Op.getOperand(2);
5522 if (!isa<ConstantSDNode>(Lane))
5528 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5529 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5530 SDValue Lane = Op.getOperand(1);
5531 if (!isa<ConstantSDNode>(Lane))
5534 SDValue Vec = Op.getOperand(0);
5535 if (Op.getValueType() == MVT::i32 &&
5536 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5538 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5544 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5545 // The only time a CONCAT_VECTORS operation can have legal types is when
5546 // two 64-bit vectors are concatenated to a 128-bit vector.
5547 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5548 "unexpected CONCAT_VECTORS");
5550 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5551 SDValue Op0 = Op.getOperand(0);
5552 SDValue Op1 = Op.getOperand(1);
5553 if (Op0.getOpcode() != ISD::UNDEF)
5554 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5555 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5556 DAG.getIntPtrConstant(0));
5557 if (Op1.getOpcode() != ISD::UNDEF)
5558 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5559 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5560 DAG.getIntPtrConstant(1));
5561 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5564 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5565 /// element has been zero/sign-extended, depending on the isSigned parameter,
5566 /// from an integer type half its size.
5567 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5569 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5570 EVT VT = N->getValueType(0);
5571 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5572 SDNode *BVN = N->getOperand(0).getNode();
5573 if (BVN->getValueType(0) != MVT::v4i32 ||
5574 BVN->getOpcode() != ISD::BUILD_VECTOR)
5576 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5577 unsigned HiElt = 1 - LoElt;
5578 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5579 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5580 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5581 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5582 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5585 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5586 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5589 if (Hi0->isNullValue() && Hi1->isNullValue())
5595 if (N->getOpcode() != ISD::BUILD_VECTOR)
5598 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5599 SDNode *Elt = N->getOperand(i).getNode();
5600 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5601 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5602 unsigned HalfSize = EltSize / 2;
5604 if (!isIntN(HalfSize, C->getSExtValue()))
5607 if (!isUIntN(HalfSize, C->getZExtValue()))
5618 /// isSignExtended - Check if a node is a vector value that is sign-extended
5619 /// or a constant BUILD_VECTOR with sign-extended elements.
5620 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5621 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5623 if (isExtendedBUILD_VECTOR(N, DAG, true))
5628 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5629 /// or a constant BUILD_VECTOR with zero-extended elements.
5630 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5631 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5633 if (isExtendedBUILD_VECTOR(N, DAG, false))
5638 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5639 if (OrigVT.getSizeInBits() >= 64)
5642 assert(OrigVT.isSimple() && "Expecting a simple value type");
5644 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5645 switch (OrigSimpleTy) {
5646 default: llvm_unreachable("Unexpected Vector Type");
5655 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5656 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5657 /// We insert the required extension here to get the vector to fill a D register.
5658 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5661 unsigned ExtOpcode) {
5662 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5663 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5664 // 64-bits we need to insert a new extension so that it will be 64-bits.
5665 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5666 if (OrigTy.getSizeInBits() >= 64)
5669 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5670 EVT NewVT = getExtensionTo64Bits(OrigTy);
5672 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5675 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5676 /// does not do any sign/zero extension. If the original vector is less
5677 /// than 64 bits, an appropriate extension will be added after the load to
5678 /// reach a total size of 64 bits. We have to add the extension separately
5679 /// because ARM does not have a sign/zero extending load for vectors.
5680 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5681 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5683 // The load already has the right type.
5684 if (ExtendedTy == LD->getMemoryVT())
5685 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5686 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5687 LD->isNonTemporal(), LD->isInvariant(),
5688 LD->getAlignment());
5690 // We need to create a zextload/sextload. We cannot just create a load
5691 // followed by a zext/zext node because LowerMUL is also run during normal
5692 // operation legalization where we can't create illegal types.
5693 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5694 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5695 LD->getMemoryVT(), LD->isVolatile(),
5696 LD->isNonTemporal(), LD->getAlignment());
5699 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5700 /// extending load, or BUILD_VECTOR with extended elements, return the
5701 /// unextended value. The unextended vector should be 64 bits so that it can
5702 /// be used as an operand to a VMULL instruction. If the original vector size
5703 /// before extension is less than 64 bits we add a an extension to resize
5704 /// the vector to 64 bits.
5705 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5706 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5707 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5708 N->getOperand(0)->getValueType(0),
5712 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5713 return SkipLoadExtensionForVMULL(LD, DAG);
5715 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5716 // have been legalized as a BITCAST from v4i32.
5717 if (N->getOpcode() == ISD::BITCAST) {
5718 SDNode *BVN = N->getOperand(0).getNode();
5719 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5720 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5721 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5722 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5723 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5725 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5726 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5727 EVT VT = N->getValueType(0);
5728 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5729 unsigned NumElts = VT.getVectorNumElements();
5730 MVT TruncVT = MVT::getIntegerVT(EltSize);
5731 SmallVector<SDValue, 8> Ops;
5732 for (unsigned i = 0; i != NumElts; ++i) {
5733 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5734 const APInt &CInt = C->getAPIntValue();
5735 // Element types smaller than 32 bits are not legal, so use i32 elements.
5736 // The values are implicitly truncated so sext vs. zext doesn't matter.
5737 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5739 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5740 MVT::getVectorVT(TruncVT, NumElts), Ops);
5743 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5744 unsigned Opcode = N->getOpcode();
5745 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5746 SDNode *N0 = N->getOperand(0).getNode();
5747 SDNode *N1 = N->getOperand(1).getNode();
5748 return N0->hasOneUse() && N1->hasOneUse() &&
5749 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5754 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5755 unsigned Opcode = N->getOpcode();
5756 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5757 SDNode *N0 = N->getOperand(0).getNode();
5758 SDNode *N1 = N->getOperand(1).getNode();
5759 return N0->hasOneUse() && N1->hasOneUse() &&
5760 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5765 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5766 // Multiplications are only custom-lowered for 128-bit vectors so that
5767 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5768 EVT VT = Op.getValueType();
5769 assert(VT.is128BitVector() && VT.isInteger() &&
5770 "unexpected type for custom-lowering ISD::MUL");
5771 SDNode *N0 = Op.getOperand(0).getNode();
5772 SDNode *N1 = Op.getOperand(1).getNode();
5773 unsigned NewOpc = 0;
5775 bool isN0SExt = isSignExtended(N0, DAG);
5776 bool isN1SExt = isSignExtended(N1, DAG);
5777 if (isN0SExt && isN1SExt)
5778 NewOpc = ARMISD::VMULLs;
5780 bool isN0ZExt = isZeroExtended(N0, DAG);
5781 bool isN1ZExt = isZeroExtended(N1, DAG);
5782 if (isN0ZExt && isN1ZExt)
5783 NewOpc = ARMISD::VMULLu;
5784 else if (isN1SExt || isN1ZExt) {
5785 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5786 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5787 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5788 NewOpc = ARMISD::VMULLs;
5790 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5791 NewOpc = ARMISD::VMULLu;
5793 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5795 NewOpc = ARMISD::VMULLu;
5801 if (VT == MVT::v2i64)
5802 // Fall through to expand this. It is not legal.
5805 // Other vector multiplications are legal.
5810 // Legalize to a VMULL instruction.
5813 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5815 Op0 = SkipExtensionForVMULL(N0, DAG);
5816 assert(Op0.getValueType().is64BitVector() &&
5817 Op1.getValueType().is64BitVector() &&
5818 "unexpected types for extended operands to VMULL");
5819 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5822 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5823 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5830 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5831 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5832 EVT Op1VT = Op1.getValueType();
5833 return DAG.getNode(N0->getOpcode(), DL, VT,
5834 DAG.getNode(NewOpc, DL, VT,
5835 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5836 DAG.getNode(NewOpc, DL, VT,
5837 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5841 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5843 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5844 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5845 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5846 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5847 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5848 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5849 // Get reciprocal estimate.
5850 // float4 recip = vrecpeq_f32(yf);
5851 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5852 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5853 // Because char has a smaller range than uchar, we can actually get away
5854 // without any newton steps. This requires that we use a weird bias
5855 // of 0xb000, however (again, this has been exhaustively tested).
5856 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5857 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5858 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5859 Y = DAG.getConstant(0xb000, MVT::i32);
5860 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5861 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5862 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5863 // Convert back to short.
5864 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5865 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5870 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5872 // Convert to float.
5873 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5874 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5875 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5876 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5877 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5878 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5880 // Use reciprocal estimate and one refinement step.
5881 // float4 recip = vrecpeq_f32(yf);
5882 // recip *= vrecpsq_f32(yf, recip);
5883 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5884 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5885 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5886 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5888 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5889 // Because short has a smaller range than ushort, we can actually get away
5890 // with only a single newton step. This requires that we use a weird bias
5891 // of 89, however (again, this has been exhaustively tested).
5892 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5893 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5894 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5895 N1 = DAG.getConstant(0x89, MVT::i32);
5896 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5897 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5898 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5899 // Convert back to integer and return.
5900 // return vmovn_s32(vcvt_s32_f32(result));
5901 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5902 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5906 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5907 EVT VT = Op.getValueType();
5908 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5909 "unexpected type for custom-lowering ISD::SDIV");
5912 SDValue N0 = Op.getOperand(0);
5913 SDValue N1 = Op.getOperand(1);
5916 if (VT == MVT::v8i8) {
5917 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5918 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5920 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5921 DAG.getIntPtrConstant(4));
5922 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5923 DAG.getIntPtrConstant(4));
5924 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5925 DAG.getIntPtrConstant(0));
5926 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5927 DAG.getIntPtrConstant(0));
5929 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5930 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5932 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5933 N0 = LowerCONCAT_VECTORS(N0, DAG);
5935 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5938 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5941 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5942 EVT VT = Op.getValueType();
5943 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5944 "unexpected type for custom-lowering ISD::UDIV");
5947 SDValue N0 = Op.getOperand(0);
5948 SDValue N1 = Op.getOperand(1);
5951 if (VT == MVT::v8i8) {
5952 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5953 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5955 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5956 DAG.getIntPtrConstant(4));
5957 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5958 DAG.getIntPtrConstant(4));
5959 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5960 DAG.getIntPtrConstant(0));
5961 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5962 DAG.getIntPtrConstant(0));
5964 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5965 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5967 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5968 N0 = LowerCONCAT_VECTORS(N0, DAG);
5970 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5971 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5976 // v4i16 sdiv ... Convert to float.
5977 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5978 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5979 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5980 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5981 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5982 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5984 // Use reciprocal estimate and two refinement steps.
5985 // float4 recip = vrecpeq_f32(yf);
5986 // recip *= vrecpsq_f32(yf, recip);
5987 // recip *= vrecpsq_f32(yf, recip);
5988 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5989 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5990 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5991 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5993 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5994 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5995 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5997 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5998 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5999 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6000 // and that it will never cause us to return an answer too large).
6001 // float4 result = as_float4(as_int4(xf*recip) + 2);
6002 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6003 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6004 N1 = DAG.getConstant(2, MVT::i32);
6005 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6006 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6007 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6008 // Convert back to integer and return.
6009 // return vmovn_u32(vcvt_s32_f32(result));
6010 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6011 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6015 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6016 EVT VT = Op.getNode()->getValueType(0);
6017 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6020 bool ExtraOp = false;
6021 switch (Op.getOpcode()) {
6022 default: llvm_unreachable("Invalid code");
6023 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6024 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6025 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6026 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6030 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6032 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6033 Op.getOperand(1), Op.getOperand(2));
6036 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6037 assert(Subtarget->isTargetDarwin());
6039 // For iOS, we want to call an alternative entry point: __sincos_stret,
6040 // return values are passed via sret.
6042 SDValue Arg = Op.getOperand(0);
6043 EVT ArgVT = Arg.getValueType();
6044 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6046 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6047 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6049 // Pair of floats / doubles used to pass the result.
6050 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6052 // Create stack object for sret.
6053 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6054 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6055 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6056 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6062 Entry.Ty = RetTy->getPointerTo();
6063 Entry.isSExt = false;
6064 Entry.isZExt = false;
6065 Entry.isSRet = true;
6066 Args.push_back(Entry);
6070 Entry.isSExt = false;
6071 Entry.isZExt = false;
6072 Args.push_back(Entry);
6074 const char *LibcallName = (ArgVT == MVT::f64)
6075 ? "__sincos_stret" : "__sincosf_stret";
6076 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6078 TargetLowering::CallLoweringInfo CLI(DAG);
6079 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6080 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6082 .setDiscardResult();
6084 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6086 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6087 MachinePointerInfo(), false, false, false, 0);
6089 // Address of cos field.
6090 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6091 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6092 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6093 MachinePointerInfo(), false, false, false, 0);
6095 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6096 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6097 LoadSin.getValue(0), LoadCos.getValue(0));
6100 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6101 // Monotonic load/store is legal for all targets
6102 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6105 // Acquire/Release load/store is not legal for targets without a
6106 // dmb or equivalent available.
6110 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6111 SmallVectorImpl<SDValue> &Results,
6113 const ARMSubtarget *Subtarget) {
6115 SDValue Cycles32, OutChain;
6117 if (Subtarget->hasPerfMon()) {
6118 // Under Power Management extensions, the cycle-count is:
6119 // mrc p15, #0, <Rt>, c9, c13, #0
6120 SDValue Ops[] = { N->getOperand(0), // Chain
6121 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6122 DAG.getConstant(15, MVT::i32),
6123 DAG.getConstant(0, MVT::i32),
6124 DAG.getConstant(9, MVT::i32),
6125 DAG.getConstant(13, MVT::i32),
6126 DAG.getConstant(0, MVT::i32)
6129 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6130 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6131 OutChain = Cycles32.getValue(1);
6133 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6134 // there are older ARM CPUs that have implementation-specific ways of
6135 // obtaining this information (FIXME!).
6136 Cycles32 = DAG.getConstant(0, MVT::i32);
6137 OutChain = DAG.getEntryNode();
6141 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6142 Cycles32, DAG.getConstant(0, MVT::i32));
6143 Results.push_back(Cycles64);
6144 Results.push_back(OutChain);
6147 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6148 switch (Op.getOpcode()) {
6149 default: llvm_unreachable("Don't know how to custom lower this!");
6150 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6151 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6152 case ISD::GlobalAddress:
6153 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6154 default: llvm_unreachable("unknown object format");
6156 return LowerGlobalAddressWindows(Op, DAG);
6158 return LowerGlobalAddressELF(Op, DAG);
6160 return LowerGlobalAddressDarwin(Op, DAG);
6162 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6163 case ISD::SELECT: return LowerSELECT(Op, DAG);
6164 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6165 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6166 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6167 case ISD::VASTART: return LowerVASTART(Op, DAG);
6168 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6169 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6170 case ISD::SINT_TO_FP:
6171 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6172 case ISD::FP_TO_SINT:
6173 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6174 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6175 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6176 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6177 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6178 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6179 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6180 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6182 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6185 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6186 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6187 case ISD::SRL_PARTS:
6188 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6189 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6190 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6191 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6192 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6193 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6194 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6195 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6196 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6197 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6198 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6199 case ISD::MUL: return LowerMUL(Op, DAG);
6200 case ISD::SDIV: return LowerSDIV(Op, DAG);
6201 case ISD::UDIV: return LowerUDIV(Op, DAG);
6205 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6210 return LowerXALUO(Op, DAG);
6211 case ISD::ATOMIC_LOAD:
6212 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6213 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6215 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6219 /// ReplaceNodeResults - Replace the results of node with an illegal result
6220 /// type with new values built out of custom code.
6221 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6222 SmallVectorImpl<SDValue>&Results,
6223 SelectionDAG &DAG) const {
6225 switch (N->getOpcode()) {
6227 llvm_unreachable("Don't know how to custom expand this!");
6229 Res = ExpandBITCAST(N, DAG);
6233 Res = Expand64BitShift(N, DAG, Subtarget);
6235 case ISD::READCYCLECOUNTER:
6236 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6240 Results.push_back(Res);
6243 //===----------------------------------------------------------------------===//
6244 // ARM Scheduler Hooks
6245 //===----------------------------------------------------------------------===//
6247 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6248 /// registers the function context.
6249 void ARMTargetLowering::
6250 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6251 MachineBasicBlock *DispatchBB, int FI) const {
6252 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6253 DebugLoc dl = MI->getDebugLoc();
6254 MachineFunction *MF = MBB->getParent();
6255 MachineRegisterInfo *MRI = &MF->getRegInfo();
6256 MachineConstantPool *MCP = MF->getConstantPool();
6257 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6258 const Function *F = MF->getFunction();
6260 bool isThumb = Subtarget->isThumb();
6261 bool isThumb2 = Subtarget->isThumb2();
6263 unsigned PCLabelId = AFI->createPICLabelUId();
6264 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6265 ARMConstantPoolValue *CPV =
6266 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6267 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6269 const TargetRegisterClass *TRC = isThumb ?
6270 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6271 (const TargetRegisterClass*)&ARM::GPRRegClass;
6273 // Grab constant pool and fixed stack memory operands.
6274 MachineMemOperand *CPMMO =
6275 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6276 MachineMemOperand::MOLoad, 4, 4);
6278 MachineMemOperand *FIMMOSt =
6279 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6280 MachineMemOperand::MOStore, 4, 4);
6282 // Load the address of the dispatch MBB into the jump buffer.
6284 // Incoming value: jbuf
6285 // ldr.n r5, LCPI1_1
6288 // str r5, [$jbuf, #+4] ; &jbuf[1]
6289 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6290 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6291 .addConstantPoolIndex(CPI)
6292 .addMemOperand(CPMMO));
6293 // Set the low bit because of thumb mode.
6294 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6296 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6297 .addReg(NewVReg1, RegState::Kill)
6299 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6300 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6301 .addReg(NewVReg2, RegState::Kill)
6303 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6304 .addReg(NewVReg3, RegState::Kill)
6306 .addImm(36) // &jbuf[1] :: pc
6307 .addMemOperand(FIMMOSt));
6308 } else if (isThumb) {
6309 // Incoming value: jbuf
6310 // ldr.n r1, LCPI1_4
6314 // add r2, $jbuf, #+4 ; &jbuf[1]
6316 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6317 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6318 .addConstantPoolIndex(CPI)
6319 .addMemOperand(CPMMO));
6320 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6321 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6322 .addReg(NewVReg1, RegState::Kill)
6324 // Set the low bit because of thumb mode.
6325 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6326 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6327 .addReg(ARM::CPSR, RegState::Define)
6329 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6330 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6331 .addReg(ARM::CPSR, RegState::Define)
6332 .addReg(NewVReg2, RegState::Kill)
6333 .addReg(NewVReg3, RegState::Kill));
6334 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6335 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6337 .addImm(36)); // &jbuf[1] :: pc
6338 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6339 .addReg(NewVReg4, RegState::Kill)
6340 .addReg(NewVReg5, RegState::Kill)
6342 .addMemOperand(FIMMOSt));
6344 // Incoming value: jbuf
6347 // str r1, [$jbuf, #+4] ; &jbuf[1]
6348 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6349 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6350 .addConstantPoolIndex(CPI)
6352 .addMemOperand(CPMMO));
6353 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6354 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6355 .addReg(NewVReg1, RegState::Kill)
6356 .addImm(PCLabelId));
6357 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6358 .addReg(NewVReg2, RegState::Kill)
6360 .addImm(36) // &jbuf[1] :: pc
6361 .addMemOperand(FIMMOSt));
6365 MachineBasicBlock *ARMTargetLowering::
6366 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6367 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6368 DebugLoc dl = MI->getDebugLoc();
6369 MachineFunction *MF = MBB->getParent();
6370 MachineRegisterInfo *MRI = &MF->getRegInfo();
6371 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6372 MachineFrameInfo *MFI = MF->getFrameInfo();
6373 int FI = MFI->getFunctionContextIndex();
6375 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6376 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6377 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6379 // Get a mapping of the call site numbers to all of the landing pads they're
6381 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6382 unsigned MaxCSNum = 0;
6383 MachineModuleInfo &MMI = MF->getMMI();
6384 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6386 if (!BB->isLandingPad()) continue;
6388 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6390 for (MachineBasicBlock::iterator
6391 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6392 if (!II->isEHLabel()) continue;
6394 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6395 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6397 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6398 for (SmallVectorImpl<unsigned>::iterator
6399 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6400 CSI != CSE; ++CSI) {
6401 CallSiteNumToLPad[*CSI].push_back(BB);
6402 MaxCSNum = std::max(MaxCSNum, *CSI);
6408 // Get an ordered list of the machine basic blocks for the jump table.
6409 std::vector<MachineBasicBlock*> LPadList;
6410 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6411 LPadList.reserve(CallSiteNumToLPad.size());
6412 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6413 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6414 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6415 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6416 LPadList.push_back(*II);
6417 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6421 assert(!LPadList.empty() &&
6422 "No landing pad destinations for the dispatch jump table!");
6424 // Create the jump table and associated information.
6425 MachineJumpTableInfo *JTI =
6426 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6427 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6428 unsigned UId = AFI->createJumpTableUId();
6429 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6431 // Create the MBBs for the dispatch code.
6433 // Shove the dispatch's address into the return slot in the function context.
6434 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6435 DispatchBB->setIsLandingPad();
6437 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6438 unsigned trap_opcode;
6439 if (Subtarget->isThumb())
6440 trap_opcode = ARM::tTRAP;
6442 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6444 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6445 DispatchBB->addSuccessor(TrapBB);
6447 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6448 DispatchBB->addSuccessor(DispContBB);
6451 MF->insert(MF->end(), DispatchBB);
6452 MF->insert(MF->end(), DispContBB);
6453 MF->insert(MF->end(), TrapBB);
6455 // Insert code into the entry block that creates and registers the function
6457 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6459 MachineMemOperand *FIMMOLd =
6460 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6461 MachineMemOperand::MOLoad |
6462 MachineMemOperand::MOVolatile, 4, 4);
6464 MachineInstrBuilder MIB;
6465 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6467 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6468 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6470 // Add a register mask with no preserved registers. This results in all
6471 // registers being marked as clobbered.
6472 MIB.addRegMask(RI.getNoPreservedMask());
6474 unsigned NumLPads = LPadList.size();
6475 if (Subtarget->isThumb2()) {
6476 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6477 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6480 .addMemOperand(FIMMOLd));
6482 if (NumLPads < 256) {
6483 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6485 .addImm(LPadList.size()));
6487 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6488 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6489 .addImm(NumLPads & 0xFFFF));
6491 unsigned VReg2 = VReg1;
6492 if ((NumLPads & 0xFFFF0000) != 0) {
6493 VReg2 = MRI->createVirtualRegister(TRC);
6494 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6496 .addImm(NumLPads >> 16));
6499 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6504 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6509 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6510 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6511 .addJumpTableIndex(MJTI)
6514 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6517 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6518 .addReg(NewVReg3, RegState::Kill)
6520 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6522 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6523 .addReg(NewVReg4, RegState::Kill)
6525 .addJumpTableIndex(MJTI)
6527 } else if (Subtarget->isThumb()) {
6528 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6529 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6532 .addMemOperand(FIMMOLd));
6534 if (NumLPads < 256) {
6535 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6539 MachineConstantPool *ConstantPool = MF->getConstantPool();
6540 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6541 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6543 // MachineConstantPool wants an explicit alignment.
6544 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6546 Align = getDataLayout()->getTypeAllocSize(C->getType());
6547 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6549 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6550 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6551 .addReg(VReg1, RegState::Define)
6552 .addConstantPoolIndex(Idx));
6553 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6558 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6563 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6564 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6565 .addReg(ARM::CPSR, RegState::Define)
6569 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6570 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6571 .addJumpTableIndex(MJTI)
6574 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6575 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6576 .addReg(ARM::CPSR, RegState::Define)
6577 .addReg(NewVReg2, RegState::Kill)
6580 MachineMemOperand *JTMMOLd =
6581 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6582 MachineMemOperand::MOLoad, 4, 4);
6584 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6585 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6586 .addReg(NewVReg4, RegState::Kill)
6588 .addMemOperand(JTMMOLd));
6590 unsigned NewVReg6 = NewVReg5;
6591 if (RelocM == Reloc::PIC_) {
6592 NewVReg6 = MRI->createVirtualRegister(TRC);
6593 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6594 .addReg(ARM::CPSR, RegState::Define)
6595 .addReg(NewVReg5, RegState::Kill)
6599 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6600 .addReg(NewVReg6, RegState::Kill)
6601 .addJumpTableIndex(MJTI)
6604 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6605 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6608 .addMemOperand(FIMMOLd));
6610 if (NumLPads < 256) {
6611 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6614 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6615 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6616 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6617 .addImm(NumLPads & 0xFFFF));
6619 unsigned VReg2 = VReg1;
6620 if ((NumLPads & 0xFFFF0000) != 0) {
6621 VReg2 = MRI->createVirtualRegister(TRC);
6622 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6624 .addImm(NumLPads >> 16));
6627 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6631 MachineConstantPool *ConstantPool = MF->getConstantPool();
6632 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6633 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6635 // MachineConstantPool wants an explicit alignment.
6636 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6638 Align = getDataLayout()->getTypeAllocSize(C->getType());
6639 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6641 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6642 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6643 .addReg(VReg1, RegState::Define)
6644 .addConstantPoolIndex(Idx)
6646 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6648 .addReg(VReg1, RegState::Kill));
6651 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6656 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6658 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6660 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6661 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6662 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6663 .addJumpTableIndex(MJTI)
6666 MachineMemOperand *JTMMOLd =
6667 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6668 MachineMemOperand::MOLoad, 4, 4);
6669 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6671 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6672 .addReg(NewVReg3, RegState::Kill)
6675 .addMemOperand(JTMMOLd));
6677 if (RelocM == Reloc::PIC_) {
6678 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6679 .addReg(NewVReg5, RegState::Kill)
6681 .addJumpTableIndex(MJTI)
6684 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6685 .addReg(NewVReg5, RegState::Kill)
6686 .addJumpTableIndex(MJTI)
6691 // Add the jump table entries as successors to the MBB.
6692 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6693 for (std::vector<MachineBasicBlock*>::iterator
6694 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6695 MachineBasicBlock *CurMBB = *I;
6696 if (SeenMBBs.insert(CurMBB))
6697 DispContBB->addSuccessor(CurMBB);
6700 // N.B. the order the invoke BBs are processed in doesn't matter here.
6701 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6702 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6703 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6704 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6705 MachineBasicBlock *BB = *I;
6707 // Remove the landing pad successor from the invoke block and replace it
6708 // with the new dispatch block.
6709 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6711 while (!Successors.empty()) {
6712 MachineBasicBlock *SMBB = Successors.pop_back_val();
6713 if (SMBB->isLandingPad()) {
6714 BB->removeSuccessor(SMBB);
6715 MBBLPads.push_back(SMBB);
6719 BB->addSuccessor(DispatchBB);
6721 // Find the invoke call and mark all of the callee-saved registers as
6722 // 'implicit defined' so that they're spilled. This prevents code from
6723 // moving instructions to before the EH block, where they will never be
6725 for (MachineBasicBlock::reverse_iterator
6726 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6727 if (!II->isCall()) continue;
6729 DenseMap<unsigned, bool> DefRegs;
6730 for (MachineInstr::mop_iterator
6731 OI = II->operands_begin(), OE = II->operands_end();
6733 if (!OI->isReg()) continue;
6734 DefRegs[OI->getReg()] = true;
6737 MachineInstrBuilder MIB(*MF, &*II);
6739 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6740 unsigned Reg = SavedRegs[i];
6741 if (Subtarget->isThumb2() &&
6742 !ARM::tGPRRegClass.contains(Reg) &&
6743 !ARM::hGPRRegClass.contains(Reg))
6745 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6747 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6750 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6757 // Mark all former landing pads as non-landing pads. The dispatch is the only
6759 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6760 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6761 (*I)->setIsLandingPad(false);
6763 // The instruction is gone now.
6764 MI->eraseFromParent();
6770 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6771 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6772 E = MBB->succ_end(); I != E; ++I)
6775 llvm_unreachable("Expecting a BB with two successors!");
6778 /// Return the load opcode for a given load size. If load size >= 8,
6779 /// neon opcode will be returned.
6780 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6782 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6783 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6785 return LdSize == 4 ? ARM::tLDRi
6786 : LdSize == 2 ? ARM::tLDRHi
6787 : LdSize == 1 ? ARM::tLDRBi : 0;
6789 return LdSize == 4 ? ARM::t2LDR_POST
6790 : LdSize == 2 ? ARM::t2LDRH_POST
6791 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6792 return LdSize == 4 ? ARM::LDR_POST_IMM
6793 : LdSize == 2 ? ARM::LDRH_POST
6794 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6797 /// Return the store opcode for a given store size. If store size >= 8,
6798 /// neon opcode will be returned.
6799 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6801 return StSize == 16 ? ARM::VST1q32wb_fixed
6802 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6804 return StSize == 4 ? ARM::tSTRi
6805 : StSize == 2 ? ARM::tSTRHi
6806 : StSize == 1 ? ARM::tSTRBi : 0;
6808 return StSize == 4 ? ARM::t2STR_POST
6809 : StSize == 2 ? ARM::t2STRH_POST
6810 : StSize == 1 ? ARM::t2STRB_POST : 0;
6811 return StSize == 4 ? ARM::STR_POST_IMM
6812 : StSize == 2 ? ARM::STRH_POST
6813 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6816 /// Emit a post-increment load operation with given size. The instructions
6817 /// will be added to BB at Pos.
6818 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6819 const TargetInstrInfo *TII, DebugLoc dl,
6820 unsigned LdSize, unsigned Data, unsigned AddrIn,
6821 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6822 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6823 assert(LdOpc != 0 && "Should have a load opcode");
6825 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6826 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6828 } else if (IsThumb1) {
6829 // load + update AddrIn
6830 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6831 .addReg(AddrIn).addImm(0));
6832 MachineInstrBuilder MIB =
6833 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6834 MIB = AddDefaultT1CC(MIB);
6835 MIB.addReg(AddrIn).addImm(LdSize);
6836 AddDefaultPred(MIB);
6837 } else if (IsThumb2) {
6838 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6839 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6842 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6843 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6844 .addReg(0).addImm(LdSize));
6848 /// Emit a post-increment store operation with given size. The instructions
6849 /// will be added to BB at Pos.
6850 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6851 const TargetInstrInfo *TII, DebugLoc dl,
6852 unsigned StSize, unsigned Data, unsigned AddrIn,
6853 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6854 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6855 assert(StOpc != 0 && "Should have a store opcode");
6857 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6858 .addReg(AddrIn).addImm(0).addReg(Data));
6859 } else if (IsThumb1) {
6860 // store + update AddrIn
6861 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6862 .addReg(AddrIn).addImm(0));
6863 MachineInstrBuilder MIB =
6864 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6865 MIB = AddDefaultT1CC(MIB);
6866 MIB.addReg(AddrIn).addImm(StSize);
6867 AddDefaultPred(MIB);
6868 } else if (IsThumb2) {
6869 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6870 .addReg(Data).addReg(AddrIn).addImm(StSize));
6872 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6873 .addReg(Data).addReg(AddrIn).addReg(0)
6879 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6880 MachineBasicBlock *BB) const {
6881 // This pseudo instruction has 3 operands: dst, src, size
6882 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6883 // Otherwise, we will generate unrolled scalar copies.
6884 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6885 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6886 MachineFunction::iterator It = BB;
6889 unsigned dest = MI->getOperand(0).getReg();
6890 unsigned src = MI->getOperand(1).getReg();
6891 unsigned SizeVal = MI->getOperand(2).getImm();
6892 unsigned Align = MI->getOperand(3).getImm();
6893 DebugLoc dl = MI->getDebugLoc();
6895 MachineFunction *MF = BB->getParent();
6896 MachineRegisterInfo &MRI = MF->getRegInfo();
6897 unsigned UnitSize = 0;
6898 const TargetRegisterClass *TRC = nullptr;
6899 const TargetRegisterClass *VecTRC = nullptr;
6901 bool IsThumb1 = Subtarget->isThumb1Only();
6902 bool IsThumb2 = Subtarget->isThumb2();
6906 } else if (Align & 2) {
6909 // Check whether we can use NEON instructions.
6910 if (!MF->getFunction()->getAttributes().
6911 hasAttribute(AttributeSet::FunctionIndex,
6912 Attribute::NoImplicitFloat) &&
6913 Subtarget->hasNEON()) {
6914 if ((Align % 16 == 0) && SizeVal >= 16)
6916 else if ((Align % 8 == 0) && SizeVal >= 8)
6919 // Can't use NEON instructions.
6924 // Select the correct opcode and register class for unit size load/store
6925 bool IsNeon = UnitSize >= 8;
6926 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6927 : (const TargetRegisterClass *)&ARM::GPRRegClass;
6929 VecTRC = UnitSize == 16
6930 ? (const TargetRegisterClass *)&ARM::DPairRegClass
6932 ? (const TargetRegisterClass *)&ARM::DPRRegClass
6935 unsigned BytesLeft = SizeVal % UnitSize;
6936 unsigned LoopSize = SizeVal - BytesLeft;
6938 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6939 // Use LDR and STR to copy.
6940 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6941 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6942 unsigned srcIn = src;
6943 unsigned destIn = dest;
6944 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6945 unsigned srcOut = MRI.createVirtualRegister(TRC);
6946 unsigned destOut = MRI.createVirtualRegister(TRC);
6947 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6948 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6949 IsThumb1, IsThumb2);
6950 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6951 IsThumb1, IsThumb2);
6956 // Handle the leftover bytes with LDRB and STRB.
6957 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6958 // [destOut] = STRB_POST(scratch, destIn, 1)
6959 for (unsigned i = 0; i < BytesLeft; i++) {
6960 unsigned srcOut = MRI.createVirtualRegister(TRC);
6961 unsigned destOut = MRI.createVirtualRegister(TRC);
6962 unsigned scratch = MRI.createVirtualRegister(TRC);
6963 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6964 IsThumb1, IsThumb2);
6965 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6966 IsThumb1, IsThumb2);
6970 MI->eraseFromParent(); // The instruction is gone now.
6974 // Expand the pseudo op to a loop.
6977 // movw varEnd, # --> with thumb2
6979 // ldrcp varEnd, idx --> without thumb2
6980 // fallthrough --> loopMBB
6982 // PHI varPhi, varEnd, varLoop
6983 // PHI srcPhi, src, srcLoop
6984 // PHI destPhi, dst, destLoop
6985 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6986 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6987 // subs varLoop, varPhi, #UnitSize
6989 // fallthrough --> exitMBB
6991 // epilogue to handle left-over bytes
6992 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6993 // [destOut] = STRB_POST(scratch, destLoop, 1)
6994 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6995 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6996 MF->insert(It, loopMBB);
6997 MF->insert(It, exitMBB);
6999 // Transfer the remainder of BB and its successor edges to exitMBB.
7000 exitMBB->splice(exitMBB->begin(), BB,
7001 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7002 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7004 // Load an immediate to varEnd.
7005 unsigned varEnd = MRI.createVirtualRegister(TRC);
7007 unsigned Vtmp = varEnd;
7008 if ((LoopSize & 0xFFFF0000) != 0)
7009 Vtmp = MRI.createVirtualRegister(TRC);
7010 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7011 .addImm(LoopSize & 0xFFFF));
7013 if ((LoopSize & 0xFFFF0000) != 0)
7014 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7015 .addReg(Vtmp).addImm(LoopSize >> 16));
7017 MachineConstantPool *ConstantPool = MF->getConstantPool();
7018 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7019 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7021 // MachineConstantPool wants an explicit alignment.
7022 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7024 Align = getDataLayout()->getTypeAllocSize(C->getType());
7025 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7028 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7029 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7031 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7032 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7034 BB->addSuccessor(loopMBB);
7036 // Generate the loop body:
7037 // varPhi = PHI(varLoop, varEnd)
7038 // srcPhi = PHI(srcLoop, src)
7039 // destPhi = PHI(destLoop, dst)
7040 MachineBasicBlock *entryBB = BB;
7042 unsigned varLoop = MRI.createVirtualRegister(TRC);
7043 unsigned varPhi = MRI.createVirtualRegister(TRC);
7044 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7045 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7046 unsigned destLoop = MRI.createVirtualRegister(TRC);
7047 unsigned destPhi = MRI.createVirtualRegister(TRC);
7049 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7050 .addReg(varLoop).addMBB(loopMBB)
7051 .addReg(varEnd).addMBB(entryBB);
7052 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7053 .addReg(srcLoop).addMBB(loopMBB)
7054 .addReg(src).addMBB(entryBB);
7055 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7056 .addReg(destLoop).addMBB(loopMBB)
7057 .addReg(dest).addMBB(entryBB);
7059 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7060 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7061 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7062 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7063 IsThumb1, IsThumb2);
7064 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7065 IsThumb1, IsThumb2);
7067 // Decrement loop variable by UnitSize.
7069 MachineInstrBuilder MIB =
7070 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7071 MIB = AddDefaultT1CC(MIB);
7072 MIB.addReg(varPhi).addImm(UnitSize);
7073 AddDefaultPred(MIB);
7075 MachineInstrBuilder MIB =
7076 BuildMI(*BB, BB->end(), dl,
7077 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7078 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7079 MIB->getOperand(5).setReg(ARM::CPSR);
7080 MIB->getOperand(5).setIsDef(true);
7082 BuildMI(*BB, BB->end(), dl,
7083 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7084 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7086 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7087 BB->addSuccessor(loopMBB);
7088 BB->addSuccessor(exitMBB);
7090 // Add epilogue to handle BytesLeft.
7092 MachineInstr *StartOfExit = exitMBB->begin();
7094 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7095 // [destOut] = STRB_POST(scratch, destLoop, 1)
7096 unsigned srcIn = srcLoop;
7097 unsigned destIn = destLoop;
7098 for (unsigned i = 0; i < BytesLeft; i++) {
7099 unsigned srcOut = MRI.createVirtualRegister(TRC);
7100 unsigned destOut = MRI.createVirtualRegister(TRC);
7101 unsigned scratch = MRI.createVirtualRegister(TRC);
7102 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7103 IsThumb1, IsThumb2);
7104 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7105 IsThumb1, IsThumb2);
7110 MI->eraseFromParent(); // The instruction is gone now.
7115 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7116 MachineBasicBlock *BB) const {
7117 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7118 DebugLoc dl = MI->getDebugLoc();
7119 bool isThumb2 = Subtarget->isThumb2();
7120 switch (MI->getOpcode()) {
7123 llvm_unreachable("Unexpected instr type to insert");
7125 // The Thumb2 pre-indexed stores have the same MI operands, they just
7126 // define them differently in the .td files from the isel patterns, so
7127 // they need pseudos.
7128 case ARM::t2STR_preidx:
7129 MI->setDesc(TII->get(ARM::t2STR_PRE));
7131 case ARM::t2STRB_preidx:
7132 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7134 case ARM::t2STRH_preidx:
7135 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7138 case ARM::STRi_preidx:
7139 case ARM::STRBi_preidx: {
7140 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7141 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7142 // Decode the offset.
7143 unsigned Offset = MI->getOperand(4).getImm();
7144 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7145 Offset = ARM_AM::getAM2Offset(Offset);
7149 MachineMemOperand *MMO = *MI->memoperands_begin();
7150 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7151 .addOperand(MI->getOperand(0)) // Rn_wb
7152 .addOperand(MI->getOperand(1)) // Rt
7153 .addOperand(MI->getOperand(2)) // Rn
7154 .addImm(Offset) // offset (skip GPR==zero_reg)
7155 .addOperand(MI->getOperand(5)) // pred
7156 .addOperand(MI->getOperand(6))
7157 .addMemOperand(MMO);
7158 MI->eraseFromParent();
7161 case ARM::STRr_preidx:
7162 case ARM::STRBr_preidx:
7163 case ARM::STRH_preidx: {
7165 switch (MI->getOpcode()) {
7166 default: llvm_unreachable("unexpected opcode!");
7167 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7168 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7169 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7171 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7172 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7173 MIB.addOperand(MI->getOperand(i));
7174 MI->eraseFromParent();
7178 case ARM::tMOVCCr_pseudo: {
7179 // To "insert" a SELECT_CC instruction, we actually have to insert the
7180 // diamond control-flow pattern. The incoming instruction knows the
7181 // destination vreg to set, the condition code register to branch on, the
7182 // true/false values to select between, and a branch opcode to use.
7183 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7184 MachineFunction::iterator It = BB;
7190 // cmpTY ccX, r1, r2
7192 // fallthrough --> copy0MBB
7193 MachineBasicBlock *thisMBB = BB;
7194 MachineFunction *F = BB->getParent();
7195 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7196 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7197 F->insert(It, copy0MBB);
7198 F->insert(It, sinkMBB);
7200 // Transfer the remainder of BB and its successor edges to sinkMBB.
7201 sinkMBB->splice(sinkMBB->begin(), BB,
7202 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7203 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7205 BB->addSuccessor(copy0MBB);
7206 BB->addSuccessor(sinkMBB);
7208 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7209 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7212 // %FalseValue = ...
7213 // # fallthrough to sinkMBB
7216 // Update machine-CFG edges
7217 BB->addSuccessor(sinkMBB);
7220 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7223 BuildMI(*BB, BB->begin(), dl,
7224 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7225 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7226 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7228 MI->eraseFromParent(); // The pseudo instruction is gone now.
7233 case ARM::BCCZi64: {
7234 // If there is an unconditional branch to the other successor, remove it.
7235 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7237 // Compare both parts that make up the double comparison separately for
7239 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7241 unsigned LHS1 = MI->getOperand(1).getReg();
7242 unsigned LHS2 = MI->getOperand(2).getReg();
7244 AddDefaultPred(BuildMI(BB, dl,
7245 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7246 .addReg(LHS1).addImm(0));
7247 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7248 .addReg(LHS2).addImm(0)
7249 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7251 unsigned RHS1 = MI->getOperand(3).getReg();
7252 unsigned RHS2 = MI->getOperand(4).getReg();
7253 AddDefaultPred(BuildMI(BB, dl,
7254 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7255 .addReg(LHS1).addReg(RHS1));
7256 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7257 .addReg(LHS2).addReg(RHS2)
7258 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7261 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7262 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7263 if (MI->getOperand(0).getImm() == ARMCC::NE)
7264 std::swap(destMBB, exitMBB);
7266 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7267 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7269 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7271 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7273 MI->eraseFromParent(); // The pseudo instruction is gone now.
7277 case ARM::Int_eh_sjlj_setjmp:
7278 case ARM::Int_eh_sjlj_setjmp_nofp:
7279 case ARM::tInt_eh_sjlj_setjmp:
7280 case ARM::t2Int_eh_sjlj_setjmp:
7281 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7282 EmitSjLjDispatchBlock(MI, BB);
7287 // To insert an ABS instruction, we have to insert the
7288 // diamond control-flow pattern. The incoming instruction knows the
7289 // source vreg to test against 0, the destination vreg to set,
7290 // the condition code register to branch on, the
7291 // true/false values to select between, and a branch opcode to use.
7296 // BCC (branch to SinkBB if V0 >= 0)
7297 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7298 // SinkBB: V1 = PHI(V2, V3)
7299 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7300 MachineFunction::iterator BBI = BB;
7302 MachineFunction *Fn = BB->getParent();
7303 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7304 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7305 Fn->insert(BBI, RSBBB);
7306 Fn->insert(BBI, SinkBB);
7308 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7309 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7310 bool isThumb2 = Subtarget->isThumb2();
7311 MachineRegisterInfo &MRI = Fn->getRegInfo();
7312 // In Thumb mode S must not be specified if source register is the SP or
7313 // PC and if destination register is the SP, so restrict register class
7314 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7315 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7316 (const TargetRegisterClass*)&ARM::GPRRegClass);
7318 // Transfer the remainder of BB and its successor edges to sinkMBB.
7319 SinkBB->splice(SinkBB->begin(), BB,
7320 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7321 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7323 BB->addSuccessor(RSBBB);
7324 BB->addSuccessor(SinkBB);
7326 // fall through to SinkMBB
7327 RSBBB->addSuccessor(SinkBB);
7329 // insert a cmp at the end of BB
7330 AddDefaultPred(BuildMI(BB, dl,
7331 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7332 .addReg(ABSSrcReg).addImm(0));
7334 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7336 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7337 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7339 // insert rsbri in RSBBB
7340 // Note: BCC and rsbri will be converted into predicated rsbmi
7341 // by if-conversion pass
7342 BuildMI(*RSBBB, RSBBB->begin(), dl,
7343 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7344 .addReg(ABSSrcReg, RegState::Kill)
7345 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7347 // insert PHI in SinkBB,
7348 // reuse ABSDstReg to not change uses of ABS instruction
7349 BuildMI(*SinkBB, SinkBB->begin(), dl,
7350 TII->get(ARM::PHI), ABSDstReg)
7351 .addReg(NewRsbDstReg).addMBB(RSBBB)
7352 .addReg(ABSSrcReg).addMBB(BB);
7354 // remove ABS instruction
7355 MI->eraseFromParent();
7357 // return last added BB
7360 case ARM::COPY_STRUCT_BYVAL_I32:
7362 return EmitStructByval(MI, BB);
7366 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7367 SDNode *Node) const {
7368 if (!MI->hasPostISelHook()) {
7369 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7370 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7374 const MCInstrDesc *MCID = &MI->getDesc();
7375 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7376 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7377 // operand is still set to noreg. If needed, set the optional operand's
7378 // register to CPSR, and remove the redundant implicit def.
7380 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7382 // Rename pseudo opcodes.
7383 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7385 const ARMBaseInstrInfo *TII =
7386 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7387 MCID = &TII->get(NewOpc);
7389 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7390 "converted opcode should be the same except for cc_out");
7394 // Add the optional cc_out operand
7395 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7397 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7399 // Any ARM instruction that sets the 's' bit should specify an optional
7400 // "cc_out" operand in the last operand position.
7401 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7402 assert(!NewOpc && "Optional cc_out operand required");
7405 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7406 // since we already have an optional CPSR def.
7407 bool definesCPSR = false;
7408 bool deadCPSR = false;
7409 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7411 const MachineOperand &MO = MI->getOperand(i);
7412 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7416 MI->RemoveOperand(i);
7421 assert(!NewOpc && "Optional cc_out operand required");
7424 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7426 assert(!MI->getOperand(ccOutIdx).getReg() &&
7427 "expect uninitialized optional cc_out operand");
7431 // If this instruction was defined with an optional CPSR def and its dag node
7432 // had a live implicit CPSR def, then activate the optional CPSR def.
7433 MachineOperand &MO = MI->getOperand(ccOutIdx);
7434 MO.setReg(ARM::CPSR);
7438 //===----------------------------------------------------------------------===//
7439 // ARM Optimization Hooks
7440 //===----------------------------------------------------------------------===//
7442 // Helper function that checks if N is a null or all ones constant.
7443 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7444 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7447 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7450 // Return true if N is conditionally 0 or all ones.
7451 // Detects these expressions where cc is an i1 value:
7453 // (select cc 0, y) [AllOnes=0]
7454 // (select cc y, 0) [AllOnes=0]
7455 // (zext cc) [AllOnes=0]
7456 // (sext cc) [AllOnes=0/1]
7457 // (select cc -1, y) [AllOnes=1]
7458 // (select cc y, -1) [AllOnes=1]
7460 // Invert is set when N is the null/all ones constant when CC is false.
7461 // OtherOp is set to the alternative value of N.
7462 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7463 SDValue &CC, bool &Invert,
7465 SelectionDAG &DAG) {
7466 switch (N->getOpcode()) {
7467 default: return false;
7469 CC = N->getOperand(0);
7470 SDValue N1 = N->getOperand(1);
7471 SDValue N2 = N->getOperand(2);
7472 if (isZeroOrAllOnes(N1, AllOnes)) {
7477 if (isZeroOrAllOnes(N2, AllOnes)) {
7484 case ISD::ZERO_EXTEND:
7485 // (zext cc) can never be the all ones value.
7489 case ISD::SIGN_EXTEND: {
7490 EVT VT = N->getValueType(0);
7491 CC = N->getOperand(0);
7492 if (CC.getValueType() != MVT::i1)
7496 // When looking for an AllOnes constant, N is an sext, and the 'other'
7498 OtherOp = DAG.getConstant(0, VT);
7499 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7500 // When looking for a 0 constant, N can be zext or sext.
7501 OtherOp = DAG.getConstant(1, VT);
7503 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7509 // Combine a constant select operand into its use:
7511 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7512 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7513 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7514 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7515 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7517 // The transform is rejected if the select doesn't have a constant operand that
7518 // is null, or all ones when AllOnes is set.
7520 // Also recognize sext/zext from i1:
7522 // (add (zext cc), x) -> (select cc (add x, 1), x)
7523 // (add (sext cc), x) -> (select cc (add x, -1), x)
7525 // These transformations eventually create predicated instructions.
7527 // @param N The node to transform.
7528 // @param Slct The N operand that is a select.
7529 // @param OtherOp The other N operand (x above).
7530 // @param DCI Context.
7531 // @param AllOnes Require the select constant to be all ones instead of null.
7532 // @returns The new node, or SDValue() on failure.
7534 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7535 TargetLowering::DAGCombinerInfo &DCI,
7536 bool AllOnes = false) {
7537 SelectionDAG &DAG = DCI.DAG;
7538 EVT VT = N->getValueType(0);
7539 SDValue NonConstantVal;
7542 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7543 NonConstantVal, DAG))
7546 // Slct is now know to be the desired identity constant when CC is true.
7547 SDValue TrueVal = OtherOp;
7548 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7549 OtherOp, NonConstantVal);
7550 // Unless SwapSelectOps says CC should be false.
7552 std::swap(TrueVal, FalseVal);
7554 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7555 CCOp, TrueVal, FalseVal);
7558 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7560 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7561 TargetLowering::DAGCombinerInfo &DCI) {
7562 SDValue N0 = N->getOperand(0);
7563 SDValue N1 = N->getOperand(1);
7564 if (N0.getNode()->hasOneUse()) {
7565 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7566 if (Result.getNode())
7569 if (N1.getNode()->hasOneUse()) {
7570 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7571 if (Result.getNode())
7577 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7578 // (only after legalization).
7579 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7580 TargetLowering::DAGCombinerInfo &DCI,
7581 const ARMSubtarget *Subtarget) {
7583 // Only perform optimization if after legalize, and if NEON is available. We
7584 // also expected both operands to be BUILD_VECTORs.
7585 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7586 || N0.getOpcode() != ISD::BUILD_VECTOR
7587 || N1.getOpcode() != ISD::BUILD_VECTOR)
7590 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7591 EVT VT = N->getValueType(0);
7592 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7595 // Check that the vector operands are of the right form.
7596 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7597 // operands, where N is the size of the formed vector.
7598 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7599 // index such that we have a pair wise add pattern.
7601 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7602 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7604 SDValue Vec = N0->getOperand(0)->getOperand(0);
7605 SDNode *V = Vec.getNode();
7606 unsigned nextIndex = 0;
7608 // For each operands to the ADD which are BUILD_VECTORs,
7609 // check to see if each of their operands are an EXTRACT_VECTOR with
7610 // the same vector and appropriate index.
7611 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7612 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7613 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7615 SDValue ExtVec0 = N0->getOperand(i);
7616 SDValue ExtVec1 = N1->getOperand(i);
7618 // First operand is the vector, verify its the same.
7619 if (V != ExtVec0->getOperand(0).getNode() ||
7620 V != ExtVec1->getOperand(0).getNode())
7623 // Second is the constant, verify its correct.
7624 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7625 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7627 // For the constant, we want to see all the even or all the odd.
7628 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7629 || C1->getZExtValue() != nextIndex+1)
7638 // Create VPADDL node.
7639 SelectionDAG &DAG = DCI.DAG;
7640 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7642 // Build operand list.
7643 SmallVector<SDValue, 8> Ops;
7644 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7645 TLI.getPointerTy()));
7647 // Input is the vector.
7650 // Get widened type and narrowed type.
7652 unsigned numElem = VT.getVectorNumElements();
7654 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7655 switch (inputLaneType.getSimpleVT().SimpleTy) {
7656 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7657 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7658 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7660 llvm_unreachable("Invalid vector element type for padd optimization.");
7663 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7664 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7665 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7668 static SDValue findMUL_LOHI(SDValue V) {
7669 if (V->getOpcode() == ISD::UMUL_LOHI ||
7670 V->getOpcode() == ISD::SMUL_LOHI)
7675 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7676 TargetLowering::DAGCombinerInfo &DCI,
7677 const ARMSubtarget *Subtarget) {
7679 if (Subtarget->isThumb1Only()) return SDValue();
7681 // Only perform the checks after legalize when the pattern is available.
7682 if (DCI.isBeforeLegalize()) return SDValue();
7684 // Look for multiply add opportunities.
7685 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7686 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7687 // a glue link from the first add to the second add.
7688 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7689 // a S/UMLAL instruction.
7692 // \ / \ [no multiline comment]
7698 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7699 SDValue AddcOp0 = AddcNode->getOperand(0);
7700 SDValue AddcOp1 = AddcNode->getOperand(1);
7702 // Check if the two operands are from the same mul_lohi node.
7703 if (AddcOp0.getNode() == AddcOp1.getNode())
7706 assert(AddcNode->getNumValues() == 2 &&
7707 AddcNode->getValueType(0) == MVT::i32 &&
7708 "Expect ADDC with two result values. First: i32");
7710 // Check that we have a glued ADDC node.
7711 if (AddcNode->getValueType(1) != MVT::Glue)
7714 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7715 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7716 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7717 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7718 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7721 // Look for the glued ADDE.
7722 SDNode* AddeNode = AddcNode->getGluedUser();
7726 // Make sure it is really an ADDE.
7727 if (AddeNode->getOpcode() != ISD::ADDE)
7730 assert(AddeNode->getNumOperands() == 3 &&
7731 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7732 "ADDE node has the wrong inputs");
7734 // Check for the triangle shape.
7735 SDValue AddeOp0 = AddeNode->getOperand(0);
7736 SDValue AddeOp1 = AddeNode->getOperand(1);
7738 // Make sure that the ADDE operands are not coming from the same node.
7739 if (AddeOp0.getNode() == AddeOp1.getNode())
7742 // Find the MUL_LOHI node walking up ADDE's operands.
7743 bool IsLeftOperandMUL = false;
7744 SDValue MULOp = findMUL_LOHI(AddeOp0);
7745 if (MULOp == SDValue())
7746 MULOp = findMUL_LOHI(AddeOp1);
7748 IsLeftOperandMUL = true;
7749 if (MULOp == SDValue())
7752 // Figure out the right opcode.
7753 unsigned Opc = MULOp->getOpcode();
7754 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7756 // Figure out the high and low input values to the MLAL node.
7757 SDValue* HiMul = &MULOp;
7758 SDValue* HiAdd = nullptr;
7759 SDValue* LoMul = nullptr;
7760 SDValue* LowAdd = nullptr;
7762 if (IsLeftOperandMUL)
7768 if (AddcOp0->getOpcode() == Opc) {
7772 if (AddcOp1->getOpcode() == Opc) {
7780 if (LoMul->getNode() != HiMul->getNode())
7783 // Create the merged node.
7784 SelectionDAG &DAG = DCI.DAG;
7786 // Build operand list.
7787 SmallVector<SDValue, 8> Ops;
7788 Ops.push_back(LoMul->getOperand(0));
7789 Ops.push_back(LoMul->getOperand(1));
7790 Ops.push_back(*LowAdd);
7791 Ops.push_back(*HiAdd);
7793 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7794 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7796 // Replace the ADDs' nodes uses by the MLA node's values.
7797 SDValue HiMLALResult(MLALNode.getNode(), 1);
7798 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7800 SDValue LoMLALResult(MLALNode.getNode(), 0);
7801 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7803 // Return original node to notify the driver to stop replacing.
7804 SDValue resNode(AddcNode, 0);
7808 /// PerformADDCCombine - Target-specific dag combine transform from
7809 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7810 static SDValue PerformADDCCombine(SDNode *N,
7811 TargetLowering::DAGCombinerInfo &DCI,
7812 const ARMSubtarget *Subtarget) {
7814 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7818 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7819 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7820 /// called with the default operands, and if that fails, with commuted
7822 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7823 TargetLowering::DAGCombinerInfo &DCI,
7824 const ARMSubtarget *Subtarget){
7826 // Attempt to create vpaddl for this add.
7827 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7828 if (Result.getNode())
7831 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7832 if (N0.getNode()->hasOneUse()) {
7833 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7834 if (Result.getNode()) return Result;
7839 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7841 static SDValue PerformADDCombine(SDNode *N,
7842 TargetLowering::DAGCombinerInfo &DCI,
7843 const ARMSubtarget *Subtarget) {
7844 SDValue N0 = N->getOperand(0);
7845 SDValue N1 = N->getOperand(1);
7847 // First try with the default operand order.
7848 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7849 if (Result.getNode())
7852 // If that didn't work, try again with the operands commuted.
7853 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7856 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7858 static SDValue PerformSUBCombine(SDNode *N,
7859 TargetLowering::DAGCombinerInfo &DCI) {
7860 SDValue N0 = N->getOperand(0);
7861 SDValue N1 = N->getOperand(1);
7863 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7864 if (N1.getNode()->hasOneUse()) {
7865 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7866 if (Result.getNode()) return Result;
7872 /// PerformVMULCombine
7873 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7874 /// special multiplier accumulator forwarding.
7880 // However, for (A + B) * (A + B),
7887 static SDValue PerformVMULCombine(SDNode *N,
7888 TargetLowering::DAGCombinerInfo &DCI,
7889 const ARMSubtarget *Subtarget) {
7890 if (!Subtarget->hasVMLxForwarding())
7893 SelectionDAG &DAG = DCI.DAG;
7894 SDValue N0 = N->getOperand(0);
7895 SDValue N1 = N->getOperand(1);
7896 unsigned Opcode = N0.getOpcode();
7897 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7898 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7899 Opcode = N1.getOpcode();
7900 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7901 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7909 EVT VT = N->getValueType(0);
7911 SDValue N00 = N0->getOperand(0);
7912 SDValue N01 = N0->getOperand(1);
7913 return DAG.getNode(Opcode, DL, VT,
7914 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7915 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7918 static SDValue PerformMULCombine(SDNode *N,
7919 TargetLowering::DAGCombinerInfo &DCI,
7920 const ARMSubtarget *Subtarget) {
7921 SelectionDAG &DAG = DCI.DAG;
7923 if (Subtarget->isThumb1Only())
7926 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7929 EVT VT = N->getValueType(0);
7930 if (VT.is64BitVector() || VT.is128BitVector())
7931 return PerformVMULCombine(N, DCI, Subtarget);
7935 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7939 int64_t MulAmt = C->getSExtValue();
7940 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7942 ShiftAmt = ShiftAmt & (32 - 1);
7943 SDValue V = N->getOperand(0);
7947 MulAmt >>= ShiftAmt;
7950 if (isPowerOf2_32(MulAmt - 1)) {
7951 // (mul x, 2^N + 1) => (add (shl x, N), x)
7952 Res = DAG.getNode(ISD::ADD, DL, VT,
7954 DAG.getNode(ISD::SHL, DL, VT,
7956 DAG.getConstant(Log2_32(MulAmt - 1),
7958 } else if (isPowerOf2_32(MulAmt + 1)) {
7959 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7960 Res = DAG.getNode(ISD::SUB, DL, VT,
7961 DAG.getNode(ISD::SHL, DL, VT,
7963 DAG.getConstant(Log2_32(MulAmt + 1),
7969 uint64_t MulAmtAbs = -MulAmt;
7970 if (isPowerOf2_32(MulAmtAbs + 1)) {
7971 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7972 Res = DAG.getNode(ISD::SUB, DL, VT,
7974 DAG.getNode(ISD::SHL, DL, VT,
7976 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7978 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7979 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7980 Res = DAG.getNode(ISD::ADD, DL, VT,
7982 DAG.getNode(ISD::SHL, DL, VT,
7984 DAG.getConstant(Log2_32(MulAmtAbs-1),
7986 Res = DAG.getNode(ISD::SUB, DL, VT,
7987 DAG.getConstant(0, MVT::i32),Res);
7994 Res = DAG.getNode(ISD::SHL, DL, VT,
7995 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7997 // Do not add new nodes to DAG combiner worklist.
7998 DCI.CombineTo(N, Res, false);
8002 static SDValue PerformANDCombine(SDNode *N,
8003 TargetLowering::DAGCombinerInfo &DCI,
8004 const ARMSubtarget *Subtarget) {
8006 // Attempt to use immediate-form VBIC
8007 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8009 EVT VT = N->getValueType(0);
8010 SelectionDAG &DAG = DCI.DAG;
8012 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8015 APInt SplatBits, SplatUndef;
8016 unsigned SplatBitSize;
8019 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8020 if (SplatBitSize <= 64) {
8022 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8023 SplatUndef.getZExtValue(), SplatBitSize,
8024 DAG, VbicVT, VT.is128BitVector(),
8026 if (Val.getNode()) {
8028 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8029 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8030 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8035 if (!Subtarget->isThumb1Only()) {
8036 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8037 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8038 if (Result.getNode())
8045 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8046 static SDValue PerformORCombine(SDNode *N,
8047 TargetLowering::DAGCombinerInfo &DCI,
8048 const ARMSubtarget *Subtarget) {
8049 // Attempt to use immediate-form VORR
8050 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8052 EVT VT = N->getValueType(0);
8053 SelectionDAG &DAG = DCI.DAG;
8055 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8058 APInt SplatBits, SplatUndef;
8059 unsigned SplatBitSize;
8061 if (BVN && Subtarget->hasNEON() &&
8062 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8063 if (SplatBitSize <= 64) {
8065 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8066 SplatUndef.getZExtValue(), SplatBitSize,
8067 DAG, VorrVT, VT.is128BitVector(),
8069 if (Val.getNode()) {
8071 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8072 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8073 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8078 if (!Subtarget->isThumb1Only()) {
8079 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8080 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8081 if (Result.getNode())
8085 // The code below optimizes (or (and X, Y), Z).
8086 // The AND operand needs to have a single user to make these optimizations
8088 SDValue N0 = N->getOperand(0);
8089 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8091 SDValue N1 = N->getOperand(1);
8093 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8094 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8095 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8097 unsigned SplatBitSize;
8100 APInt SplatBits0, SplatBits1;
8101 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8102 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8103 // Ensure that the second operand of both ands are constants
8104 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8105 HasAnyUndefs) && !HasAnyUndefs) {
8106 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8107 HasAnyUndefs) && !HasAnyUndefs) {
8108 // Ensure that the bit width of the constants are the same and that
8109 // the splat arguments are logical inverses as per the pattern we
8110 // are trying to simplify.
8111 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8112 SplatBits0 == ~SplatBits1) {
8113 // Canonicalize the vector type to make instruction selection
8115 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8116 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8120 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8126 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8129 // BFI is only available on V6T2+
8130 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8134 // 1) or (and A, mask), val => ARMbfi A, val, mask
8135 // iff (val & mask) == val
8137 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8138 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8139 // && mask == ~mask2
8140 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8141 // && ~mask == mask2
8142 // (i.e., copy a bitfield value into another bitfield of the same width)
8147 SDValue N00 = N0.getOperand(0);
8149 // The value and the mask need to be constants so we can verify this is
8150 // actually a bitfield set. If the mask is 0xffff, we can do better
8151 // via a movt instruction, so don't use BFI in that case.
8152 SDValue MaskOp = N0.getOperand(1);
8153 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8156 unsigned Mask = MaskC->getZExtValue();
8160 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8161 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8163 unsigned Val = N1C->getZExtValue();
8164 if ((Val & ~Mask) != Val)
8167 if (ARM::isBitFieldInvertedMask(Mask)) {
8168 Val >>= countTrailingZeros(~Mask);
8170 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8171 DAG.getConstant(Val, MVT::i32),
8172 DAG.getConstant(Mask, MVT::i32));
8174 // Do not add new nodes to DAG combiner worklist.
8175 DCI.CombineTo(N, Res, false);
8178 } else if (N1.getOpcode() == ISD::AND) {
8179 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8180 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8183 unsigned Mask2 = N11C->getZExtValue();
8185 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8187 if (ARM::isBitFieldInvertedMask(Mask) &&
8189 // The pack halfword instruction works better for masks that fit it,
8190 // so use that when it's available.
8191 if (Subtarget->hasT2ExtractPack() &&
8192 (Mask == 0xffff || Mask == 0xffff0000))
8195 unsigned amt = countTrailingZeros(Mask2);
8196 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8197 DAG.getConstant(amt, MVT::i32));
8198 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8199 DAG.getConstant(Mask, MVT::i32));
8200 // Do not add new nodes to DAG combiner worklist.
8201 DCI.CombineTo(N, Res, false);
8203 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8205 // The pack halfword instruction works better for masks that fit it,
8206 // so use that when it's available.
8207 if (Subtarget->hasT2ExtractPack() &&
8208 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8211 unsigned lsb = countTrailingZeros(Mask);
8212 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8213 DAG.getConstant(lsb, MVT::i32));
8214 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8215 DAG.getConstant(Mask2, MVT::i32));
8216 // Do not add new nodes to DAG combiner worklist.
8217 DCI.CombineTo(N, Res, false);
8222 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8223 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8224 ARM::isBitFieldInvertedMask(~Mask)) {
8225 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8226 // where lsb(mask) == #shamt and masked bits of B are known zero.
8227 SDValue ShAmt = N00.getOperand(1);
8228 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8229 unsigned LSB = countTrailingZeros(Mask);
8233 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8234 DAG.getConstant(~Mask, MVT::i32));
8236 // Do not add new nodes to DAG combiner worklist.
8237 DCI.CombineTo(N, Res, false);
8243 static SDValue PerformXORCombine(SDNode *N,
8244 TargetLowering::DAGCombinerInfo &DCI,
8245 const ARMSubtarget *Subtarget) {
8246 EVT VT = N->getValueType(0);
8247 SelectionDAG &DAG = DCI.DAG;
8249 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8252 if (!Subtarget->isThumb1Only()) {
8253 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8254 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8255 if (Result.getNode())
8262 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8263 /// the bits being cleared by the AND are not demanded by the BFI.
8264 static SDValue PerformBFICombine(SDNode *N,
8265 TargetLowering::DAGCombinerInfo &DCI) {
8266 SDValue N1 = N->getOperand(1);
8267 if (N1.getOpcode() == ISD::AND) {
8268 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8271 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8272 unsigned LSB = countTrailingZeros(~InvMask);
8273 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8274 unsigned Mask = (1 << Width)-1;
8275 unsigned Mask2 = N11C->getZExtValue();
8276 if ((Mask & (~Mask2)) == 0)
8277 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8278 N->getOperand(0), N1.getOperand(0),
8284 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8285 /// ARMISD::VMOVRRD.
8286 static SDValue PerformVMOVRRDCombine(SDNode *N,
8287 TargetLowering::DAGCombinerInfo &DCI) {
8288 // vmovrrd(vmovdrr x, y) -> x,y
8289 SDValue InDouble = N->getOperand(0);
8290 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8291 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8293 // vmovrrd(load f64) -> (load i32), (load i32)
8294 SDNode *InNode = InDouble.getNode();
8295 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8296 InNode->getValueType(0) == MVT::f64 &&
8297 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8298 !cast<LoadSDNode>(InNode)->isVolatile()) {
8299 // TODO: Should this be done for non-FrameIndex operands?
8300 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8302 SelectionDAG &DAG = DCI.DAG;
8304 SDValue BasePtr = LD->getBasePtr();
8305 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8306 LD->getPointerInfo(), LD->isVolatile(),
8307 LD->isNonTemporal(), LD->isInvariant(),
8308 LD->getAlignment());
8310 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8311 DAG.getConstant(4, MVT::i32));
8312 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8313 LD->getPointerInfo(), LD->isVolatile(),
8314 LD->isNonTemporal(), LD->isInvariant(),
8315 std::min(4U, LD->getAlignment() / 2));
8317 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8318 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8319 std::swap (NewLD1, NewLD2);
8320 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8321 DCI.RemoveFromWorklist(LD);
8329 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8330 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8331 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8332 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8333 SDValue Op0 = N->getOperand(0);
8334 SDValue Op1 = N->getOperand(1);
8335 if (Op0.getOpcode() == ISD::BITCAST)
8336 Op0 = Op0.getOperand(0);
8337 if (Op1.getOpcode() == ISD::BITCAST)
8338 Op1 = Op1.getOperand(0);
8339 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8340 Op0.getNode() == Op1.getNode() &&
8341 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8342 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8343 N->getValueType(0), Op0.getOperand(0));
8347 /// PerformSTORECombine - Target-specific dag combine xforms for
8349 static SDValue PerformSTORECombine(SDNode *N,
8350 TargetLowering::DAGCombinerInfo &DCI) {
8351 StoreSDNode *St = cast<StoreSDNode>(N);
8352 if (St->isVolatile())
8355 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8356 // pack all of the elements in one place. Next, store to memory in fewer
8358 SDValue StVal = St->getValue();
8359 EVT VT = StVal.getValueType();
8360 if (St->isTruncatingStore() && VT.isVector()) {
8361 SelectionDAG &DAG = DCI.DAG;
8362 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8363 EVT StVT = St->getMemoryVT();
8364 unsigned NumElems = VT.getVectorNumElements();
8365 assert(StVT != VT && "Cannot truncate to the same type");
8366 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8367 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8369 // From, To sizes and ElemCount must be pow of two
8370 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8372 // We are going to use the original vector elt for storing.
8373 // Accumulated smaller vector elements must be a multiple of the store size.
8374 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8376 unsigned SizeRatio = FromEltSz / ToEltSz;
8377 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8379 // Create a type on which we perform the shuffle.
8380 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8381 NumElems*SizeRatio);
8382 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8385 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8386 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8387 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8389 // Can't shuffle using an illegal type.
8390 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8392 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8393 DAG.getUNDEF(WideVec.getValueType()),
8395 // At this point all of the data is stored at the bottom of the
8396 // register. We now need to save it to mem.
8398 // Find the largest store unit
8399 MVT StoreType = MVT::i8;
8400 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8401 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8402 MVT Tp = (MVT::SimpleValueType)tp;
8403 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8406 // Didn't find a legal store type.
8407 if (!TLI.isTypeLegal(StoreType))
8410 // Bitcast the original vector into a vector of store-size units
8411 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8412 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8413 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8414 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8415 SmallVector<SDValue, 8> Chains;
8416 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8417 TLI.getPointerTy());
8418 SDValue BasePtr = St->getBasePtr();
8420 // Perform one or more big stores into memory.
8421 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8422 for (unsigned I = 0; I < E; I++) {
8423 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8424 StoreType, ShuffWide,
8425 DAG.getIntPtrConstant(I));
8426 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8427 St->getPointerInfo(), St->isVolatile(),
8428 St->isNonTemporal(), St->getAlignment());
8429 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8431 Chains.push_back(Ch);
8433 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8436 if (!ISD::isNormalStore(St))
8439 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8440 // ARM stores of arguments in the same cache line.
8441 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8442 StVal.getNode()->hasOneUse()) {
8443 SelectionDAG &DAG = DCI.DAG;
8444 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8446 SDValue BasePtr = St->getBasePtr();
8447 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8448 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8449 BasePtr, St->getPointerInfo(), St->isVolatile(),
8450 St->isNonTemporal(), St->getAlignment());
8452 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8453 DAG.getConstant(4, MVT::i32));
8454 return DAG.getStore(NewST1.getValue(0), DL,
8455 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8456 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8457 St->isNonTemporal(),
8458 std::min(4U, St->getAlignment() / 2));
8461 if (StVal.getValueType() != MVT::i64 ||
8462 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8465 // Bitcast an i64 store extracted from a vector to f64.
8466 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8467 SelectionDAG &DAG = DCI.DAG;
8469 SDValue IntVec = StVal.getOperand(0);
8470 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8471 IntVec.getValueType().getVectorNumElements());
8472 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8473 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8474 Vec, StVal.getOperand(1));
8476 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8477 // Make the DAGCombiner fold the bitcasts.
8478 DCI.AddToWorklist(Vec.getNode());
8479 DCI.AddToWorklist(ExtElt.getNode());
8480 DCI.AddToWorklist(V.getNode());
8481 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8482 St->getPointerInfo(), St->isVolatile(),
8483 St->isNonTemporal(), St->getAlignment(),
8487 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8488 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8489 /// i64 vector to have f64 elements, since the value can then be loaded
8490 /// directly into a VFP register.
8491 static bool hasNormalLoadOperand(SDNode *N) {
8492 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8493 for (unsigned i = 0; i < NumElts; ++i) {
8494 SDNode *Elt = N->getOperand(i).getNode();
8495 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8501 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8502 /// ISD::BUILD_VECTOR.
8503 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8504 TargetLowering::DAGCombinerInfo &DCI){
8505 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8506 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8507 // into a pair of GPRs, which is fine when the value is used as a scalar,
8508 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8509 SelectionDAG &DAG = DCI.DAG;
8510 if (N->getNumOperands() == 2) {
8511 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8516 // Load i64 elements as f64 values so that type legalization does not split
8517 // them up into i32 values.
8518 EVT VT = N->getValueType(0);
8519 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8522 SmallVector<SDValue, 8> Ops;
8523 unsigned NumElts = VT.getVectorNumElements();
8524 for (unsigned i = 0; i < NumElts; ++i) {
8525 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8527 // Make the DAGCombiner fold the bitcast.
8528 DCI.AddToWorklist(V.getNode());
8530 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8531 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8532 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8535 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8537 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8538 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8539 // At that time, we may have inserted bitcasts from integer to float.
8540 // If these bitcasts have survived DAGCombine, change the lowering of this
8541 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8542 // force to use floating point types.
8544 // Make sure we can change the type of the vector.
8545 // This is possible iff:
8546 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8547 // 1.1. Vector is used only once.
8548 // 1.2. Use is a bit convert to an integer type.
8549 // 2. The size of its operands are 32-bits (64-bits are not legal).
8550 EVT VT = N->getValueType(0);
8551 EVT EltVT = VT.getVectorElementType();
8553 // Check 1.1. and 2.
8554 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8557 // By construction, the input type must be float.
8558 assert(EltVT == MVT::f32 && "Unexpected type!");
8561 SDNode *Use = *N->use_begin();
8562 if (Use->getOpcode() != ISD::BITCAST ||
8563 Use->getValueType(0).isFloatingPoint())
8566 // Check profitability.
8567 // Model is, if more than half of the relevant operands are bitcast from
8568 // i32, turn the build_vector into a sequence of insert_vector_elt.
8569 // Relevant operands are everything that is not statically
8570 // (i.e., at compile time) bitcasted.
8571 unsigned NumOfBitCastedElts = 0;
8572 unsigned NumElts = VT.getVectorNumElements();
8573 unsigned NumOfRelevantElts = NumElts;
8574 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8575 SDValue Elt = N->getOperand(Idx);
8576 if (Elt->getOpcode() == ISD::BITCAST) {
8577 // Assume only bit cast to i32 will go away.
8578 if (Elt->getOperand(0).getValueType() == MVT::i32)
8579 ++NumOfBitCastedElts;
8580 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8581 // Constants are statically casted, thus do not count them as
8582 // relevant operands.
8583 --NumOfRelevantElts;
8586 // Check if more than half of the elements require a non-free bitcast.
8587 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8590 SelectionDAG &DAG = DCI.DAG;
8591 // Create the new vector type.
8592 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8593 // Check if the type is legal.
8594 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8595 if (!TLI.isTypeLegal(VecVT))
8599 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8600 // => BITCAST INSERT_VECTOR_ELT
8601 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8603 SDValue Vec = DAG.getUNDEF(VecVT);
8605 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8606 SDValue V = N->getOperand(Idx);
8607 if (V.getOpcode() == ISD::UNDEF)
8609 if (V.getOpcode() == ISD::BITCAST &&
8610 V->getOperand(0).getValueType() == MVT::i32)
8611 // Fold obvious case.
8612 V = V.getOperand(0);
8614 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8615 // Make the DAGCombiner fold the bitcasts.
8616 DCI.AddToWorklist(V.getNode());
8618 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8619 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8621 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8622 // Make the DAGCombiner fold the bitcasts.
8623 DCI.AddToWorklist(Vec.getNode());
8627 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8628 /// ISD::INSERT_VECTOR_ELT.
8629 static SDValue PerformInsertEltCombine(SDNode *N,
8630 TargetLowering::DAGCombinerInfo &DCI) {
8631 // Bitcast an i64 load inserted into a vector to f64.
8632 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8633 EVT VT = N->getValueType(0);
8634 SDNode *Elt = N->getOperand(1).getNode();
8635 if (VT.getVectorElementType() != MVT::i64 ||
8636 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8639 SelectionDAG &DAG = DCI.DAG;
8641 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8642 VT.getVectorNumElements());
8643 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8644 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8645 // Make the DAGCombiner fold the bitcasts.
8646 DCI.AddToWorklist(Vec.getNode());
8647 DCI.AddToWorklist(V.getNode());
8648 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8649 Vec, V, N->getOperand(2));
8650 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8653 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8654 /// ISD::VECTOR_SHUFFLE.
8655 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8656 // The LLVM shufflevector instruction does not require the shuffle mask
8657 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8658 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8659 // operands do not match the mask length, they are extended by concatenating
8660 // them with undef vectors. That is probably the right thing for other
8661 // targets, but for NEON it is better to concatenate two double-register
8662 // size vector operands into a single quad-register size vector. Do that
8663 // transformation here:
8664 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8665 // shuffle(concat(v1, v2), undef)
8666 SDValue Op0 = N->getOperand(0);
8667 SDValue Op1 = N->getOperand(1);
8668 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8669 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8670 Op0.getNumOperands() != 2 ||
8671 Op1.getNumOperands() != 2)
8673 SDValue Concat0Op1 = Op0.getOperand(1);
8674 SDValue Concat1Op1 = Op1.getOperand(1);
8675 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8676 Concat1Op1.getOpcode() != ISD::UNDEF)
8678 // Skip the transformation if any of the types are illegal.
8679 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8680 EVT VT = N->getValueType(0);
8681 if (!TLI.isTypeLegal(VT) ||
8682 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8683 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8686 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8687 Op0.getOperand(0), Op1.getOperand(0));
8688 // Translate the shuffle mask.
8689 SmallVector<int, 16> NewMask;
8690 unsigned NumElts = VT.getVectorNumElements();
8691 unsigned HalfElts = NumElts/2;
8692 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8693 for (unsigned n = 0; n < NumElts; ++n) {
8694 int MaskElt = SVN->getMaskElt(n);
8696 if (MaskElt < (int)HalfElts)
8698 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8699 NewElt = HalfElts + MaskElt - NumElts;
8700 NewMask.push_back(NewElt);
8702 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8703 DAG.getUNDEF(VT), NewMask.data());
8706 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8707 /// NEON load/store intrinsics to merge base address updates.
8708 static SDValue CombineBaseUpdate(SDNode *N,
8709 TargetLowering::DAGCombinerInfo &DCI) {
8710 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8713 SelectionDAG &DAG = DCI.DAG;
8714 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8715 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8716 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8717 SDValue Addr = N->getOperand(AddrOpIdx);
8719 // Search for a use of the address operand that is an increment.
8720 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8721 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8723 if (User->getOpcode() != ISD::ADD ||
8724 UI.getUse().getResNo() != Addr.getResNo())
8727 // Check that the add is independent of the load/store. Otherwise, folding
8728 // it would create a cycle.
8729 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8732 // Find the new opcode for the updating load/store.
8734 bool isLaneOp = false;
8735 unsigned NewOpc = 0;
8736 unsigned NumVecs = 0;
8738 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8740 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8741 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8743 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8745 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8747 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8749 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8750 NumVecs = 2; isLaneOp = true; break;
8751 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8752 NumVecs = 3; isLaneOp = true; break;
8753 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8754 NumVecs = 4; isLaneOp = true; break;
8755 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8756 NumVecs = 1; isLoad = false; break;
8757 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8758 NumVecs = 2; isLoad = false; break;
8759 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8760 NumVecs = 3; isLoad = false; break;
8761 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8762 NumVecs = 4; isLoad = false; break;
8763 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8764 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8765 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8766 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8767 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8768 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8772 switch (N->getOpcode()) {
8773 default: llvm_unreachable("unexpected opcode for Neon base update");
8774 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8775 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8776 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8780 // Find the size of memory referenced by the load/store.
8783 VecTy = N->getValueType(0);
8785 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8786 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8788 NumBytes /= VecTy.getVectorNumElements();
8790 // If the increment is a constant, it must match the memory ref size.
8791 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8792 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8793 uint64_t IncVal = CInc->getZExtValue();
8794 if (IncVal != NumBytes)
8796 } else if (NumBytes >= 3 * 16) {
8797 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8798 // separate instructions that make it harder to use a non-constant update.
8802 // Create the new updating load/store node.
8804 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8806 for (n = 0; n < NumResultVecs; ++n)
8808 Tys[n++] = MVT::i32;
8809 Tys[n] = MVT::Other;
8810 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8811 SmallVector<SDValue, 8> Ops;
8812 Ops.push_back(N->getOperand(0)); // incoming chain
8813 Ops.push_back(N->getOperand(AddrOpIdx));
8815 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8816 Ops.push_back(N->getOperand(i));
8818 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8819 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8820 Ops, MemInt->getMemoryVT(),
8821 MemInt->getMemOperand());
8824 std::vector<SDValue> NewResults;
8825 for (unsigned i = 0; i < NumResultVecs; ++i) {
8826 NewResults.push_back(SDValue(UpdN.getNode(), i));
8828 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8829 DCI.CombineTo(N, NewResults);
8830 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8837 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8838 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8839 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8841 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8842 SelectionDAG &DAG = DCI.DAG;
8843 EVT VT = N->getValueType(0);
8844 // vldN-dup instructions only support 64-bit vectors for N > 1.
8845 if (!VT.is64BitVector())
8848 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8849 SDNode *VLD = N->getOperand(0).getNode();
8850 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8852 unsigned NumVecs = 0;
8853 unsigned NewOpc = 0;
8854 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8855 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8857 NewOpc = ARMISD::VLD2DUP;
8858 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8860 NewOpc = ARMISD::VLD3DUP;
8861 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8863 NewOpc = ARMISD::VLD4DUP;
8868 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8869 // numbers match the load.
8870 unsigned VLDLaneNo =
8871 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8872 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8874 // Ignore uses of the chain result.
8875 if (UI.getUse().getResNo() == NumVecs)
8878 if (User->getOpcode() != ARMISD::VDUPLANE ||
8879 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8883 // Create the vldN-dup node.
8886 for (n = 0; n < NumVecs; ++n)
8888 Tys[n] = MVT::Other;
8889 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8890 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8891 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8892 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8893 Ops, VLDMemInt->getMemoryVT(),
8894 VLDMemInt->getMemOperand());
8897 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8899 unsigned ResNo = UI.getUse().getResNo();
8900 // Ignore uses of the chain result.
8901 if (ResNo == NumVecs)
8904 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8907 // Now the vldN-lane intrinsic is dead except for its chain result.
8908 // Update uses of the chain.
8909 std::vector<SDValue> VLDDupResults;
8910 for (unsigned n = 0; n < NumVecs; ++n)
8911 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8912 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8913 DCI.CombineTo(VLD, VLDDupResults);
8918 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8919 /// ARMISD::VDUPLANE.
8920 static SDValue PerformVDUPLANECombine(SDNode *N,
8921 TargetLowering::DAGCombinerInfo &DCI) {
8922 SDValue Op = N->getOperand(0);
8924 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8925 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8926 if (CombineVLDDUP(N, DCI))
8927 return SDValue(N, 0);
8929 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8930 // redundant. Ignore bit_converts for now; element sizes are checked below.
8931 while (Op.getOpcode() == ISD::BITCAST)
8932 Op = Op.getOperand(0);
8933 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8936 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8937 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8938 // The canonical VMOV for a zero vector uses a 32-bit element size.
8939 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8941 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8943 EVT VT = N->getValueType(0);
8944 if (EltSize > VT.getVectorElementType().getSizeInBits())
8947 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8950 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8951 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8952 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8956 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8958 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8963 APFloat APF = C->getValueAPF();
8964 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8965 != APFloat::opOK || !isExact)
8968 c0 = (I == 0) ? cN : c0;
8969 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8976 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8977 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8978 /// when the VMUL has a constant operand that is a power of 2.
8980 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8981 /// vmul.f32 d16, d17, d16
8982 /// vcvt.s32.f32 d16, d16
8984 /// vcvt.s32.f32 d16, d16, #3
8985 static SDValue PerformVCVTCombine(SDNode *N,
8986 TargetLowering::DAGCombinerInfo &DCI,
8987 const ARMSubtarget *Subtarget) {
8988 SelectionDAG &DAG = DCI.DAG;
8989 SDValue Op = N->getOperand(0);
8991 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8992 Op.getOpcode() != ISD::FMUL)
8996 SDValue N0 = Op->getOperand(0);
8997 SDValue ConstVec = Op->getOperand(1);
8998 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9000 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9001 !isConstVecPow2(ConstVec, isSigned, C))
9004 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9005 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9006 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9007 // These instructions only exist converting from f32 to i32. We can handle
9008 // smaller integers by generating an extra truncate, but larger ones would
9013 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9014 Intrinsic::arm_neon_vcvtfp2fxu;
9015 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9016 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9017 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9018 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9019 DAG.getConstant(Log2_64(C), MVT::i32));
9021 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9022 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9027 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9028 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9029 /// when the VDIV has a constant operand that is a power of 2.
9031 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9032 /// vcvt.f32.s32 d16, d16
9033 /// vdiv.f32 d16, d17, d16
9035 /// vcvt.f32.s32 d16, d16, #3
9036 static SDValue PerformVDIVCombine(SDNode *N,
9037 TargetLowering::DAGCombinerInfo &DCI,
9038 const ARMSubtarget *Subtarget) {
9039 SelectionDAG &DAG = DCI.DAG;
9040 SDValue Op = N->getOperand(0);
9041 unsigned OpOpcode = Op.getNode()->getOpcode();
9043 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9044 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9048 SDValue ConstVec = N->getOperand(1);
9049 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9051 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9052 !isConstVecPow2(ConstVec, isSigned, C))
9055 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9056 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9057 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9058 // These instructions only exist converting from i32 to f32. We can handle
9059 // smaller integers by generating an extra extend, but larger ones would
9064 SDValue ConvInput = Op.getOperand(0);
9065 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9066 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9067 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9068 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9071 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9072 Intrinsic::arm_neon_vcvtfxu2fp;
9073 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9075 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9076 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9079 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9080 /// operand of a vector shift operation, where all the elements of the
9081 /// build_vector must have the same constant integer value.
9082 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9083 // Ignore bit_converts.
9084 while (Op.getOpcode() == ISD::BITCAST)
9085 Op = Op.getOperand(0);
9086 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9087 APInt SplatBits, SplatUndef;
9088 unsigned SplatBitSize;
9090 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9091 HasAnyUndefs, ElementBits) ||
9092 SplatBitSize > ElementBits)
9094 Cnt = SplatBits.getSExtValue();
9098 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9099 /// operand of a vector shift left operation. That value must be in the range:
9100 /// 0 <= Value < ElementBits for a left shift; or
9101 /// 0 <= Value <= ElementBits for a long left shift.
9102 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9103 assert(VT.isVector() && "vector shift count is not a vector type");
9104 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9105 if (! getVShiftImm(Op, ElementBits, Cnt))
9107 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9110 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9111 /// operand of a vector shift right operation. For a shift opcode, the value
9112 /// is positive, but for an intrinsic the value count must be negative. The
9113 /// absolute value must be in the range:
9114 /// 1 <= |Value| <= ElementBits for a right shift; or
9115 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9116 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9118 assert(VT.isVector() && "vector shift count is not a vector type");
9119 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9120 if (! getVShiftImm(Op, ElementBits, Cnt))
9124 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9127 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9128 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9129 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9132 // Don't do anything for most intrinsics.
9135 // Vector shifts: check for immediate versions and lower them.
9136 // Note: This is done during DAG combining instead of DAG legalizing because
9137 // the build_vectors for 64-bit vector element shift counts are generally
9138 // not legal, and it is hard to see their values after they get legalized to
9139 // loads from a constant pool.
9140 case Intrinsic::arm_neon_vshifts:
9141 case Intrinsic::arm_neon_vshiftu:
9142 case Intrinsic::arm_neon_vrshifts:
9143 case Intrinsic::arm_neon_vrshiftu:
9144 case Intrinsic::arm_neon_vrshiftn:
9145 case Intrinsic::arm_neon_vqshifts:
9146 case Intrinsic::arm_neon_vqshiftu:
9147 case Intrinsic::arm_neon_vqshiftsu:
9148 case Intrinsic::arm_neon_vqshiftns:
9149 case Intrinsic::arm_neon_vqshiftnu:
9150 case Intrinsic::arm_neon_vqshiftnsu:
9151 case Intrinsic::arm_neon_vqrshiftns:
9152 case Intrinsic::arm_neon_vqrshiftnu:
9153 case Intrinsic::arm_neon_vqrshiftnsu: {
9154 EVT VT = N->getOperand(1).getValueType();
9156 unsigned VShiftOpc = 0;
9159 case Intrinsic::arm_neon_vshifts:
9160 case Intrinsic::arm_neon_vshiftu:
9161 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9162 VShiftOpc = ARMISD::VSHL;
9165 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9166 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9167 ARMISD::VSHRs : ARMISD::VSHRu);
9172 case Intrinsic::arm_neon_vrshifts:
9173 case Intrinsic::arm_neon_vrshiftu:
9174 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9178 case Intrinsic::arm_neon_vqshifts:
9179 case Intrinsic::arm_neon_vqshiftu:
9180 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9184 case Intrinsic::arm_neon_vqshiftsu:
9185 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9187 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9189 case Intrinsic::arm_neon_vrshiftn:
9190 case Intrinsic::arm_neon_vqshiftns:
9191 case Intrinsic::arm_neon_vqshiftnu:
9192 case Intrinsic::arm_neon_vqshiftnsu:
9193 case Intrinsic::arm_neon_vqrshiftns:
9194 case Intrinsic::arm_neon_vqrshiftnu:
9195 case Intrinsic::arm_neon_vqrshiftnsu:
9196 // Narrowing shifts require an immediate right shift.
9197 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9199 llvm_unreachable("invalid shift count for narrowing vector shift "
9203 llvm_unreachable("unhandled vector shift");
9207 case Intrinsic::arm_neon_vshifts:
9208 case Intrinsic::arm_neon_vshiftu:
9209 // Opcode already set above.
9211 case Intrinsic::arm_neon_vrshifts:
9212 VShiftOpc = ARMISD::VRSHRs; break;
9213 case Intrinsic::arm_neon_vrshiftu:
9214 VShiftOpc = ARMISD::VRSHRu; break;
9215 case Intrinsic::arm_neon_vrshiftn:
9216 VShiftOpc = ARMISD::VRSHRN; break;
9217 case Intrinsic::arm_neon_vqshifts:
9218 VShiftOpc = ARMISD::VQSHLs; break;
9219 case Intrinsic::arm_neon_vqshiftu:
9220 VShiftOpc = ARMISD::VQSHLu; break;
9221 case Intrinsic::arm_neon_vqshiftsu:
9222 VShiftOpc = ARMISD::VQSHLsu; break;
9223 case Intrinsic::arm_neon_vqshiftns:
9224 VShiftOpc = ARMISD::VQSHRNs; break;
9225 case Intrinsic::arm_neon_vqshiftnu:
9226 VShiftOpc = ARMISD::VQSHRNu; break;
9227 case Intrinsic::arm_neon_vqshiftnsu:
9228 VShiftOpc = ARMISD::VQSHRNsu; break;
9229 case Intrinsic::arm_neon_vqrshiftns:
9230 VShiftOpc = ARMISD::VQRSHRNs; break;
9231 case Intrinsic::arm_neon_vqrshiftnu:
9232 VShiftOpc = ARMISD::VQRSHRNu; break;
9233 case Intrinsic::arm_neon_vqrshiftnsu:
9234 VShiftOpc = ARMISD::VQRSHRNsu; break;
9237 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9238 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9241 case Intrinsic::arm_neon_vshiftins: {
9242 EVT VT = N->getOperand(1).getValueType();
9244 unsigned VShiftOpc = 0;
9246 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9247 VShiftOpc = ARMISD::VSLI;
9248 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9249 VShiftOpc = ARMISD::VSRI;
9251 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9254 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9255 N->getOperand(1), N->getOperand(2),
9256 DAG.getConstant(Cnt, MVT::i32));
9259 case Intrinsic::arm_neon_vqrshifts:
9260 case Intrinsic::arm_neon_vqrshiftu:
9261 // No immediate versions of these to check for.
9268 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9269 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9270 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9271 /// vector element shift counts are generally not legal, and it is hard to see
9272 /// their values after they get legalized to loads from a constant pool.
9273 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9274 const ARMSubtarget *ST) {
9275 EVT VT = N->getValueType(0);
9276 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9277 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9278 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9279 SDValue N1 = N->getOperand(1);
9280 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9281 SDValue N0 = N->getOperand(0);
9282 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9283 DAG.MaskedValueIsZero(N0.getOperand(0),
9284 APInt::getHighBitsSet(32, 16)))
9285 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9289 // Nothing to be done for scalar shifts.
9290 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9291 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9294 assert(ST->hasNEON() && "unexpected vector shift");
9297 switch (N->getOpcode()) {
9298 default: llvm_unreachable("unexpected shift opcode");
9301 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9302 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9303 DAG.getConstant(Cnt, MVT::i32));
9308 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9309 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9310 ARMISD::VSHRs : ARMISD::VSHRu);
9311 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9312 DAG.getConstant(Cnt, MVT::i32));
9318 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9319 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9320 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9321 const ARMSubtarget *ST) {
9322 SDValue N0 = N->getOperand(0);
9324 // Check for sign- and zero-extensions of vector extract operations of 8-
9325 // and 16-bit vector elements. NEON supports these directly. They are
9326 // handled during DAG combining because type legalization will promote them
9327 // to 32-bit types and it is messy to recognize the operations after that.
9328 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9329 SDValue Vec = N0.getOperand(0);
9330 SDValue Lane = N0.getOperand(1);
9331 EVT VT = N->getValueType(0);
9332 EVT EltVT = N0.getValueType();
9333 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9335 if (VT == MVT::i32 &&
9336 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9337 TLI.isTypeLegal(Vec.getValueType()) &&
9338 isa<ConstantSDNode>(Lane)) {
9341 switch (N->getOpcode()) {
9342 default: llvm_unreachable("unexpected opcode");
9343 case ISD::SIGN_EXTEND:
9344 Opc = ARMISD::VGETLANEs;
9346 case ISD::ZERO_EXTEND:
9347 case ISD::ANY_EXTEND:
9348 Opc = ARMISD::VGETLANEu;
9351 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9358 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9359 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9360 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9361 const ARMSubtarget *ST) {
9362 // If the target supports NEON, try to use vmax/vmin instructions for f32
9363 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9364 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9365 // a NaN; only do the transformation when it matches that behavior.
9367 // For now only do this when using NEON for FP operations; if using VFP, it
9368 // is not obvious that the benefit outweighs the cost of switching to the
9370 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9371 N->getValueType(0) != MVT::f32)
9374 SDValue CondLHS = N->getOperand(0);
9375 SDValue CondRHS = N->getOperand(1);
9376 SDValue LHS = N->getOperand(2);
9377 SDValue RHS = N->getOperand(3);
9378 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9380 unsigned Opcode = 0;
9382 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9383 IsReversed = false; // x CC y ? x : y
9384 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9385 IsReversed = true ; // x CC y ? y : x
9399 // If LHS is NaN, an ordered comparison will be false and the result will
9400 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9401 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9402 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9403 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9405 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9406 // will return -0, so vmin can only be used for unsafe math or if one of
9407 // the operands is known to be nonzero.
9408 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9409 !DAG.getTarget().Options.UnsafeFPMath &&
9410 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9412 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9421 // If LHS is NaN, an ordered comparison will be false and the result will
9422 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9423 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9424 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9425 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9427 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9428 // will return +0, so vmax can only be used for unsafe math or if one of
9429 // the operands is known to be nonzero.
9430 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9431 !DAG.getTarget().Options.UnsafeFPMath &&
9432 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9434 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9440 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9443 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9445 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9446 SDValue Cmp = N->getOperand(4);
9447 if (Cmp.getOpcode() != ARMISD::CMPZ)
9448 // Only looking at EQ and NE cases.
9451 EVT VT = N->getValueType(0);
9453 SDValue LHS = Cmp.getOperand(0);
9454 SDValue RHS = Cmp.getOperand(1);
9455 SDValue FalseVal = N->getOperand(0);
9456 SDValue TrueVal = N->getOperand(1);
9457 SDValue ARMcc = N->getOperand(2);
9458 ARMCC::CondCodes CC =
9459 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9477 /// FIXME: Turn this into a target neutral optimization?
9479 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9480 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9481 N->getOperand(3), Cmp);
9482 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9484 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9485 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9486 N->getOperand(3), NewCmp);
9489 if (Res.getNode()) {
9490 APInt KnownZero, KnownOne;
9491 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9492 // Capture demanded bits information that would be otherwise lost.
9493 if (KnownZero == 0xfffffffe)
9494 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9495 DAG.getValueType(MVT::i1));
9496 else if (KnownZero == 0xffffff00)
9497 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9498 DAG.getValueType(MVT::i8));
9499 else if (KnownZero == 0xffff0000)
9500 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9501 DAG.getValueType(MVT::i16));
9507 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9508 DAGCombinerInfo &DCI) const {
9509 switch (N->getOpcode()) {
9511 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9512 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9513 case ISD::SUB: return PerformSUBCombine(N, DCI);
9514 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9515 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9516 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9517 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9518 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9519 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9520 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9521 case ISD::STORE: return PerformSTORECombine(N, DCI);
9522 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9523 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9524 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9525 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9526 case ISD::FP_TO_SINT:
9527 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9528 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9529 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9532 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9533 case ISD::SIGN_EXTEND:
9534 case ISD::ZERO_EXTEND:
9535 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9536 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9537 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9538 case ARMISD::VLD2DUP:
9539 case ARMISD::VLD3DUP:
9540 case ARMISD::VLD4DUP:
9541 return CombineBaseUpdate(N, DCI);
9542 case ARMISD::BUILD_VECTOR:
9543 return PerformARMBUILD_VECTORCombine(N, DCI);
9544 case ISD::INTRINSIC_VOID:
9545 case ISD::INTRINSIC_W_CHAIN:
9546 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9547 case Intrinsic::arm_neon_vld1:
9548 case Intrinsic::arm_neon_vld2:
9549 case Intrinsic::arm_neon_vld3:
9550 case Intrinsic::arm_neon_vld4:
9551 case Intrinsic::arm_neon_vld2lane:
9552 case Intrinsic::arm_neon_vld3lane:
9553 case Intrinsic::arm_neon_vld4lane:
9554 case Intrinsic::arm_neon_vst1:
9555 case Intrinsic::arm_neon_vst2:
9556 case Intrinsic::arm_neon_vst3:
9557 case Intrinsic::arm_neon_vst4:
9558 case Intrinsic::arm_neon_vst2lane:
9559 case Intrinsic::arm_neon_vst3lane:
9560 case Intrinsic::arm_neon_vst4lane:
9561 return CombineBaseUpdate(N, DCI);
9569 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9571 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9574 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9576 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9577 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9579 switch (VT.getSimpleVT().SimpleTy) {
9585 // Unaligned access can use (for example) LRDB, LRDH, LDR
9586 if (AllowsUnaligned) {
9588 *Fast = Subtarget->hasV7Ops();
9595 // For any little-endian targets with neon, we can support unaligned ld/st
9596 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9597 // A big-endian target may also explicitly support unaligned accesses
9598 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9608 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9609 unsigned AlignCheck) {
9610 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9611 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9614 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9615 unsigned DstAlign, unsigned SrcAlign,
9616 bool IsMemset, bool ZeroMemset,
9618 MachineFunction &MF) const {
9619 const Function *F = MF.getFunction();
9621 // See if we can use NEON instructions for this...
9622 if ((!IsMemset || ZeroMemset) &&
9623 Subtarget->hasNEON() &&
9624 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9625 Attribute::NoImplicitFloat)) {
9628 (memOpAlign(SrcAlign, DstAlign, 16) ||
9629 (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9631 } else if (Size >= 8 &&
9632 (memOpAlign(SrcAlign, DstAlign, 8) ||
9633 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9638 // Lowering to i32/i16 if the size permits.
9644 // Let the target-independent logic figure it out.
9648 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9649 if (Val.getOpcode() != ISD::LOAD)
9652 EVT VT1 = Val.getValueType();
9653 if (!VT1.isSimple() || !VT1.isInteger() ||
9654 !VT2.isSimple() || !VT2.isInteger())
9657 switch (VT1.getSimpleVT().SimpleTy) {
9662 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9669 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9670 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9673 if (!isTypeLegal(EVT::getEVT(Ty1)))
9676 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9678 // Assuming the caller doesn't have a zeroext or signext return parameter,
9679 // truncation all the way down to i1 is valid.
9684 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9689 switch (VT.getSimpleVT().SimpleTy) {
9690 default: return false;
9705 if ((V & (Scale - 1)) != 0)
9708 return V == (V & ((1LL << 5) - 1));
9711 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9712 const ARMSubtarget *Subtarget) {
9719 switch (VT.getSimpleVT().SimpleTy) {
9720 default: return false;
9725 // + imm12 or - imm8
9727 return V == (V & ((1LL << 8) - 1));
9728 return V == (V & ((1LL << 12) - 1));
9731 // Same as ARM mode. FIXME: NEON?
9732 if (!Subtarget->hasVFP2())
9737 return V == (V & ((1LL << 8) - 1));
9741 /// isLegalAddressImmediate - Return true if the integer value can be used
9742 /// as the offset of the target addressing mode for load / store of the
9744 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9745 const ARMSubtarget *Subtarget) {
9752 if (Subtarget->isThumb1Only())
9753 return isLegalT1AddressImmediate(V, VT);
9754 else if (Subtarget->isThumb2())
9755 return isLegalT2AddressImmediate(V, VT, Subtarget);
9760 switch (VT.getSimpleVT().SimpleTy) {
9761 default: return false;
9766 return V == (V & ((1LL << 12) - 1));
9769 return V == (V & ((1LL << 8) - 1));
9772 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9777 return V == (V & ((1LL << 8) - 1));
9781 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9783 int Scale = AM.Scale;
9787 switch (VT.getSimpleVT().SimpleTy) {
9788 default: return false;
9797 return Scale == 2 || Scale == 4 || Scale == 8;
9800 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9804 // Note, we allow "void" uses (basically, uses that aren't loads or
9805 // stores), because arm allows folding a scale into many arithmetic
9806 // operations. This should be made more precise and revisited later.
9808 // Allow r << imm, but the imm has to be a multiple of two.
9809 if (Scale & 1) return false;
9810 return isPowerOf2_32(Scale);
9814 /// isLegalAddressingMode - Return true if the addressing mode represented
9815 /// by AM is legal for this target, for a load/store of the specified type.
9816 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9818 EVT VT = getValueType(Ty, true);
9819 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9822 // Can never fold addr of global into load/store.
9827 case 0: // no scale reg, must be "r+i" or "r", or "i".
9830 if (Subtarget->isThumb1Only())
9834 // ARM doesn't support any R+R*scale+imm addr modes.
9841 if (Subtarget->isThumb2())
9842 return isLegalT2ScaledAddressingMode(AM, VT);
9844 int Scale = AM.Scale;
9845 switch (VT.getSimpleVT().SimpleTy) {
9846 default: return false;
9850 if (Scale < 0) Scale = -Scale;
9854 return isPowerOf2_32(Scale & ~1);
9858 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9863 // Note, we allow "void" uses (basically, uses that aren't loads or
9864 // stores), because arm allows folding a scale into many arithmetic
9865 // operations. This should be made more precise and revisited later.
9867 // Allow r << imm, but the imm has to be a multiple of two.
9868 if (Scale & 1) return false;
9869 return isPowerOf2_32(Scale);
9875 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9876 /// icmp immediate, that is the target has icmp instructions which can compare
9877 /// a register against the immediate without having to materialize the
9878 /// immediate into a register.
9879 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9880 // Thumb2 and ARM modes can use cmn for negative immediates.
9881 if (!Subtarget->isThumb())
9882 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9883 if (Subtarget->isThumb2())
9884 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9885 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9886 return Imm >= 0 && Imm <= 255;
9889 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9890 /// *or sub* immediate, that is the target has add or sub instructions which can
9891 /// add a register with the immediate without having to materialize the
9892 /// immediate into a register.
9893 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9894 // Same encoding for add/sub, just flip the sign.
9895 int64_t AbsImm = llvm::abs64(Imm);
9896 if (!Subtarget->isThumb())
9897 return ARM_AM::getSOImmVal(AbsImm) != -1;
9898 if (Subtarget->isThumb2())
9899 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9900 // Thumb1 only has 8-bit unsigned immediate.
9901 return AbsImm >= 0 && AbsImm <= 255;
9904 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9905 bool isSEXTLoad, SDValue &Base,
9906 SDValue &Offset, bool &isInc,
9907 SelectionDAG &DAG) {
9908 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9911 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9913 Base = Ptr->getOperand(0);
9914 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9915 int RHSC = (int)RHS->getZExtValue();
9916 if (RHSC < 0 && RHSC > -256) {
9917 assert(Ptr->getOpcode() == ISD::ADD);
9919 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9923 isInc = (Ptr->getOpcode() == ISD::ADD);
9924 Offset = Ptr->getOperand(1);
9926 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9928 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9929 int RHSC = (int)RHS->getZExtValue();
9930 if (RHSC < 0 && RHSC > -0x1000) {
9931 assert(Ptr->getOpcode() == ISD::ADD);
9933 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9934 Base = Ptr->getOperand(0);
9939 if (Ptr->getOpcode() == ISD::ADD) {
9941 ARM_AM::ShiftOpc ShOpcVal=
9942 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9943 if (ShOpcVal != ARM_AM::no_shift) {
9944 Base = Ptr->getOperand(1);
9945 Offset = Ptr->getOperand(0);
9947 Base = Ptr->getOperand(0);
9948 Offset = Ptr->getOperand(1);
9953 isInc = (Ptr->getOpcode() == ISD::ADD);
9954 Base = Ptr->getOperand(0);
9955 Offset = Ptr->getOperand(1);
9959 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9963 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9964 bool isSEXTLoad, SDValue &Base,
9965 SDValue &Offset, bool &isInc,
9966 SelectionDAG &DAG) {
9967 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9970 Base = Ptr->getOperand(0);
9971 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9972 int RHSC = (int)RHS->getZExtValue();
9973 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9974 assert(Ptr->getOpcode() == ISD::ADD);
9976 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9978 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9979 isInc = Ptr->getOpcode() == ISD::ADD;
9980 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9988 /// getPreIndexedAddressParts - returns true by value, base pointer and
9989 /// offset pointer and addressing mode by reference if the node's address
9990 /// can be legally represented as pre-indexed load / store address.
9992 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9994 ISD::MemIndexedMode &AM,
9995 SelectionDAG &DAG) const {
9996 if (Subtarget->isThumb1Only())
10001 bool isSEXTLoad = false;
10002 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10003 Ptr = LD->getBasePtr();
10004 VT = LD->getMemoryVT();
10005 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10006 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10007 Ptr = ST->getBasePtr();
10008 VT = ST->getMemoryVT();
10013 bool isLegal = false;
10014 if (Subtarget->isThumb2())
10015 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10016 Offset, isInc, DAG);
10018 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10019 Offset, isInc, DAG);
10023 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10027 /// getPostIndexedAddressParts - returns true by value, base pointer and
10028 /// offset pointer and addressing mode by reference if this node can be
10029 /// combined with a load / store to form a post-indexed load / store.
10030 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10033 ISD::MemIndexedMode &AM,
10034 SelectionDAG &DAG) const {
10035 if (Subtarget->isThumb1Only())
10040 bool isSEXTLoad = false;
10041 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10042 VT = LD->getMemoryVT();
10043 Ptr = LD->getBasePtr();
10044 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10045 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10046 VT = ST->getMemoryVT();
10047 Ptr = ST->getBasePtr();
10052 bool isLegal = false;
10053 if (Subtarget->isThumb2())
10054 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10057 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10063 // Swap base ptr and offset to catch more post-index load / store when
10064 // it's legal. In Thumb2 mode, offset must be an immediate.
10065 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10066 !Subtarget->isThumb2())
10067 std::swap(Base, Offset);
10069 // Post-indexed load / store update the base pointer.
10074 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10078 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10081 const SelectionDAG &DAG,
10082 unsigned Depth) const {
10083 unsigned BitWidth = KnownOne.getBitWidth();
10084 KnownZero = KnownOne = APInt(BitWidth, 0);
10085 switch (Op.getOpcode()) {
10091 // These nodes' second result is a boolean
10092 if (Op.getResNo() == 0)
10094 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10096 case ARMISD::CMOV: {
10097 // Bits are known zero/one if known on the LHS and RHS.
10098 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10099 if (KnownZero == 0 && KnownOne == 0) return;
10101 APInt KnownZeroRHS, KnownOneRHS;
10102 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10103 KnownZero &= KnownZeroRHS;
10104 KnownOne &= KnownOneRHS;
10107 case ISD::INTRINSIC_W_CHAIN: {
10108 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10109 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10112 case Intrinsic::arm_ldaex:
10113 case Intrinsic::arm_ldrex: {
10114 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10115 unsigned MemBits = VT.getScalarType().getSizeInBits();
10116 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10124 //===----------------------------------------------------------------------===//
10125 // ARM Inline Assembly Support
10126 //===----------------------------------------------------------------------===//
10128 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10129 // Looking for "rev" which is V6+.
10130 if (!Subtarget->hasV6Ops())
10133 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10134 std::string AsmStr = IA->getAsmString();
10135 SmallVector<StringRef, 4> AsmPieces;
10136 SplitString(AsmStr, AsmPieces, ";\n");
10138 switch (AsmPieces.size()) {
10139 default: return false;
10141 AsmStr = AsmPieces[0];
10143 SplitString(AsmStr, AsmPieces, " \t,");
10146 if (AsmPieces.size() == 3 &&
10147 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10148 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10149 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10150 if (Ty && Ty->getBitWidth() == 32)
10151 return IntrinsicLowering::LowerToByteSwap(CI);
10159 /// getConstraintType - Given a constraint letter, return the type of
10160 /// constraint it is for this target.
10161 ARMTargetLowering::ConstraintType
10162 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10163 if (Constraint.size() == 1) {
10164 switch (Constraint[0]) {
10166 case 'l': return C_RegisterClass;
10167 case 'w': return C_RegisterClass;
10168 case 'h': return C_RegisterClass;
10169 case 'x': return C_RegisterClass;
10170 case 't': return C_RegisterClass;
10171 case 'j': return C_Other; // Constant for movw.
10172 // An address with a single base register. Due to the way we
10173 // currently handle addresses it is the same as an 'r' memory constraint.
10174 case 'Q': return C_Memory;
10176 } else if (Constraint.size() == 2) {
10177 switch (Constraint[0]) {
10179 // All 'U+' constraints are addresses.
10180 case 'U': return C_Memory;
10183 return TargetLowering::getConstraintType(Constraint);
10186 /// Examine constraint type and operand type and determine a weight value.
10187 /// This object must already have been set up with the operand type
10188 /// and the current alternative constraint selected.
10189 TargetLowering::ConstraintWeight
10190 ARMTargetLowering::getSingleConstraintMatchWeight(
10191 AsmOperandInfo &info, const char *constraint) const {
10192 ConstraintWeight weight = CW_Invalid;
10193 Value *CallOperandVal = info.CallOperandVal;
10194 // If we don't have a value, we can't do a match,
10195 // but allow it at the lowest weight.
10196 if (!CallOperandVal)
10198 Type *type = CallOperandVal->getType();
10199 // Look at the constraint type.
10200 switch (*constraint) {
10202 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10205 if (type->isIntegerTy()) {
10206 if (Subtarget->isThumb())
10207 weight = CW_SpecificReg;
10209 weight = CW_Register;
10213 if (type->isFloatingPointTy())
10214 weight = CW_Register;
10220 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10222 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10224 if (Constraint.size() == 1) {
10225 // GCC ARM Constraint Letters
10226 switch (Constraint[0]) {
10227 case 'l': // Low regs or general regs.
10228 if (Subtarget->isThumb())
10229 return RCPair(0U, &ARM::tGPRRegClass);
10230 return RCPair(0U, &ARM::GPRRegClass);
10231 case 'h': // High regs or no regs.
10232 if (Subtarget->isThumb())
10233 return RCPair(0U, &ARM::hGPRRegClass);
10236 return RCPair(0U, &ARM::GPRRegClass);
10238 if (VT == MVT::Other)
10240 if (VT == MVT::f32)
10241 return RCPair(0U, &ARM::SPRRegClass);
10242 if (VT.getSizeInBits() == 64)
10243 return RCPair(0U, &ARM::DPRRegClass);
10244 if (VT.getSizeInBits() == 128)
10245 return RCPair(0U, &ARM::QPRRegClass);
10248 if (VT == MVT::Other)
10250 if (VT == MVT::f32)
10251 return RCPair(0U, &ARM::SPR_8RegClass);
10252 if (VT.getSizeInBits() == 64)
10253 return RCPair(0U, &ARM::DPR_8RegClass);
10254 if (VT.getSizeInBits() == 128)
10255 return RCPair(0U, &ARM::QPR_8RegClass);
10258 if (VT == MVT::f32)
10259 return RCPair(0U, &ARM::SPRRegClass);
10263 if (StringRef("{cc}").equals_lower(Constraint))
10264 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10266 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10269 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10270 /// vector. If it is invalid, don't add anything to Ops.
10271 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10272 std::string &Constraint,
10273 std::vector<SDValue>&Ops,
10274 SelectionDAG &DAG) const {
10277 // Currently only support length 1 constraints.
10278 if (Constraint.length() != 1) return;
10280 char ConstraintLetter = Constraint[0];
10281 switch (ConstraintLetter) {
10284 case 'I': case 'J': case 'K': case 'L':
10285 case 'M': case 'N': case 'O':
10286 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10290 int64_t CVal64 = C->getSExtValue();
10291 int CVal = (int) CVal64;
10292 // None of these constraints allow values larger than 32 bits. Check
10293 // that the value fits in an int.
10294 if (CVal != CVal64)
10297 switch (ConstraintLetter) {
10299 // Constant suitable for movw, must be between 0 and
10301 if (Subtarget->hasV6T2Ops())
10302 if (CVal >= 0 && CVal <= 65535)
10306 if (Subtarget->isThumb1Only()) {
10307 // This must be a constant between 0 and 255, for ADD
10309 if (CVal >= 0 && CVal <= 255)
10311 } else if (Subtarget->isThumb2()) {
10312 // A constant that can be used as an immediate value in a
10313 // data-processing instruction.
10314 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10317 // A constant that can be used as an immediate value in a
10318 // data-processing instruction.
10319 if (ARM_AM::getSOImmVal(CVal) != -1)
10325 if (Subtarget->isThumb()) { // FIXME thumb2
10326 // This must be a constant between -255 and -1, for negated ADD
10327 // immediates. This can be used in GCC with an "n" modifier that
10328 // prints the negated value, for use with SUB instructions. It is
10329 // not useful otherwise but is implemented for compatibility.
10330 if (CVal >= -255 && CVal <= -1)
10333 // This must be a constant between -4095 and 4095. It is not clear
10334 // what this constraint is intended for. Implemented for
10335 // compatibility with GCC.
10336 if (CVal >= -4095 && CVal <= 4095)
10342 if (Subtarget->isThumb1Only()) {
10343 // A 32-bit value where only one byte has a nonzero value. Exclude
10344 // zero to match GCC. This constraint is used by GCC internally for
10345 // constants that can be loaded with a move/shift combination.
10346 // It is not useful otherwise but is implemented for compatibility.
10347 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10349 } else if (Subtarget->isThumb2()) {
10350 // A constant whose bitwise inverse can be used as an immediate
10351 // value in a data-processing instruction. This can be used in GCC
10352 // with a "B" modifier that prints the inverted value, for use with
10353 // BIC and MVN instructions. It is not useful otherwise but is
10354 // implemented for compatibility.
10355 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10358 // A constant whose bitwise inverse can be used as an immediate
10359 // value in a data-processing instruction. This can be used in GCC
10360 // with a "B" modifier that prints the inverted value, for use with
10361 // BIC and MVN instructions. It is not useful otherwise but is
10362 // implemented for compatibility.
10363 if (ARM_AM::getSOImmVal(~CVal) != -1)
10369 if (Subtarget->isThumb1Only()) {
10370 // This must be a constant between -7 and 7,
10371 // for 3-operand ADD/SUB immediate instructions.
10372 if (CVal >= -7 && CVal < 7)
10374 } else if (Subtarget->isThumb2()) {
10375 // A constant whose negation can be used as an immediate value in a
10376 // data-processing instruction. This can be used in GCC with an "n"
10377 // modifier that prints the negated value, for use with SUB
10378 // instructions. It is not useful otherwise but is implemented for
10380 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10383 // A constant whose negation can be used as an immediate value in a
10384 // data-processing instruction. This can be used in GCC with an "n"
10385 // modifier that prints the negated value, for use with SUB
10386 // instructions. It is not useful otherwise but is implemented for
10388 if (ARM_AM::getSOImmVal(-CVal) != -1)
10394 if (Subtarget->isThumb()) { // FIXME thumb2
10395 // This must be a multiple of 4 between 0 and 1020, for
10396 // ADD sp + immediate.
10397 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10400 // A power of two or a constant between 0 and 32. This is used in
10401 // GCC for the shift amount on shifted register operands, but it is
10402 // useful in general for any shift amounts.
10403 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10409 if (Subtarget->isThumb()) { // FIXME thumb2
10410 // This must be a constant between 0 and 31, for shift amounts.
10411 if (CVal >= 0 && CVal <= 31)
10417 if (Subtarget->isThumb()) { // FIXME thumb2
10418 // This must be a multiple of 4 between -508 and 508, for
10419 // ADD/SUB sp = sp + immediate.
10420 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10425 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10429 if (Result.getNode()) {
10430 Ops.push_back(Result);
10433 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10436 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10437 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10438 unsigned Opcode = Op->getOpcode();
10439 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10440 "Invalid opcode for Div/Rem lowering");
10441 bool isSigned = (Opcode == ISD::SDIVREM);
10442 EVT VT = Op->getValueType(0);
10443 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10446 switch (VT.getSimpleVT().SimpleTy) {
10447 default: llvm_unreachable("Unexpected request for libcall!");
10448 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10449 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10450 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10451 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10454 SDValue InChain = DAG.getEntryNode();
10456 TargetLowering::ArgListTy Args;
10457 TargetLowering::ArgListEntry Entry;
10458 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10459 EVT ArgVT = Op->getOperand(i).getValueType();
10460 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10461 Entry.Node = Op->getOperand(i);
10463 Entry.isSExt = isSigned;
10464 Entry.isZExt = !isSigned;
10465 Args.push_back(Entry);
10468 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10471 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10474 TargetLowering::CallLoweringInfo CLI(DAG);
10475 CLI.setDebugLoc(dl).setChain(InChain)
10476 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, &Args, 0)
10477 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10479 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10480 return CallInfo.first;
10484 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10485 // The ARM target isn't yet aware of offsets.
10489 bool ARM::isBitFieldInvertedMask(unsigned v) {
10490 if (v == 0xffffffff)
10493 // there can be 1's on either or both "outsides", all the "inside"
10494 // bits must be 0's
10495 unsigned TO = CountTrailingOnes_32(v);
10496 unsigned LO = CountLeadingOnes_32(v);
10497 v = (v >> TO) << TO;
10498 v = (v << LO) >> LO;
10502 /// isFPImmLegal - Returns true if the target can instruction select the
10503 /// specified FP immediate natively. If false, the legalizer will
10504 /// materialize the FP immediate as a load from a constant pool.
10505 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10506 if (!Subtarget->hasVFP3())
10508 if (VT == MVT::f32)
10509 return ARM_AM::getFP32Imm(Imm) != -1;
10510 if (VT == MVT::f64)
10511 return ARM_AM::getFP64Imm(Imm) != -1;
10515 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10516 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10517 /// specified in the intrinsic calls.
10518 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10520 unsigned Intrinsic) const {
10521 switch (Intrinsic) {
10522 case Intrinsic::arm_neon_vld1:
10523 case Intrinsic::arm_neon_vld2:
10524 case Intrinsic::arm_neon_vld3:
10525 case Intrinsic::arm_neon_vld4:
10526 case Intrinsic::arm_neon_vld2lane:
10527 case Intrinsic::arm_neon_vld3lane:
10528 case Intrinsic::arm_neon_vld4lane: {
10529 Info.opc = ISD::INTRINSIC_W_CHAIN;
10530 // Conservatively set memVT to the entire set of vectors loaded.
10531 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10532 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10533 Info.ptrVal = I.getArgOperand(0);
10535 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10536 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10537 Info.vol = false; // volatile loads with NEON intrinsics not supported
10538 Info.readMem = true;
10539 Info.writeMem = false;
10542 case Intrinsic::arm_neon_vst1:
10543 case Intrinsic::arm_neon_vst2:
10544 case Intrinsic::arm_neon_vst3:
10545 case Intrinsic::arm_neon_vst4:
10546 case Intrinsic::arm_neon_vst2lane:
10547 case Intrinsic::arm_neon_vst3lane:
10548 case Intrinsic::arm_neon_vst4lane: {
10549 Info.opc = ISD::INTRINSIC_VOID;
10550 // Conservatively set memVT to the entire set of vectors stored.
10551 unsigned NumElts = 0;
10552 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10553 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10554 if (!ArgTy->isVectorTy())
10556 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10558 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10559 Info.ptrVal = I.getArgOperand(0);
10561 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10562 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10563 Info.vol = false; // volatile stores with NEON intrinsics not supported
10564 Info.readMem = false;
10565 Info.writeMem = true;
10568 case Intrinsic::arm_ldaex:
10569 case Intrinsic::arm_ldrex: {
10570 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10571 Info.opc = ISD::INTRINSIC_W_CHAIN;
10572 Info.memVT = MVT::getVT(PtrTy->getElementType());
10573 Info.ptrVal = I.getArgOperand(0);
10575 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10577 Info.readMem = true;
10578 Info.writeMem = false;
10581 case Intrinsic::arm_stlex:
10582 case Intrinsic::arm_strex: {
10583 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10584 Info.opc = ISD::INTRINSIC_W_CHAIN;
10585 Info.memVT = MVT::getVT(PtrTy->getElementType());
10586 Info.ptrVal = I.getArgOperand(1);
10588 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10590 Info.readMem = false;
10591 Info.writeMem = true;
10594 case Intrinsic::arm_stlexd:
10595 case Intrinsic::arm_strexd: {
10596 Info.opc = ISD::INTRINSIC_W_CHAIN;
10597 Info.memVT = MVT::i64;
10598 Info.ptrVal = I.getArgOperand(2);
10602 Info.readMem = false;
10603 Info.writeMem = true;
10606 case Intrinsic::arm_ldaexd:
10607 case Intrinsic::arm_ldrexd: {
10608 Info.opc = ISD::INTRINSIC_W_CHAIN;
10609 Info.memVT = MVT::i64;
10610 Info.ptrVal = I.getArgOperand(0);
10614 Info.readMem = true;
10615 Info.writeMem = false;
10625 /// \brief Returns true if it is beneficial to convert a load of a constant
10626 /// to just the constant itself.
10627 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10629 assert(Ty->isIntegerTy());
10631 unsigned Bits = Ty->getPrimitiveSizeInBits();
10632 if (Bits == 0 || Bits > 32)
10637 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10638 // Loads and stores less than 64-bits are already atomic; ones above that
10639 // are doomed anyway, so defer to the default libcall and blame the OS when
10640 // things go wrong:
10641 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10642 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10643 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10644 return LI->getType()->getPrimitiveSizeInBits() == 64;
10646 // For the real atomic operations, we have ldrex/strex up to 64 bits.
10647 return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10650 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10651 AtomicOrdering Ord) const {
10652 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10653 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10655 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10657 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10658 // intrinsic must return {i32, i32} and we have to recombine them into a
10659 // single i64 here.
10660 if (ValTy->getPrimitiveSizeInBits() == 64) {
10661 Intrinsic::ID Int =
10662 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10663 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10665 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10666 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10668 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10669 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10670 if (!Subtarget->isLittle())
10671 std::swap (Lo, Hi);
10672 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10673 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10674 return Builder.CreateOr(
10675 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10678 Type *Tys[] = { Addr->getType() };
10679 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10680 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10682 return Builder.CreateTruncOrBitCast(
10683 Builder.CreateCall(Ldrex, Addr),
10684 cast<PointerType>(Addr->getType())->getElementType());
10687 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10689 AtomicOrdering Ord) const {
10690 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10692 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10694 // Since the intrinsics must have legal type, the i64 intrinsics take two
10695 // parameters: "i32, i32". We must marshal Val into the appropriate form
10696 // before the call.
10697 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10698 Intrinsic::ID Int =
10699 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10700 Function *Strex = Intrinsic::getDeclaration(M, Int);
10701 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10703 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10704 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10705 if (!Subtarget->isLittle())
10706 std::swap (Lo, Hi);
10707 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10708 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10711 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10712 Type *Tys[] = { Addr->getType() };
10713 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10715 return Builder.CreateCall2(
10716 Strex, Builder.CreateZExtOrBitCast(
10717 Val, Strex->getFunctionType()->getParamType(0)),
10729 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10730 uint64_t &Members) {
10731 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10732 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10733 uint64_t SubMembers = 0;
10734 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10736 Members += SubMembers;
10738 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10739 uint64_t SubMembers = 0;
10740 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10742 Members += SubMembers * AT->getNumElements();
10743 } else if (Ty->isFloatTy()) {
10744 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10748 } else if (Ty->isDoubleTy()) {
10749 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10753 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10760 return VT->getBitWidth() == 64;
10762 return VT->getBitWidth() == 128;
10764 switch (VT->getBitWidth()) {
10777 return (Members > 0 && Members <= 4);
10780 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10781 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10782 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10783 if (getEffectiveCallingConv(CallConv, isVarArg) !=
10784 CallingConv::ARM_AAPCS_VFP)
10787 HABaseType Base = HA_UNKNOWN;
10788 uint64_t Members = 0;
10789 bool result = isHomogeneousAggregate(Ty, Base, Members);
10790 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");