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 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
54 STATISTIC(NumTailCalls, "Number of tail calls");
55 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
58 // This option should go away when tail calls fully work.
60 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
61 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
65 EnableARMLongCalls("arm-long-calls", cl::Hidden,
66 cl::desc("Generate calls via indirect call instructions"),
70 ARMInterworking("arm-interworking", cl::Hidden,
71 cl::desc("Enable / disable ARM interworking (for debugging only)"),
75 class ARMCCState : public CCState {
77 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
78 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
79 LLVMContext &C, ParmContext PC)
80 : CCState(CC, isVarArg, MF, TM, locs, C) {
81 assert(((PC == Call) || (PC == Prologue)) &&
82 "ARMCCState users must specify whether their context is call"
83 "or prologue generation.");
89 // The APCS parameter registers.
90 static const uint16_t GPRArgRegs[] = {
91 ARM::R0, ARM::R1, ARM::R2, ARM::R3
94 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
95 MVT PromotedBitwiseVT) {
96 if (VT != PromotedLdStVT) {
97 setOperationAction(ISD::LOAD, VT, Promote);
98 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
100 setOperationAction(ISD::STORE, VT, Promote);
101 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
104 MVT ElemTy = VT.getVectorElementType();
105 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
106 setOperationAction(ISD::SETCC, VT, Custom);
107 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
108 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
109 if (ElemTy == MVT::i32) {
110 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
111 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
112 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
113 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
115 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
116 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
117 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
118 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
120 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
121 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
122 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
123 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
124 setOperationAction(ISD::SELECT, VT, Expand);
125 setOperationAction(ISD::SELECT_CC, VT, Expand);
126 setOperationAction(ISD::VSELECT, VT, Expand);
127 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
128 if (VT.isInteger()) {
129 setOperationAction(ISD::SHL, VT, Custom);
130 setOperationAction(ISD::SRA, VT, Custom);
131 setOperationAction(ISD::SRL, VT, Custom);
134 // Promote all bit-wise operations.
135 if (VT.isInteger() && VT != PromotedBitwiseVT) {
136 setOperationAction(ISD::AND, VT, Promote);
137 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
138 setOperationAction(ISD::OR, VT, Promote);
139 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
140 setOperationAction(ISD::XOR, VT, Promote);
141 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
144 // Neon does not support vector divide/remainder operations.
145 setOperationAction(ISD::SDIV, VT, Expand);
146 setOperationAction(ISD::UDIV, VT, Expand);
147 setOperationAction(ISD::FDIV, VT, Expand);
148 setOperationAction(ISD::SREM, VT, Expand);
149 setOperationAction(ISD::UREM, VT, Expand);
150 setOperationAction(ISD::FREM, VT, Expand);
153 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
154 addRegisterClass(VT, &ARM::DPRRegClass);
155 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
158 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
159 addRegisterClass(VT, &ARM::QPRRegClass);
160 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
163 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
164 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
165 return new TargetLoweringObjectFileMachO();
167 return new ARMElfTargetObjectFile();
170 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
171 : TargetLowering(TM, createTLOF(TM)) {
172 Subtarget = &TM.getSubtarget<ARMSubtarget>();
173 RegInfo = TM.getRegisterInfo();
174 Itins = TM.getInstrItineraryData();
176 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
178 if (Subtarget->isTargetIOS()) {
179 // Uses VFP for Thumb libfuncs if available.
180 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
181 Subtarget->hasARMOps()) {
182 // Single-precision floating-point arithmetic.
183 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
184 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
185 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
186 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
188 // Double-precision floating-point arithmetic.
189 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
190 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
191 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
192 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
194 // Single-precision comparisons.
195 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
196 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
197 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
198 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
199 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
200 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
201 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
202 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
204 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
209 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
210 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
211 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
213 // Double-precision comparisons.
214 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
215 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
216 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
217 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
218 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
219 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
220 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
221 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
223 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
228 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
229 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
230 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
232 // Floating-point to integer conversions.
233 // i64 conversions are done via library routines even when generating VFP
234 // instructions, so use the same ones.
235 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
236 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
237 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
238 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
240 // Conversions between floating types.
241 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
242 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
244 // Integer to floating-point conversions.
245 // i64 conversions are done via library routines even when generating VFP
246 // instructions, so use the same ones.
247 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
248 // e.g., __floatunsidf vs. __floatunssidfvfp.
249 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
250 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
251 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
252 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
256 // These libcalls are not available in 32-bit.
257 setLibcallName(RTLIB::SHL_I128, 0);
258 setLibcallName(RTLIB::SRL_I128, 0);
259 setLibcallName(RTLIB::SRA_I128, 0);
261 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
262 // Double-precision floating-point arithmetic helper functions
263 // RTABI chapter 4.1.2, Table 2
264 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
265 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
266 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
267 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
268 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
269 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
270 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
271 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
273 // Double-precision floating-point comparison helper functions
274 // RTABI chapter 4.1.2, Table 3
275 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
276 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
277 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
278 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
279 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
280 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
281 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
282 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
283 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
284 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
285 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
286 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
287 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
288 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
289 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
290 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
291 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
296 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
297 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
298 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
300 // Single-precision floating-point arithmetic helper functions
301 // RTABI chapter 4.1.2, Table 4
302 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
303 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
304 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
305 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
306 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
307 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
308 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
309 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
311 // Single-precision floating-point comparison helper functions
312 // RTABI chapter 4.1.2, Table 5
313 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
314 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
315 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
316 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
317 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
318 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
319 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
320 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
321 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
322 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
323 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
324 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
325 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
326 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
327 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
328 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
329 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
334 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
335 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
336 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
338 // Floating-point to integer conversions.
339 // RTABI chapter 4.1.2, Table 6
340 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
341 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
342 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
343 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
344 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
345 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
346 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
347 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
348 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
353 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
354 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
355 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
357 // Conversions between floating types.
358 // RTABI chapter 4.1.2, Table 7
359 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
360 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
361 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
362 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
364 // Integer to floating-point conversions.
365 // RTABI chapter 4.1.2, Table 8
366 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
367 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
368 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
369 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
370 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
371 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
372 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
373 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
374 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
379 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
380 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
381 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
383 // Long long helper functions
384 // RTABI chapter 4.2, Table 9
385 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
386 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
387 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
388 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
389 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
393 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
394 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
396 // Integer division functions
397 // RTABI chapter 4.3.1
398 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
399 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
400 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
401 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
402 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
403 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
404 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
405 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
406 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
411 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
412 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
413 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
416 // RTABI chapter 4.3.4
417 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
418 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
419 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
420 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
421 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
422 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
425 // Use divmod compiler-rt calls for iOS 5.0 and later.
426 if (Subtarget->getTargetTriple().isiOS() &&
427 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
428 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
429 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
432 if (Subtarget->isThumb1Only())
433 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
435 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
436 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
437 !Subtarget->isThumb1Only()) {
438 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
439 if (!Subtarget->isFPOnlySP())
440 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
442 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
445 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
447 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
448 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
449 setTruncStoreAction((MVT::SimpleValueType)VT,
450 (MVT::SimpleValueType)InnerVT, Expand);
451 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
452 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
453 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
456 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
457 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
459 if (Subtarget->hasNEON()) {
460 addDRTypeForNEON(MVT::v2f32);
461 addDRTypeForNEON(MVT::v8i8);
462 addDRTypeForNEON(MVT::v4i16);
463 addDRTypeForNEON(MVT::v2i32);
464 addDRTypeForNEON(MVT::v1i64);
466 addQRTypeForNEON(MVT::v4f32);
467 addQRTypeForNEON(MVT::v2f64);
468 addQRTypeForNEON(MVT::v16i8);
469 addQRTypeForNEON(MVT::v8i16);
470 addQRTypeForNEON(MVT::v4i32);
471 addQRTypeForNEON(MVT::v2i64);
473 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474 // neither Neon nor VFP support any arithmetic operations on it.
475 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476 // supported for v4f32.
477 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480 // FIXME: Code duplication: FDIV and FREM are expanded always, see
481 // ARMTargetLowering::addTypeForNEON method for details.
482 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484 // FIXME: Create unittest.
485 // In another words, find a way when "copysign" appears in DAG with vector
487 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488 // FIXME: Code duplication: SETCC has custom operation action, see
489 // ARMTargetLowering::addTypeForNEON method for details.
490 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491 // FIXME: Create unittest for FNEG and for FABS.
492 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
512 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
513 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
514 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
515 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
516 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
517 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
518 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
519 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
520 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
521 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
523 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
524 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
525 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
526 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
528 // Mark v2f32 intrinsics.
529 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
530 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
531 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
532 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
533 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
534 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
535 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
536 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
537 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
538 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
539 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
540 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
541 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
542 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
543 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
545 // Neon does not support some operations on v1i64 and v2i64 types.
546 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
547 // Custom handling for some quad-vector types to detect VMULL.
548 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
549 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
550 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
551 // Custom handling for some vector types to avoid expensive expansions
552 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
553 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
554 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
555 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
556 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
557 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
558 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
559 // a destination type that is wider than the source, and nor does
560 // it have a FP_TO_[SU]INT instruction with a narrower destination than
562 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
563 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
564 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
565 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
567 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
568 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
570 // NEON does not have single instruction CTPOP for vectors with element
571 // types wider than 8-bits. However, custom lowering can leverage the
572 // v8i8/v16i8 vcnt instruction.
573 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
574 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
575 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
576 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
578 // NEON only has FMA instructions as of VFP4.
579 if (!Subtarget->hasVFP4()) {
580 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
581 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
584 setTargetDAGCombine(ISD::INTRINSIC_VOID);
585 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
586 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
587 setTargetDAGCombine(ISD::SHL);
588 setTargetDAGCombine(ISD::SRL);
589 setTargetDAGCombine(ISD::SRA);
590 setTargetDAGCombine(ISD::SIGN_EXTEND);
591 setTargetDAGCombine(ISD::ZERO_EXTEND);
592 setTargetDAGCombine(ISD::ANY_EXTEND);
593 setTargetDAGCombine(ISD::SELECT_CC);
594 setTargetDAGCombine(ISD::BUILD_VECTOR);
595 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
596 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
597 setTargetDAGCombine(ISD::STORE);
598 setTargetDAGCombine(ISD::FP_TO_SINT);
599 setTargetDAGCombine(ISD::FP_TO_UINT);
600 setTargetDAGCombine(ISD::FDIV);
602 // It is legal to extload from v4i8 to v4i16 or v4i32.
603 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
604 MVT::v4i16, MVT::v2i16,
606 for (unsigned i = 0; i < 6; ++i) {
607 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
608 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
609 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
613 // ARM and Thumb2 support UMLAL/SMLAL.
614 if (!Subtarget->isThumb1Only())
615 setTargetDAGCombine(ISD::ADDC);
618 computeRegisterProperties();
620 // ARM does not have f32 extending load.
621 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
623 // ARM does not have i1 sign extending load.
624 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
626 // ARM supports all 4 flavors of integer indexed load / store.
627 if (!Subtarget->isThumb1Only()) {
628 for (unsigned im = (unsigned)ISD::PRE_INC;
629 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
630 setIndexedLoadAction(im, MVT::i1, Legal);
631 setIndexedLoadAction(im, MVT::i8, Legal);
632 setIndexedLoadAction(im, MVT::i16, Legal);
633 setIndexedLoadAction(im, MVT::i32, Legal);
634 setIndexedStoreAction(im, MVT::i1, Legal);
635 setIndexedStoreAction(im, MVT::i8, Legal);
636 setIndexedStoreAction(im, MVT::i16, Legal);
637 setIndexedStoreAction(im, MVT::i32, Legal);
641 // i64 operation support.
642 setOperationAction(ISD::MUL, MVT::i64, Expand);
643 setOperationAction(ISD::MULHU, MVT::i32, Expand);
644 if (Subtarget->isThumb1Only()) {
645 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
646 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
648 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
649 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
650 setOperationAction(ISD::MULHS, MVT::i32, Expand);
652 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
653 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
654 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
655 setOperationAction(ISD::SRL, MVT::i64, Custom);
656 setOperationAction(ISD::SRA, MVT::i64, Custom);
658 if (!Subtarget->isThumb1Only()) {
659 // FIXME: We should do this for Thumb1 as well.
660 setOperationAction(ISD::ADDC, MVT::i32, Custom);
661 setOperationAction(ISD::ADDE, MVT::i32, Custom);
662 setOperationAction(ISD::SUBC, MVT::i32, Custom);
663 setOperationAction(ISD::SUBE, MVT::i32, Custom);
666 // ARM does not have ROTL.
667 setOperationAction(ISD::ROTL, MVT::i32, Expand);
668 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
669 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
670 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
671 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
673 // These just redirect to CTTZ and CTLZ on ARM.
674 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
675 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
677 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
679 // Only ARMv6 has BSWAP.
680 if (!Subtarget->hasV6Ops())
681 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
683 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
684 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
685 // These are expanded into libcalls if the cpu doesn't have HW divider.
686 setOperationAction(ISD::SDIV, MVT::i32, Expand);
687 setOperationAction(ISD::UDIV, MVT::i32, Expand);
690 // FIXME: Also set divmod for SREM on EABI
691 setOperationAction(ISD::SREM, MVT::i32, Expand);
692 setOperationAction(ISD::UREM, MVT::i32, Expand);
693 // Register based DivRem for AEABI (RTABI 4.2)
694 if (Subtarget->isTargetAEABI()) {
695 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
696 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
697 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
698 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
699 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
700 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
701 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
702 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
704 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
705 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
706 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
707 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
708 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
709 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
710 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
711 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
713 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
714 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
716 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
717 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
720 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
721 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
722 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
723 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
724 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
726 setOperationAction(ISD::TRAP, MVT::Other, Legal);
728 // Use the default implementation.
729 setOperationAction(ISD::VASTART, MVT::Other, Custom);
730 setOperationAction(ISD::VAARG, MVT::Other, Expand);
731 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
732 setOperationAction(ISD::VAEND, MVT::Other, Expand);
733 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
734 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
736 if (!Subtarget->isTargetDarwin()) {
737 // Non-Darwin platforms may return values in these registers via the
738 // personality function.
739 setExceptionPointerRegister(ARM::R0);
740 setExceptionSelectorRegister(ARM::R1);
743 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
744 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
745 // the default expansion.
746 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
747 // ATOMIC_FENCE needs custom lowering; the other 32-bit ones are legal and
749 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
750 // Custom lowering for 64-bit ops
751 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
752 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
753 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
754 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
755 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
756 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
757 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
758 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
759 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
760 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
761 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
762 // On v8, we have particularly efficient implementations of atomic fences
763 // if they can be combined with nearby atomic loads and stores.
764 if (!Subtarget->hasV8Ops()) {
765 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
766 setInsertFencesForAtomic(true);
768 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
770 // If there's anything we can use as a barrier, go through custom lowering
772 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
773 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
775 // Set them all for expansion, which will force libcalls.
776 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
777 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
778 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
779 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
780 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
781 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
782 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
783 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
784 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
785 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
786 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
787 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
788 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
789 // Unordered/Monotonic case.
790 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
791 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
794 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
796 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
797 if (!Subtarget->hasV6Ops()) {
798 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
799 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
801 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
803 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
804 !Subtarget->isThumb1Only()) {
805 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
806 // iff target supports vfp2.
807 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
808 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
811 // We want to custom lower some of our intrinsics.
812 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
813 if (Subtarget->isTargetDarwin()) {
814 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
815 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
816 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
819 setOperationAction(ISD::SETCC, MVT::i32, Expand);
820 setOperationAction(ISD::SETCC, MVT::f32, Expand);
821 setOperationAction(ISD::SETCC, MVT::f64, Expand);
822 setOperationAction(ISD::SELECT, MVT::i32, Custom);
823 setOperationAction(ISD::SELECT, MVT::f32, Custom);
824 setOperationAction(ISD::SELECT, MVT::f64, Custom);
825 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
826 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
827 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
829 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
830 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
831 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
832 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
833 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
835 // We don't support sin/cos/fmod/copysign/pow
836 setOperationAction(ISD::FSIN, MVT::f64, Expand);
837 setOperationAction(ISD::FSIN, MVT::f32, Expand);
838 setOperationAction(ISD::FCOS, MVT::f32, Expand);
839 setOperationAction(ISD::FCOS, MVT::f64, Expand);
840 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
841 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
842 setOperationAction(ISD::FREM, MVT::f64, Expand);
843 setOperationAction(ISD::FREM, MVT::f32, Expand);
844 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
845 !Subtarget->isThumb1Only()) {
846 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
847 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
849 setOperationAction(ISD::FPOW, MVT::f64, Expand);
850 setOperationAction(ISD::FPOW, MVT::f32, Expand);
852 if (!Subtarget->hasVFP4()) {
853 setOperationAction(ISD::FMA, MVT::f64, Expand);
854 setOperationAction(ISD::FMA, MVT::f32, Expand);
857 // Various VFP goodness
858 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
859 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
860 if (Subtarget->hasVFP2()) {
861 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
862 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
863 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
864 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
866 // Special handling for half-precision FP.
867 if (!Subtarget->hasFP16()) {
868 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
869 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
873 // We have target-specific dag combine patterns for the following nodes:
874 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
875 setTargetDAGCombine(ISD::ADD);
876 setTargetDAGCombine(ISD::SUB);
877 setTargetDAGCombine(ISD::MUL);
878 setTargetDAGCombine(ISD::AND);
879 setTargetDAGCombine(ISD::OR);
880 setTargetDAGCombine(ISD::XOR);
882 if (Subtarget->hasV6Ops())
883 setTargetDAGCombine(ISD::SRL);
885 setStackPointerRegisterToSaveRestore(ARM::SP);
887 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
888 !Subtarget->hasVFP2())
889 setSchedulingPreference(Sched::RegPressure);
891 setSchedulingPreference(Sched::Hybrid);
893 //// temporary - rewrite interface to use type
894 MaxStoresPerMemset = 8;
895 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
896 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
897 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
898 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
899 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
901 // On ARM arguments smaller than 4 bytes are extended, so all arguments
902 // are at least 4 bytes aligned.
903 setMinStackArgumentAlignment(4);
905 // Prefer likely predicted branches to selects on out-of-order cores.
906 PredictableSelectIsExpensive = Subtarget->isLikeA9();
908 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
911 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
912 bool isThumb2, unsigned &LdrOpc,
914 static const unsigned LoadBares[4][2] = {{ARM::LDREXB, ARM::t2LDREXB},
915 {ARM::LDREXH, ARM::t2LDREXH},
916 {ARM::LDREX, ARM::t2LDREX},
917 {ARM::LDREXD, ARM::t2LDREXD}};
918 static const unsigned LoadAcqs[4][2] = {{ARM::LDAEXB, ARM::t2LDAEXB},
919 {ARM::LDAEXH, ARM::t2LDAEXH},
920 {ARM::LDAEX, ARM::t2LDAEX},
921 {ARM::LDAEXD, ARM::t2LDAEXD}};
922 static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
923 {ARM::STREXH, ARM::t2STREXH},
924 {ARM::STREX, ARM::t2STREX},
925 {ARM::STREXD, ARM::t2STREXD}};
926 static const unsigned StoreRels[4][2] = {{ARM::STLEXB, ARM::t2STLEXB},
927 {ARM::STLEXH, ARM::t2STLEXH},
928 {ARM::STLEX, ARM::t2STLEX},
929 {ARM::STLEXD, ARM::t2STLEXD}};
931 const unsigned (*LoadOps)[2], (*StoreOps)[2];
932 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
937 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
938 StoreOps = StoreRels;
940 StoreOps = StoreBares;
942 assert(isPowerOf2_32(Size) && Size <= 8 &&
943 "unsupported size for atomic binary op!");
945 LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
946 StrOpc = StoreOps[Log2_32(Size)][isThumb2];
949 // FIXME: It might make sense to define the representative register class as the
950 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
951 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
952 // SPR's representative would be DPR_VFP2. This should work well if register
953 // pressure tracking were modified such that a register use would increment the
954 // pressure of the register class's representative and all of it's super
955 // classes' representatives transitively. We have not implemented this because
956 // of the difficulty prior to coalescing of modeling operand register classes
957 // due to the common occurrence of cross class copies and subregister insertions
959 std::pair<const TargetRegisterClass*, uint8_t>
960 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
961 const TargetRegisterClass *RRC = 0;
963 switch (VT.SimpleTy) {
965 return TargetLowering::findRepresentativeClass(VT);
966 // Use DPR as representative register class for all floating point
967 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
968 // the cost is 1 for both f32 and f64.
969 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
970 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
971 RRC = &ARM::DPRRegClass;
972 // When NEON is used for SP, only half of the register file is available
973 // because operations that define both SP and DP results will be constrained
974 // to the VFP2 class (D0-D15). We currently model this constraint prior to
975 // coalescing by double-counting the SP regs. See the FIXME above.
976 if (Subtarget->useNEONForSinglePrecisionFP())
979 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
980 case MVT::v4f32: case MVT::v2f64:
981 RRC = &ARM::DPRRegClass;
985 RRC = &ARM::DPRRegClass;
989 RRC = &ARM::DPRRegClass;
993 return std::make_pair(RRC, Cost);
996 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
999 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1000 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
1001 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1002 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1003 case ARMISD::CALL: return "ARMISD::CALL";
1004 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1005 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1006 case ARMISD::tCALL: return "ARMISD::tCALL";
1007 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1008 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1009 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1010 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1011 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1012 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1013 case ARMISD::CMP: return "ARMISD::CMP";
1014 case ARMISD::CMN: return "ARMISD::CMN";
1015 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1016 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1017 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1018 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1019 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1021 case ARMISD::CMOV: return "ARMISD::CMOV";
1023 case ARMISD::RBIT: return "ARMISD::RBIT";
1025 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1026 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1027 case ARMISD::SITOF: return "ARMISD::SITOF";
1028 case ARMISD::UITOF: return "ARMISD::UITOF";
1030 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1031 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1032 case ARMISD::RRX: return "ARMISD::RRX";
1034 case ARMISD::ADDC: return "ARMISD::ADDC";
1035 case ARMISD::ADDE: return "ARMISD::ADDE";
1036 case ARMISD::SUBC: return "ARMISD::SUBC";
1037 case ARMISD::SUBE: return "ARMISD::SUBE";
1039 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1040 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1042 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1043 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1045 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1047 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1049 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1051 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1053 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1055 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1056 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1057 case ARMISD::VCGE: return "ARMISD::VCGE";
1058 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1059 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1060 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1061 case ARMISD::VCGT: return "ARMISD::VCGT";
1062 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1063 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1064 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1065 case ARMISD::VTST: return "ARMISD::VTST";
1067 case ARMISD::VSHL: return "ARMISD::VSHL";
1068 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1069 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1070 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
1071 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
1072 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
1073 case ARMISD::VSHRN: return "ARMISD::VSHRN";
1074 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1075 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1076 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1077 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1078 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1079 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1080 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1081 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1082 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1083 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1084 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1085 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1086 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1087 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1088 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1089 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1090 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1091 case ARMISD::VDUP: return "ARMISD::VDUP";
1092 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1093 case ARMISD::VEXT: return "ARMISD::VEXT";
1094 case ARMISD::VREV64: return "ARMISD::VREV64";
1095 case ARMISD::VREV32: return "ARMISD::VREV32";
1096 case ARMISD::VREV16: return "ARMISD::VREV16";
1097 case ARMISD::VZIP: return "ARMISD::VZIP";
1098 case ARMISD::VUZP: return "ARMISD::VUZP";
1099 case ARMISD::VTRN: return "ARMISD::VTRN";
1100 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1101 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1102 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1103 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1104 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1105 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1106 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1107 case ARMISD::FMAX: return "ARMISD::FMAX";
1108 case ARMISD::FMIN: return "ARMISD::FMIN";
1109 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1110 case ARMISD::VMINNM: return "ARMISD::VMIN";
1111 case ARMISD::BFI: return "ARMISD::BFI";
1112 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1113 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1114 case ARMISD::VBSL: return "ARMISD::VBSL";
1115 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1116 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1117 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1118 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1119 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1120 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1121 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1122 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1123 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1124 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1125 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1126 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1127 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1128 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1129 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1130 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1131 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1132 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1133 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1134 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1138 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1139 if (!VT.isVector()) return getPointerTy();
1140 return VT.changeVectorElementTypeToInteger();
1143 /// getRegClassFor - Return the register class that should be used for the
1144 /// specified value type.
1145 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1146 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1147 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1148 // load / store 4 to 8 consecutive D registers.
1149 if (Subtarget->hasNEON()) {
1150 if (VT == MVT::v4i64)
1151 return &ARM::QQPRRegClass;
1152 if (VT == MVT::v8i64)
1153 return &ARM::QQQQPRRegClass;
1155 return TargetLowering::getRegClassFor(VT);
1158 // Create a fast isel object.
1160 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1161 const TargetLibraryInfo *libInfo) const {
1162 return ARM::createFastISel(funcInfo, libInfo);
1165 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1166 /// be used for loads / stores from the global.
1167 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1168 return (Subtarget->isThumb1Only() ? 127 : 4095);
1171 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1172 unsigned NumVals = N->getNumValues();
1174 return Sched::RegPressure;
1176 for (unsigned i = 0; i != NumVals; ++i) {
1177 EVT VT = N->getValueType(i);
1178 if (VT == MVT::Glue || VT == MVT::Other)
1180 if (VT.isFloatingPoint() || VT.isVector())
1184 if (!N->isMachineOpcode())
1185 return Sched::RegPressure;
1187 // Load are scheduled for latency even if there instruction itinerary
1188 // is not available.
1189 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1190 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1192 if (MCID.getNumDefs() == 0)
1193 return Sched::RegPressure;
1194 if (!Itins->isEmpty() &&
1195 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1198 return Sched::RegPressure;
1201 //===----------------------------------------------------------------------===//
1203 //===----------------------------------------------------------------------===//
1205 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1206 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1208 default: llvm_unreachable("Unknown condition code!");
1209 case ISD::SETNE: return ARMCC::NE;
1210 case ISD::SETEQ: return ARMCC::EQ;
1211 case ISD::SETGT: return ARMCC::GT;
1212 case ISD::SETGE: return ARMCC::GE;
1213 case ISD::SETLT: return ARMCC::LT;
1214 case ISD::SETLE: return ARMCC::LE;
1215 case ISD::SETUGT: return ARMCC::HI;
1216 case ISD::SETUGE: return ARMCC::HS;
1217 case ISD::SETULT: return ARMCC::LO;
1218 case ISD::SETULE: return ARMCC::LS;
1222 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1223 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1224 ARMCC::CondCodes &CondCode2) {
1225 CondCode2 = ARMCC::AL;
1227 default: llvm_unreachable("Unknown FP condition!");
1229 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1231 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1233 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1234 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1235 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1236 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1237 case ISD::SETO: CondCode = ARMCC::VC; break;
1238 case ISD::SETUO: CondCode = ARMCC::VS; break;
1239 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1240 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1241 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1243 case ISD::SETULT: CondCode = ARMCC::LT; break;
1245 case ISD::SETULE: CondCode = ARMCC::LE; break;
1247 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1251 //===----------------------------------------------------------------------===//
1252 // Calling Convention Implementation
1253 //===----------------------------------------------------------------------===//
1255 #include "ARMGenCallingConv.inc"
1257 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1258 /// given CallingConvention value.
1259 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1261 bool isVarArg) const {
1264 llvm_unreachable("Unsupported calling convention");
1265 case CallingConv::Fast:
1266 if (Subtarget->hasVFP2() && !isVarArg) {
1267 if (!Subtarget->isAAPCS_ABI())
1268 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1269 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1270 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1273 case CallingConv::C: {
1274 // Use target triple & subtarget features to do actual dispatch.
1275 if (!Subtarget->isAAPCS_ABI())
1276 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1277 else if (Subtarget->hasVFP2() &&
1278 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1280 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1281 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1283 case CallingConv::ARM_AAPCS_VFP:
1285 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1287 case CallingConv::ARM_AAPCS:
1288 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1289 case CallingConv::ARM_APCS:
1290 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1291 case CallingConv::GHC:
1292 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1296 /// LowerCallResult - Lower the result values of a call into the
1297 /// appropriate copies out of appropriate physical registers.
1299 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1300 CallingConv::ID CallConv, bool isVarArg,
1301 const SmallVectorImpl<ISD::InputArg> &Ins,
1302 SDLoc dl, SelectionDAG &DAG,
1303 SmallVectorImpl<SDValue> &InVals,
1304 bool isThisReturn, SDValue ThisVal) const {
1306 // Assign locations to each value returned by this call.
1307 SmallVector<CCValAssign, 16> RVLocs;
1308 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1309 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1310 CCInfo.AnalyzeCallResult(Ins,
1311 CCAssignFnForNode(CallConv, /* Return*/ true,
1314 // Copy all of the result registers out of their specified physreg.
1315 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1316 CCValAssign VA = RVLocs[i];
1318 // Pass 'this' value directly from the argument to return value, to avoid
1319 // reg unit interference
1320 if (i == 0 && isThisReturn) {
1321 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1322 "unexpected return calling convention register assignment");
1323 InVals.push_back(ThisVal);
1328 if (VA.needsCustom()) {
1329 // Handle f64 or half of a v2f64.
1330 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1332 Chain = Lo.getValue(1);
1333 InFlag = Lo.getValue(2);
1334 VA = RVLocs[++i]; // skip ahead to next loc
1335 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1337 Chain = Hi.getValue(1);
1338 InFlag = Hi.getValue(2);
1339 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1341 if (VA.getLocVT() == MVT::v2f64) {
1342 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1343 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1344 DAG.getConstant(0, MVT::i32));
1346 VA = RVLocs[++i]; // skip ahead to next loc
1347 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1348 Chain = Lo.getValue(1);
1349 InFlag = Lo.getValue(2);
1350 VA = RVLocs[++i]; // skip ahead to next loc
1351 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1352 Chain = Hi.getValue(1);
1353 InFlag = Hi.getValue(2);
1354 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1355 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1356 DAG.getConstant(1, MVT::i32));
1359 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1361 Chain = Val.getValue(1);
1362 InFlag = Val.getValue(2);
1365 switch (VA.getLocInfo()) {
1366 default: llvm_unreachable("Unknown loc info!");
1367 case CCValAssign::Full: break;
1368 case CCValAssign::BCvt:
1369 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1373 InVals.push_back(Val);
1379 /// LowerMemOpCallTo - Store the argument to the stack.
1381 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1382 SDValue StackPtr, SDValue Arg,
1383 SDLoc dl, SelectionDAG &DAG,
1384 const CCValAssign &VA,
1385 ISD::ArgFlagsTy Flags) const {
1386 unsigned LocMemOffset = VA.getLocMemOffset();
1387 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1388 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1389 return DAG.getStore(Chain, dl, Arg, PtrOff,
1390 MachinePointerInfo::getStack(LocMemOffset),
1394 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1395 SDValue Chain, SDValue &Arg,
1396 RegsToPassVector &RegsToPass,
1397 CCValAssign &VA, CCValAssign &NextVA,
1399 SmallVectorImpl<SDValue> &MemOpChains,
1400 ISD::ArgFlagsTy Flags) const {
1402 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1403 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1404 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1406 if (NextVA.isRegLoc())
1407 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1409 assert(NextVA.isMemLoc());
1410 if (StackPtr.getNode() == 0)
1411 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1413 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1419 /// LowerCall - Lowering a call into a callseq_start <-
1420 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1423 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1424 SmallVectorImpl<SDValue> &InVals) const {
1425 SelectionDAG &DAG = CLI.DAG;
1427 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1428 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1429 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1430 SDValue Chain = CLI.Chain;
1431 SDValue Callee = CLI.Callee;
1432 bool &isTailCall = CLI.IsTailCall;
1433 CallingConv::ID CallConv = CLI.CallConv;
1434 bool doesNotRet = CLI.DoesNotReturn;
1435 bool isVarArg = CLI.IsVarArg;
1437 MachineFunction &MF = DAG.getMachineFunction();
1438 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1439 bool isThisReturn = false;
1440 bool isSibCall = false;
1441 // Disable tail calls if they're not supported.
1442 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1445 // Check if it's really possible to do a tail call.
1446 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1447 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1448 Outs, OutVals, Ins, DAG);
1449 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1450 // detected sibcalls.
1457 // Analyze operands of the call, assigning locations to each operand.
1458 SmallVector<CCValAssign, 16> ArgLocs;
1459 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1460 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1461 CCInfo.AnalyzeCallOperands(Outs,
1462 CCAssignFnForNode(CallConv, /* Return*/ false,
1465 // Get a count of how many bytes are to be pushed on the stack.
1466 unsigned NumBytes = CCInfo.getNextStackOffset();
1468 // For tail calls, memory operands are available in our caller's stack.
1472 // Adjust the stack pointer for the new arguments...
1473 // These operations are automatically eliminated by the prolog/epilog pass
1475 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1478 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1480 RegsToPassVector RegsToPass;
1481 SmallVector<SDValue, 8> MemOpChains;
1483 // Walk the register/memloc assignments, inserting copies/loads. In the case
1484 // of tail call optimization, arguments are handled later.
1485 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1487 ++i, ++realArgIdx) {
1488 CCValAssign &VA = ArgLocs[i];
1489 SDValue Arg = OutVals[realArgIdx];
1490 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1491 bool isByVal = Flags.isByVal();
1493 // Promote the value if needed.
1494 switch (VA.getLocInfo()) {
1495 default: llvm_unreachable("Unknown loc info!");
1496 case CCValAssign::Full: break;
1497 case CCValAssign::SExt:
1498 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1500 case CCValAssign::ZExt:
1501 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1503 case CCValAssign::AExt:
1504 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1506 case CCValAssign::BCvt:
1507 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1511 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1512 if (VA.needsCustom()) {
1513 if (VA.getLocVT() == MVT::v2f64) {
1514 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1515 DAG.getConstant(0, MVT::i32));
1516 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1517 DAG.getConstant(1, MVT::i32));
1519 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1520 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1522 VA = ArgLocs[++i]; // skip ahead to next loc
1523 if (VA.isRegLoc()) {
1524 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1525 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1527 assert(VA.isMemLoc());
1529 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1530 dl, DAG, VA, Flags));
1533 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1534 StackPtr, MemOpChains, Flags);
1536 } else if (VA.isRegLoc()) {
1537 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1538 assert(VA.getLocVT() == MVT::i32 &&
1539 "unexpected calling convention register assignment");
1540 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1541 "unexpected use of 'returned'");
1542 isThisReturn = true;
1544 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1545 } else if (isByVal) {
1546 assert(VA.isMemLoc());
1547 unsigned offset = 0;
1549 // True if this byval aggregate will be split between registers
1551 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1552 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1554 if (CurByValIdx < ByValArgsCount) {
1556 unsigned RegBegin, RegEnd;
1557 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1559 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1561 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1562 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1563 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1564 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1565 MachinePointerInfo(),
1566 false, false, false,
1567 DAG.InferPtrAlignment(AddArg));
1568 MemOpChains.push_back(Load.getValue(1));
1569 RegsToPass.push_back(std::make_pair(j, Load));
1572 // If parameter size outsides register area, "offset" value
1573 // helps us to calculate stack slot for remained part properly.
1574 offset = RegEnd - RegBegin;
1576 CCInfo.nextInRegsParam();
1579 if (Flags.getByValSize() > 4*offset) {
1580 unsigned LocMemOffset = VA.getLocMemOffset();
1581 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1582 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1584 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1585 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1586 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1588 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1590 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1591 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1592 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1593 Ops, array_lengthof(Ops)));
1595 } else if (!isSibCall) {
1596 assert(VA.isMemLoc());
1598 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1599 dl, DAG, VA, Flags));
1603 if (!MemOpChains.empty())
1604 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1605 &MemOpChains[0], MemOpChains.size());
1607 // Build a sequence of copy-to-reg nodes chained together with token chain
1608 // and flag operands which copy the outgoing args into the appropriate regs.
1610 // Tail call byval lowering might overwrite argument registers so in case of
1611 // tail call optimization the copies to registers are lowered later.
1613 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1614 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1615 RegsToPass[i].second, InFlag);
1616 InFlag = Chain.getValue(1);
1619 // For tail calls lower the arguments to the 'real' stack slot.
1621 // Force all the incoming stack arguments to be loaded from the stack
1622 // before any new outgoing arguments are stored to the stack, because the
1623 // outgoing stack slots may alias the incoming argument stack slots, and
1624 // the alias isn't otherwise explicit. This is slightly more conservative
1625 // than necessary, because it means that each store effectively depends
1626 // on every argument instead of just those arguments it would clobber.
1628 // Do not flag preceding copytoreg stuff together with the following stuff.
1630 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1631 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1632 RegsToPass[i].second, InFlag);
1633 InFlag = Chain.getValue(1);
1638 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1639 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1640 // node so that legalize doesn't hack it.
1641 bool isDirect = false;
1642 bool isARMFunc = false;
1643 bool isLocalARMFunc = false;
1644 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1646 if (EnableARMLongCalls) {
1647 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1648 && "long-calls with non-static relocation model!");
1649 // Handle a global address or an external symbol. If it's not one of
1650 // those, the target's already in a register, so we don't need to do
1652 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1653 const GlobalValue *GV = G->getGlobal();
1654 // Create a constant pool entry for the callee address
1655 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1656 ARMConstantPoolValue *CPV =
1657 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1659 // Get the address of the callee into a register
1660 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1661 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1662 Callee = DAG.getLoad(getPointerTy(), dl,
1663 DAG.getEntryNode(), CPAddr,
1664 MachinePointerInfo::getConstantPool(),
1665 false, false, false, 0);
1666 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1667 const char *Sym = S->getSymbol();
1669 // Create a constant pool entry for the callee address
1670 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1671 ARMConstantPoolValue *CPV =
1672 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1673 ARMPCLabelIndex, 0);
1674 // Get the address of the callee into a register
1675 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1676 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1677 Callee = DAG.getLoad(getPointerTy(), dl,
1678 DAG.getEntryNode(), CPAddr,
1679 MachinePointerInfo::getConstantPool(),
1680 false, false, false, 0);
1682 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1683 const GlobalValue *GV = G->getGlobal();
1685 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1686 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1687 getTargetMachine().getRelocationModel() != Reloc::Static;
1688 isARMFunc = !Subtarget->isThumb() || isStub;
1689 // ARM call to a local ARM function is predicable.
1690 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1691 // tBX takes a register source operand.
1692 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1693 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1694 ARMConstantPoolValue *CPV =
1695 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1696 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1697 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1698 Callee = DAG.getLoad(getPointerTy(), dl,
1699 DAG.getEntryNode(), CPAddr,
1700 MachinePointerInfo::getConstantPool(),
1701 false, false, false, 0);
1702 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1703 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1704 getPointerTy(), Callee, PICLabel);
1706 // On ELF targets for PIC code, direct calls should go through the PLT
1707 unsigned OpFlags = 0;
1708 if (Subtarget->isTargetELF() &&
1709 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1710 OpFlags = ARMII::MO_PLT;
1711 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1713 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1715 bool isStub = Subtarget->isTargetDarwin() &&
1716 getTargetMachine().getRelocationModel() != Reloc::Static;
1717 isARMFunc = !Subtarget->isThumb() || isStub;
1718 // tBX takes a register source operand.
1719 const char *Sym = S->getSymbol();
1720 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1721 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1722 ARMConstantPoolValue *CPV =
1723 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1724 ARMPCLabelIndex, 4);
1725 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1726 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1727 Callee = DAG.getLoad(getPointerTy(), dl,
1728 DAG.getEntryNode(), CPAddr,
1729 MachinePointerInfo::getConstantPool(),
1730 false, false, false, 0);
1731 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1732 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1733 getPointerTy(), Callee, PICLabel);
1735 unsigned OpFlags = 0;
1736 // On ELF targets for PIC code, direct calls should go through the PLT
1737 if (Subtarget->isTargetELF() &&
1738 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1739 OpFlags = ARMII::MO_PLT;
1740 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1744 // FIXME: handle tail calls differently.
1746 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1747 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1748 if (Subtarget->isThumb()) {
1749 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1750 CallOpc = ARMISD::CALL_NOLINK;
1752 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1754 if (!isDirect && !Subtarget->hasV5TOps())
1755 CallOpc = ARMISD::CALL_NOLINK;
1756 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1757 // Emit regular call when code size is the priority
1759 // "mov lr, pc; b _foo" to avoid confusing the RSP
1760 CallOpc = ARMISD::CALL_NOLINK;
1762 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1765 std::vector<SDValue> Ops;
1766 Ops.push_back(Chain);
1767 Ops.push_back(Callee);
1769 // Add argument registers to the end of the list so that they are known live
1771 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1772 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1773 RegsToPass[i].second.getValueType()));
1775 // Add a register mask operand representing the call-preserved registers.
1777 const uint32_t *Mask;
1778 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1779 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1781 // For 'this' returns, use the R0-preserving mask if applicable
1782 Mask = ARI->getThisReturnPreservedMask(CallConv);
1784 // Set isThisReturn to false if the calling convention is not one that
1785 // allows 'returned' to be modeled in this way, so LowerCallResult does
1786 // not try to pass 'this' straight through
1787 isThisReturn = false;
1788 Mask = ARI->getCallPreservedMask(CallConv);
1791 Mask = ARI->getCallPreservedMask(CallConv);
1793 assert(Mask && "Missing call preserved mask for calling convention");
1794 Ops.push_back(DAG.getRegisterMask(Mask));
1797 if (InFlag.getNode())
1798 Ops.push_back(InFlag);
1800 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1802 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1804 // Returns a chain and a flag for retval copy to use.
1805 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1806 InFlag = Chain.getValue(1);
1808 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1809 DAG.getIntPtrConstant(0, true), InFlag, dl);
1811 InFlag = Chain.getValue(1);
1813 // Handle result values, copying them out of physregs into vregs that we
1815 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1816 InVals, isThisReturn,
1817 isThisReturn ? OutVals[0] : SDValue());
1820 /// HandleByVal - Every parameter *after* a byval parameter is passed
1821 /// on the stack. Remember the next parameter register to allocate,
1822 /// and then confiscate the rest of the parameter registers to insure
1825 ARMTargetLowering::HandleByVal(
1826 CCState *State, unsigned &size, unsigned Align) const {
1827 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1828 assert((State->getCallOrPrologue() == Prologue ||
1829 State->getCallOrPrologue() == Call) &&
1830 "unhandled ParmContext");
1832 // For in-prologue parameters handling, we also introduce stack offset
1833 // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1834 // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1835 // NSAA should be evaluted (NSAA means "next stacked argument address").
1836 // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1837 // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1838 unsigned NSAAOffset = State->getNextStackOffset();
1839 if (State->getCallOrPrologue() != Call) {
1840 for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1842 State->getInRegsParamInfo(i, RB, RE);
1843 assert(NSAAOffset >= (RE-RB)*4 &&
1844 "Stack offset for byval regs doesn't introduced anymore?");
1845 NSAAOffset -= (RE-RB)*4;
1848 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1849 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1850 unsigned AlignInRegs = Align / 4;
1851 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1852 for (unsigned i = 0; i < Waste; ++i)
1853 reg = State->AllocateReg(GPRArgRegs, 4);
1856 unsigned excess = 4 * (ARM::R4 - reg);
1858 // Special case when NSAA != SP and parameter size greater than size of
1859 // all remained GPR regs. In that case we can't split parameter, we must
1860 // send it to stack. We also must set NCRN to R4, so waste all
1861 // remained registers.
1862 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1863 while (State->AllocateReg(GPRArgRegs, 4))
1868 // First register for byval parameter is the first register that wasn't
1869 // allocated before this method call, so it would be "reg".
1870 // If parameter is small enough to be saved in range [reg, r4), then
1871 // the end (first after last) register would be reg + param-size-in-regs,
1872 // else parameter would be splitted between registers and stack,
1873 // end register would be r4 in this case.
1874 unsigned ByValRegBegin = reg;
1875 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1876 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1877 // Note, first register is allocated in the beginning of function already,
1878 // allocate remained amount of registers we need.
1879 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1880 State->AllocateReg(GPRArgRegs, 4);
1881 // At a call site, a byval parameter that is split between
1882 // registers and memory needs its size truncated here. In a
1883 // function prologue, such byval parameters are reassembled in
1884 // memory, and are not truncated.
1885 if (State->getCallOrPrologue() == Call) {
1886 // Make remained size equal to 0 in case, when
1887 // the whole structure may be stored into registers.
1897 /// MatchingStackOffset - Return true if the given stack call argument is
1898 /// already available in the same position (relatively) of the caller's
1899 /// incoming argument stack.
1901 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1902 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1903 const TargetInstrInfo *TII) {
1904 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1906 if (Arg.getOpcode() == ISD::CopyFromReg) {
1907 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1908 if (!TargetRegisterInfo::isVirtualRegister(VR))
1910 MachineInstr *Def = MRI->getVRegDef(VR);
1913 if (!Flags.isByVal()) {
1914 if (!TII->isLoadFromStackSlot(Def, FI))
1919 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1920 if (Flags.isByVal())
1921 // ByVal argument is passed in as a pointer but it's now being
1922 // dereferenced. e.g.
1923 // define @foo(%struct.X* %A) {
1924 // tail call @bar(%struct.X* byval %A)
1927 SDValue Ptr = Ld->getBasePtr();
1928 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1931 FI = FINode->getIndex();
1935 assert(FI != INT_MAX);
1936 if (!MFI->isFixedObjectIndex(FI))
1938 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1941 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1942 /// for tail call optimization. Targets which want to do tail call
1943 /// optimization should implement this function.
1945 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1946 CallingConv::ID CalleeCC,
1948 bool isCalleeStructRet,
1949 bool isCallerStructRet,
1950 const SmallVectorImpl<ISD::OutputArg> &Outs,
1951 const SmallVectorImpl<SDValue> &OutVals,
1952 const SmallVectorImpl<ISD::InputArg> &Ins,
1953 SelectionDAG& DAG) const {
1954 const Function *CallerF = DAG.getMachineFunction().getFunction();
1955 CallingConv::ID CallerCC = CallerF->getCallingConv();
1956 bool CCMatch = CallerCC == CalleeCC;
1958 // Look for obvious safe cases to perform tail call optimization that do not
1959 // require ABI changes. This is what gcc calls sibcall.
1961 // Do not sibcall optimize vararg calls unless the call site is not passing
1963 if (isVarArg && !Outs.empty())
1966 // Exception-handling functions need a special set of instructions to indicate
1967 // a return to the hardware. Tail-calling another function would probably
1969 if (CallerF->hasFnAttribute("interrupt"))
1972 // Also avoid sibcall optimization if either caller or callee uses struct
1973 // return semantics.
1974 if (isCalleeStructRet || isCallerStructRet)
1977 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1978 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1979 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1980 // support in the assembler and linker to be used. This would need to be
1981 // fixed to fully support tail calls in Thumb1.
1983 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1984 // LR. This means if we need to reload LR, it takes an extra instructions,
1985 // which outweighs the value of the tail call; but here we don't know yet
1986 // whether LR is going to be used. Probably the right approach is to
1987 // generate the tail call here and turn it back into CALL/RET in
1988 // emitEpilogue if LR is used.
1990 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1991 // but we need to make sure there are enough registers; the only valid
1992 // registers are the 4 used for parameters. We don't currently do this
1994 if (Subtarget->isThumb1Only())
1997 // If the calling conventions do not match, then we'd better make sure the
1998 // results are returned in the same way as what the caller expects.
2000 SmallVector<CCValAssign, 16> RVLocs1;
2001 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2002 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2003 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2005 SmallVector<CCValAssign, 16> RVLocs2;
2006 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2007 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2008 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2010 if (RVLocs1.size() != RVLocs2.size())
2012 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2013 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2015 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2017 if (RVLocs1[i].isRegLoc()) {
2018 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2021 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2027 // If Caller's vararg or byval argument has been split between registers and
2028 // stack, do not perform tail call, since part of the argument is in caller's
2030 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2031 getInfo<ARMFunctionInfo>();
2032 if (AFI_Caller->getArgRegsSaveSize())
2035 // If the callee takes no arguments then go on to check the results of the
2037 if (!Outs.empty()) {
2038 // Check if stack adjustment is needed. For now, do not do this if any
2039 // argument is passed on the stack.
2040 SmallVector<CCValAssign, 16> ArgLocs;
2041 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2042 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2043 CCInfo.AnalyzeCallOperands(Outs,
2044 CCAssignFnForNode(CalleeCC, false, isVarArg));
2045 if (CCInfo.getNextStackOffset()) {
2046 MachineFunction &MF = DAG.getMachineFunction();
2048 // Check if the arguments are already laid out in the right way as
2049 // the caller's fixed stack objects.
2050 MachineFrameInfo *MFI = MF.getFrameInfo();
2051 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2052 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2053 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2055 ++i, ++realArgIdx) {
2056 CCValAssign &VA = ArgLocs[i];
2057 EVT RegVT = VA.getLocVT();
2058 SDValue Arg = OutVals[realArgIdx];
2059 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2060 if (VA.getLocInfo() == CCValAssign::Indirect)
2062 if (VA.needsCustom()) {
2063 // f64 and vector types are split into multiple registers or
2064 // register/stack-slot combinations. The types will not match
2065 // the registers; give up on memory f64 refs until we figure
2066 // out what to do about this.
2069 if (!ArgLocs[++i].isRegLoc())
2071 if (RegVT == MVT::v2f64) {
2072 if (!ArgLocs[++i].isRegLoc())
2074 if (!ArgLocs[++i].isRegLoc())
2077 } else if (!VA.isRegLoc()) {
2078 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2090 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2091 MachineFunction &MF, bool isVarArg,
2092 const SmallVectorImpl<ISD::OutputArg> &Outs,
2093 LLVMContext &Context) const {
2094 SmallVector<CCValAssign, 16> RVLocs;
2095 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2096 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2100 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2101 SDLoc DL, SelectionDAG &DAG) {
2102 const MachineFunction &MF = DAG.getMachineFunction();
2103 const Function *F = MF.getFunction();
2105 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2107 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2108 // version of the "preferred return address". These offsets affect the return
2109 // instruction if this is a return from PL1 without hypervisor extensions.
2110 // IRQ/FIQ: +4 "subs pc, lr, #4"
2111 // SWI: 0 "subs pc, lr, #0"
2112 // ABORT: +4 "subs pc, lr, #4"
2113 // UNDEF: +4/+2 "subs pc, lr, #0"
2114 // UNDEF varies depending on where the exception came from ARM or Thumb
2115 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2118 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2121 else if (IntKind == "SWI" || IntKind == "UNDEF")
2124 report_fatal_error("Unsupported interrupt attribute. If present, value "
2125 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2127 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2129 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2130 RetOps.data(), RetOps.size());
2134 ARMTargetLowering::LowerReturn(SDValue Chain,
2135 CallingConv::ID CallConv, bool isVarArg,
2136 const SmallVectorImpl<ISD::OutputArg> &Outs,
2137 const SmallVectorImpl<SDValue> &OutVals,
2138 SDLoc dl, SelectionDAG &DAG) const {
2140 // CCValAssign - represent the assignment of the return value to a location.
2141 SmallVector<CCValAssign, 16> RVLocs;
2143 // CCState - Info about the registers and stack slots.
2144 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2145 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2147 // Analyze outgoing return values.
2148 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2152 SmallVector<SDValue, 4> RetOps;
2153 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2155 // Copy the result values into the output registers.
2156 for (unsigned i = 0, realRVLocIdx = 0;
2158 ++i, ++realRVLocIdx) {
2159 CCValAssign &VA = RVLocs[i];
2160 assert(VA.isRegLoc() && "Can only return in registers!");
2162 SDValue Arg = OutVals[realRVLocIdx];
2164 switch (VA.getLocInfo()) {
2165 default: llvm_unreachable("Unknown loc info!");
2166 case CCValAssign::Full: break;
2167 case CCValAssign::BCvt:
2168 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2172 if (VA.needsCustom()) {
2173 if (VA.getLocVT() == MVT::v2f64) {
2174 // Extract the first half and return it in two registers.
2175 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2176 DAG.getConstant(0, MVT::i32));
2177 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2178 DAG.getVTList(MVT::i32, MVT::i32), Half);
2180 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2181 Flag = Chain.getValue(1);
2182 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2183 VA = RVLocs[++i]; // skip ahead to next loc
2184 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2185 HalfGPRs.getValue(1), Flag);
2186 Flag = Chain.getValue(1);
2187 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2188 VA = RVLocs[++i]; // skip ahead to next loc
2190 // Extract the 2nd half and fall through to handle it as an f64 value.
2191 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2192 DAG.getConstant(1, MVT::i32));
2194 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2196 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2197 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2198 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2199 Flag = Chain.getValue(1);
2200 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2201 VA = RVLocs[++i]; // skip ahead to next loc
2202 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2205 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2207 // Guarantee that all emitted copies are
2208 // stuck together, avoiding something bad.
2209 Flag = Chain.getValue(1);
2210 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2213 // Update chain and glue.
2216 RetOps.push_back(Flag);
2218 // CPUs which aren't M-class use a special sequence to return from
2219 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2220 // though we use "subs pc, lr, #N").
2222 // M-class CPUs actually use a normal return sequence with a special
2223 // (hardware-provided) value in LR, so the normal code path works.
2224 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2225 !Subtarget->isMClass()) {
2226 if (Subtarget->isThumb1Only())
2227 report_fatal_error("interrupt attribute is not supported in Thumb1");
2228 return LowerInterruptReturn(RetOps, dl, DAG);
2231 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2232 RetOps.data(), RetOps.size());
2235 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2236 if (N->getNumValues() != 1)
2238 if (!N->hasNUsesOfValue(1, 0))
2241 SDValue TCChain = Chain;
2242 SDNode *Copy = *N->use_begin();
2243 if (Copy->getOpcode() == ISD::CopyToReg) {
2244 // If the copy has a glue operand, we conservatively assume it isn't safe to
2245 // perform a tail call.
2246 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2248 TCChain = Copy->getOperand(0);
2249 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2250 SDNode *VMov = Copy;
2251 // f64 returned in a pair of GPRs.
2252 SmallPtrSet<SDNode*, 2> Copies;
2253 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2255 if (UI->getOpcode() != ISD::CopyToReg)
2259 if (Copies.size() > 2)
2262 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2264 SDValue UseChain = UI->getOperand(0);
2265 if (Copies.count(UseChain.getNode()))
2272 } else if (Copy->getOpcode() == ISD::BITCAST) {
2273 // f32 returned in a single GPR.
2274 if (!Copy->hasOneUse())
2276 Copy = *Copy->use_begin();
2277 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2279 TCChain = Copy->getOperand(0);
2284 bool HasRet = false;
2285 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2287 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2288 UI->getOpcode() != ARMISD::INTRET_FLAG)
2300 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2301 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2304 if (!CI->isTailCall())
2307 return !Subtarget->isThumb1Only();
2310 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2311 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2312 // one of the above mentioned nodes. It has to be wrapped because otherwise
2313 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2314 // be used to form addressing mode. These wrapped nodes will be selected
2316 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2317 EVT PtrVT = Op.getValueType();
2318 // FIXME there is no actual debug info here
2320 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2322 if (CP->isMachineConstantPoolEntry())
2323 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2324 CP->getAlignment());
2326 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2327 CP->getAlignment());
2328 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2331 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2332 return MachineJumpTableInfo::EK_Inline;
2335 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2336 SelectionDAG &DAG) const {
2337 MachineFunction &MF = DAG.getMachineFunction();
2338 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2339 unsigned ARMPCLabelIndex = 0;
2341 EVT PtrVT = getPointerTy();
2342 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2343 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2345 if (RelocM == Reloc::Static) {
2346 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2348 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2349 ARMPCLabelIndex = AFI->createPICLabelUId();
2350 ARMConstantPoolValue *CPV =
2351 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2352 ARMCP::CPBlockAddress, PCAdj);
2353 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2355 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2356 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2357 MachinePointerInfo::getConstantPool(),
2358 false, false, false, 0);
2359 if (RelocM == Reloc::Static)
2361 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2362 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2365 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2367 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2368 SelectionDAG &DAG) const {
2370 EVT PtrVT = getPointerTy();
2371 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2372 MachineFunction &MF = DAG.getMachineFunction();
2373 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2374 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2375 ARMConstantPoolValue *CPV =
2376 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2377 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2378 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2379 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2380 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2381 MachinePointerInfo::getConstantPool(),
2382 false, false, false, 0);
2383 SDValue Chain = Argument.getValue(1);
2385 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2386 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2388 // call __tls_get_addr.
2391 Entry.Node = Argument;
2392 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2393 Args.push_back(Entry);
2394 // FIXME: is there useful debug info available here?
2395 TargetLowering::CallLoweringInfo CLI(Chain,
2396 (Type *) Type::getInt32Ty(*DAG.getContext()),
2397 false, false, false, false,
2398 0, CallingConv::C, /*isTailCall=*/false,
2399 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2400 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2401 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2402 return CallResult.first;
2405 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2406 // "local exec" model.
2408 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2410 TLSModel::Model model) const {
2411 const GlobalValue *GV = GA->getGlobal();
2414 SDValue Chain = DAG.getEntryNode();
2415 EVT PtrVT = getPointerTy();
2416 // Get the Thread Pointer
2417 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2419 if (model == TLSModel::InitialExec) {
2420 MachineFunction &MF = DAG.getMachineFunction();
2421 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2422 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2423 // Initial exec model.
2424 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2425 ARMConstantPoolValue *CPV =
2426 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2427 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2429 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2430 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2431 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2432 MachinePointerInfo::getConstantPool(),
2433 false, false, false, 0);
2434 Chain = Offset.getValue(1);
2436 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2437 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2439 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2440 MachinePointerInfo::getConstantPool(),
2441 false, false, false, 0);
2444 assert(model == TLSModel::LocalExec);
2445 ARMConstantPoolValue *CPV =
2446 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2447 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2448 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2449 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2450 MachinePointerInfo::getConstantPool(),
2451 false, false, false, 0);
2454 // The address of the thread local variable is the add of the thread
2455 // pointer with the offset of the variable.
2456 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2460 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2461 // TODO: implement the "local dynamic" model
2462 assert(Subtarget->isTargetELF() &&
2463 "TLS not implemented for non-ELF targets");
2464 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2466 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2469 case TLSModel::GeneralDynamic:
2470 case TLSModel::LocalDynamic:
2471 return LowerToTLSGeneralDynamicModel(GA, DAG);
2472 case TLSModel::InitialExec:
2473 case TLSModel::LocalExec:
2474 return LowerToTLSExecModels(GA, DAG, model);
2476 llvm_unreachable("bogus TLS model");
2479 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2480 SelectionDAG &DAG) const {
2481 EVT PtrVT = getPointerTy();
2483 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2484 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2485 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2486 ARMConstantPoolValue *CPV =
2487 ARMConstantPoolConstant::Create(GV,
2488 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2489 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2490 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2491 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2493 MachinePointerInfo::getConstantPool(),
2494 false, false, false, 0);
2495 SDValue Chain = Result.getValue(1);
2496 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2497 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2499 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2500 MachinePointerInfo::getGOT(),
2501 false, false, false, 0);
2505 // If we have T2 ops, we can materialize the address directly via movt/movw
2506 // pair. This is always cheaper.
2507 if (Subtarget->useMovt()) {
2509 // FIXME: Once remat is capable of dealing with instructions with register
2510 // operands, expand this into two nodes.
2511 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2512 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2514 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2515 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2516 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2517 MachinePointerInfo::getConstantPool(),
2518 false, false, false, 0);
2522 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2523 SelectionDAG &DAG) const {
2524 EVT PtrVT = getPointerTy();
2526 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2527 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2529 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2530 // update ARMFastISel::ARMMaterializeGV.
2531 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2533 // FIXME: Once remat is capable of dealing with instructions with register
2534 // operands, expand this into two nodes.
2535 if (RelocM == Reloc::Static)
2536 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2537 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2539 unsigned Wrapper = (RelocM == Reloc::PIC_)
2540 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2541 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2542 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2543 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2544 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2545 MachinePointerInfo::getGOT(),
2546 false, false, false, 0);
2550 unsigned ARMPCLabelIndex = 0;
2552 if (RelocM == Reloc::Static) {
2553 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2555 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2556 ARMPCLabelIndex = AFI->createPICLabelUId();
2557 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2558 ARMConstantPoolValue *CPV =
2559 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2561 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2563 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2565 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2566 MachinePointerInfo::getConstantPool(),
2567 false, false, false, 0);
2568 SDValue Chain = Result.getValue(1);
2570 if (RelocM == Reloc::PIC_) {
2571 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2572 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2575 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2576 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2577 false, false, false, 0);
2582 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2583 SelectionDAG &DAG) const {
2584 assert(Subtarget->isTargetELF() &&
2585 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2586 MachineFunction &MF = DAG.getMachineFunction();
2587 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2588 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2589 EVT PtrVT = getPointerTy();
2591 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2592 ARMConstantPoolValue *CPV =
2593 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2594 ARMPCLabelIndex, PCAdj);
2595 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2596 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2597 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2598 MachinePointerInfo::getConstantPool(),
2599 false, false, false, 0);
2600 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2601 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2605 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2607 SDValue Val = DAG.getConstant(0, MVT::i32);
2608 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2609 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2610 Op.getOperand(1), Val);
2614 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2616 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2617 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2621 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2622 const ARMSubtarget *Subtarget) const {
2623 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2626 default: return SDValue(); // Don't custom lower most intrinsics.
2627 case Intrinsic::arm_thread_pointer: {
2628 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2629 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2631 case Intrinsic::eh_sjlj_lsda: {
2632 MachineFunction &MF = DAG.getMachineFunction();
2633 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2634 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2635 EVT PtrVT = getPointerTy();
2636 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2638 unsigned PCAdj = (RelocM != Reloc::PIC_)
2639 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2640 ARMConstantPoolValue *CPV =
2641 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2642 ARMCP::CPLSDA, PCAdj);
2643 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2644 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2646 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2647 MachinePointerInfo::getConstantPool(),
2648 false, false, false, 0);
2650 if (RelocM == Reloc::PIC_) {
2651 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2652 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2656 case Intrinsic::arm_neon_vmulls:
2657 case Intrinsic::arm_neon_vmullu: {
2658 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2659 ? ARMISD::VMULLs : ARMISD::VMULLu;
2660 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2661 Op.getOperand(1), Op.getOperand(2));
2666 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2667 const ARMSubtarget *Subtarget) {
2668 // FIXME: handle "fence singlethread" more efficiently.
2670 if (!Subtarget->hasDataBarrier()) {
2671 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2672 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2674 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2675 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2676 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2677 DAG.getConstant(0, MVT::i32));
2680 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2681 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2682 unsigned Domain = ARM_MB::ISH;
2683 if (Subtarget->isMClass()) {
2684 // Only a full system barrier exists in the M-class architectures.
2685 Domain = ARM_MB::SY;
2686 } else if (Subtarget->isSwift() && Ord == Release) {
2687 // Swift happens to implement ISHST barriers in a way that's compatible with
2688 // Release semantics but weaker than ISH so we'd be fools not to use
2689 // it. Beware: other processors probably don't!
2690 Domain = ARM_MB::ISHST;
2693 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2694 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2695 DAG.getConstant(Domain, MVT::i32));
2698 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2699 const ARMSubtarget *Subtarget) {
2700 // ARM pre v5TE and Thumb1 does not have preload instructions.
2701 if (!(Subtarget->isThumb2() ||
2702 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2703 // Just preserve the chain.
2704 return Op.getOperand(0);
2707 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2709 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2710 // ARMv7 with MP extension has PLDW.
2711 return Op.getOperand(0);
2713 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2714 if (Subtarget->isThumb()) {
2716 isRead = ~isRead & 1;
2717 isData = ~isData & 1;
2720 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2721 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2722 DAG.getConstant(isData, MVT::i32));
2725 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2726 MachineFunction &MF = DAG.getMachineFunction();
2727 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2729 // vastart just stores the address of the VarArgsFrameIndex slot into the
2730 // memory location argument.
2732 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2733 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2734 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2735 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2736 MachinePointerInfo(SV), false, false, 0);
2740 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2741 SDValue &Root, SelectionDAG &DAG,
2743 MachineFunction &MF = DAG.getMachineFunction();
2744 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2746 const TargetRegisterClass *RC;
2747 if (AFI->isThumb1OnlyFunction())
2748 RC = &ARM::tGPRRegClass;
2750 RC = &ARM::GPRRegClass;
2752 // Transform the arguments stored in physical registers into virtual ones.
2753 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2754 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2757 if (NextVA.isMemLoc()) {
2758 MachineFrameInfo *MFI = MF.getFrameInfo();
2759 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2761 // Create load node to retrieve arguments from the stack.
2762 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2763 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2764 MachinePointerInfo::getFixedStack(FI),
2765 false, false, false, 0);
2767 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2768 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2771 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2775 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2776 unsigned InRegsParamRecordIdx,
2778 unsigned &ArgRegsSize,
2779 unsigned &ArgRegsSaveSize)
2782 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2783 unsigned RBegin, REnd;
2784 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2785 NumGPRs = REnd - RBegin;
2787 unsigned int firstUnalloced;
2788 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2789 sizeof(GPRArgRegs) /
2790 sizeof(GPRArgRegs[0]));
2791 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2794 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2795 ArgRegsSize = NumGPRs * 4;
2797 // If parameter is split between stack and GPRs...
2798 if (NumGPRs && Align == 8 &&
2799 (ArgRegsSize < ArgSize ||
2800 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2801 // Add padding for part of param recovered from GPRs, so
2802 // its last byte must be at address K*8 - 1.
2803 // We need to do it, since remained (stack) part of parameter has
2804 // stack alignment, and we need to "attach" "GPRs head" without gaps
2807 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2808 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2810 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2812 ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2813 (ArgRegsSize + AFI->getArgRegsSaveSize());
2814 ArgRegsSaveSize = ArgRegsSize + Padding;
2816 // We don't need to extend regs save size for byval parameters if they
2817 // are passed via GPRs only.
2818 ArgRegsSaveSize = ArgRegsSize;
2821 // The remaining GPRs hold either the beginning of variable-argument
2822 // data, or the beginning of an aggregate passed by value (usually
2823 // byval). Either way, we allocate stack slots adjacent to the data
2824 // provided by our caller, and store the unallocated registers there.
2825 // If this is a variadic function, the va_list pointer will begin with
2826 // these values; otherwise, this reassembles a (byval) structure that
2827 // was split between registers and memory.
2828 // Return: The frame index registers were stored into.
2830 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2831 SDLoc dl, SDValue &Chain,
2832 const Value *OrigArg,
2833 unsigned InRegsParamRecordIdx,
2834 unsigned OffsetFromOrigArg,
2837 bool ForceMutable) const {
2839 // Currently, two use-cases possible:
2840 // Case #1. Non var-args function, and we meet first byval parameter.
2841 // Setup first unallocated register as first byval register;
2842 // eat all remained registers
2843 // (these two actions are performed by HandleByVal method).
2844 // Then, here, we initialize stack frame with
2845 // "store-reg" instructions.
2846 // Case #2. Var-args function, that doesn't contain byval parameters.
2847 // The same: eat all remained unallocated registers,
2848 // initialize stack frame.
2850 MachineFunction &MF = DAG.getMachineFunction();
2851 MachineFrameInfo *MFI = MF.getFrameInfo();
2852 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2853 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2854 unsigned RBegin, REnd;
2855 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2856 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2857 firstRegToSaveIndex = RBegin - ARM::R0;
2858 lastRegToSaveIndex = REnd - ARM::R0;
2860 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2861 (GPRArgRegs, array_lengthof(GPRArgRegs));
2862 lastRegToSaveIndex = 4;
2865 unsigned ArgRegsSize, ArgRegsSaveSize;
2866 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2867 ArgRegsSize, ArgRegsSaveSize);
2869 // Store any by-val regs to their spots on the stack so that they may be
2870 // loaded by deferencing the result of formal parameter pointer or va_next.
2871 // Note: once stack area for byval/varargs registers
2872 // was initialized, it can't be initialized again.
2873 if (ArgRegsSaveSize) {
2875 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2878 assert(AFI->getStoredByValParamsPadding() == 0 &&
2879 "The only parameter may be padded.");
2880 AFI->setStoredByValParamsPadding(Padding);
2883 int FrameIndex = MFI->CreateFixedObject(
2885 Padding + ArgOffset,
2887 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2889 SmallVector<SDValue, 4> MemOps;
2890 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2891 ++firstRegToSaveIndex, ++i) {
2892 const TargetRegisterClass *RC;
2893 if (AFI->isThumb1OnlyFunction())
2894 RC = &ARM::tGPRRegClass;
2896 RC = &ARM::GPRRegClass;
2898 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2899 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2901 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2902 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2904 MemOps.push_back(Store);
2905 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2906 DAG.getConstant(4, getPointerTy()));
2909 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2911 if (!MemOps.empty())
2912 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2913 &MemOps[0], MemOps.size());
2916 // This will point to the next argument passed via stack.
2917 return MFI->CreateFixedObject(
2918 4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2921 // Setup stack frame, the va_list pointer will start from.
2923 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2924 SDLoc dl, SDValue &Chain,
2926 bool ForceMutable) const {
2927 MachineFunction &MF = DAG.getMachineFunction();
2928 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2930 // Try to store any remaining integer argument regs
2931 // to their spots on the stack so that they may be loaded by deferencing
2932 // the result of va_next.
2933 // If there is no regs to be stored, just point address after last
2934 // argument passed via stack.
2936 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2937 0, ArgOffset, 0, ForceMutable);
2939 AFI->setVarArgsFrameIndex(FrameIndex);
2943 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2944 CallingConv::ID CallConv, bool isVarArg,
2945 const SmallVectorImpl<ISD::InputArg>
2947 SDLoc dl, SelectionDAG &DAG,
2948 SmallVectorImpl<SDValue> &InVals)
2950 MachineFunction &MF = DAG.getMachineFunction();
2951 MachineFrameInfo *MFI = MF.getFrameInfo();
2953 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2955 // Assign locations to all of the incoming arguments.
2956 SmallVector<CCValAssign, 16> ArgLocs;
2957 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2958 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2959 CCInfo.AnalyzeFormalArguments(Ins,
2960 CCAssignFnForNode(CallConv, /* Return*/ false,
2963 SmallVector<SDValue, 16> ArgValues;
2964 int lastInsIndex = -1;
2966 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2967 unsigned CurArgIdx = 0;
2969 // Initially ArgRegsSaveSize is zero.
2970 // Then we increase this value each time we meet byval parameter.
2971 // We also increase this value in case of varargs function.
2972 AFI->setArgRegsSaveSize(0);
2974 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2975 CCValAssign &VA = ArgLocs[i];
2976 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2977 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2978 // Arguments stored in registers.
2979 if (VA.isRegLoc()) {
2980 EVT RegVT = VA.getLocVT();
2982 if (VA.needsCustom()) {
2983 // f64 and vector types are split up into multiple registers or
2984 // combinations of registers and stack slots.
2985 if (VA.getLocVT() == MVT::v2f64) {
2986 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2988 VA = ArgLocs[++i]; // skip ahead to next loc
2990 if (VA.isMemLoc()) {
2991 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2992 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2993 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2994 MachinePointerInfo::getFixedStack(FI),
2995 false, false, false, 0);
2997 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3000 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3001 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3002 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3003 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3004 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3006 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3009 const TargetRegisterClass *RC;
3011 if (RegVT == MVT::f32)
3012 RC = &ARM::SPRRegClass;
3013 else if (RegVT == MVT::f64)
3014 RC = &ARM::DPRRegClass;
3015 else if (RegVT == MVT::v2f64)
3016 RC = &ARM::QPRRegClass;
3017 else if (RegVT == MVT::i32)
3018 RC = AFI->isThumb1OnlyFunction() ?
3019 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3020 (const TargetRegisterClass*)&ARM::GPRRegClass;
3022 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3024 // Transform the arguments in physical registers into virtual ones.
3025 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3026 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3029 // If this is an 8 or 16-bit value, it is really passed promoted
3030 // to 32 bits. Insert an assert[sz]ext to capture this, then
3031 // truncate to the right size.
3032 switch (VA.getLocInfo()) {
3033 default: llvm_unreachable("Unknown loc info!");
3034 case CCValAssign::Full: break;
3035 case CCValAssign::BCvt:
3036 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3038 case CCValAssign::SExt:
3039 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3040 DAG.getValueType(VA.getValVT()));
3041 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3043 case CCValAssign::ZExt:
3044 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3045 DAG.getValueType(VA.getValVT()));
3046 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3050 InVals.push_back(ArgValue);
3052 } else { // VA.isRegLoc()
3055 assert(VA.isMemLoc());
3056 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3058 int index = ArgLocs[i].getValNo();
3060 // Some Ins[] entries become multiple ArgLoc[] entries.
3061 // Process them only once.
3062 if (index != lastInsIndex)
3064 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3065 // FIXME: For now, all byval parameter objects are marked mutable.
3066 // This can be changed with more analysis.
3067 // In case of tail call optimization mark all arguments mutable.
3068 // Since they could be overwritten by lowering of arguments in case of
3070 if (Flags.isByVal()) {
3071 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3072 int FrameIndex = StoreByValRegs(
3073 CCInfo, DAG, dl, Chain, CurOrigArg,
3075 Ins[VA.getValNo()].PartOffset,
3076 VA.getLocMemOffset(),
3077 Flags.getByValSize(),
3078 true /*force mutable frames*/);
3079 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3080 CCInfo.nextInRegsParam();
3082 unsigned FIOffset = VA.getLocMemOffset() +
3083 AFI->getStoredByValParamsPadding();
3084 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3087 // Create load nodes to retrieve arguments from the stack.
3088 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3089 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3090 MachinePointerInfo::getFixedStack(FI),
3091 false, false, false, 0));
3093 lastInsIndex = index;
3100 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3101 CCInfo.getNextStackOffset());
3106 /// isFloatingPointZero - Return true if this is +0.0.
3107 static bool isFloatingPointZero(SDValue Op) {
3108 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3109 return CFP->getValueAPF().isPosZero();
3110 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3111 // Maybe this has already been legalized into the constant pool?
3112 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3113 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3114 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3115 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3116 return CFP->getValueAPF().isPosZero();
3122 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3123 /// the given operands.
3125 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3126 SDValue &ARMcc, SelectionDAG &DAG,
3128 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3129 unsigned C = RHSC->getZExtValue();
3130 if (!isLegalICmpImmediate(C)) {
3131 // Constant does not fit, try adjusting it by one?
3136 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3137 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3138 RHS = DAG.getConstant(C-1, MVT::i32);
3143 if (C != 0 && isLegalICmpImmediate(C-1)) {
3144 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3145 RHS = DAG.getConstant(C-1, MVT::i32);
3150 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3151 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3152 RHS = DAG.getConstant(C+1, MVT::i32);
3157 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3158 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3159 RHS = DAG.getConstant(C+1, MVT::i32);
3166 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3167 ARMISD::NodeType CompareType;
3170 CompareType = ARMISD::CMP;
3175 CompareType = ARMISD::CMPZ;
3178 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3179 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3182 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3184 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3187 if (!isFloatingPointZero(RHS))
3188 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3190 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3191 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3194 /// duplicateCmp - Glue values can have only one use, so this function
3195 /// duplicates a comparison node.
3197 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3198 unsigned Opc = Cmp.getOpcode();
3200 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3201 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3203 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3204 Cmp = Cmp.getOperand(0);
3205 Opc = Cmp.getOpcode();
3206 if (Opc == ARMISD::CMPFP)
3207 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3209 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3210 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3212 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3215 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3216 SDValue Cond = Op.getOperand(0);
3217 SDValue SelectTrue = Op.getOperand(1);
3218 SDValue SelectFalse = Op.getOperand(2);
3223 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3224 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3226 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3227 const ConstantSDNode *CMOVTrue =
3228 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3229 const ConstantSDNode *CMOVFalse =
3230 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3232 if (CMOVTrue && CMOVFalse) {
3233 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3234 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3238 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3240 False = SelectFalse;
3241 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3246 if (True.getNode() && False.getNode()) {
3247 EVT VT = Op.getValueType();
3248 SDValue ARMcc = Cond.getOperand(2);
3249 SDValue CCR = Cond.getOperand(3);
3250 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3251 assert(True.getValueType() == VT);
3252 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3257 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3258 // undefined bits before doing a full-word comparison with zero.
3259 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3260 DAG.getConstant(1, Cond.getValueType()));
3262 return DAG.getSelectCC(dl, Cond,
3263 DAG.getConstant(0, Cond.getValueType()),
3264 SelectTrue, SelectFalse, ISD::SETNE);
3267 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3268 if (CC == ISD::SETNE)
3270 return ISD::getSetCCSwappedOperands(CC);
3273 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3274 bool &swpCmpOps, bool &swpVselOps) {
3275 // Start by selecting the GE condition code for opcodes that return true for
3277 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3279 CondCode = ARMCC::GE;
3281 // and GT for opcodes that return false for 'equality'.
3282 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3284 CondCode = ARMCC::GT;
3286 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3287 // to swap the compare operands.
3288 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3292 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3293 // If we have an unordered opcode, we need to swap the operands to the VSEL
3294 // instruction (effectively negating the condition).
3296 // This also has the effect of swapping which one of 'less' or 'greater'
3297 // returns true, so we also swap the compare operands. It also switches
3298 // whether we return true for 'equality', so we compensate by picking the
3299 // opposite condition code to our original choice.
3300 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3301 CC == ISD::SETUGT) {
3302 swpCmpOps = !swpCmpOps;
3303 swpVselOps = !swpVselOps;
3304 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3307 // 'ordered' is 'anything but unordered', so use the VS condition code and
3308 // swap the VSEL operands.
3309 if (CC == ISD::SETO) {
3310 CondCode = ARMCC::VS;
3314 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3315 // code and swap the VSEL operands.
3316 if (CC == ISD::SETUNE) {
3317 CondCode = ARMCC::EQ;
3322 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3323 EVT VT = Op.getValueType();
3324 SDValue LHS = Op.getOperand(0);
3325 SDValue RHS = Op.getOperand(1);
3326 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3327 SDValue TrueVal = Op.getOperand(2);
3328 SDValue FalseVal = Op.getOperand(3);
3331 if (LHS.getValueType() == MVT::i32) {
3332 // Try to generate VSEL on ARMv8.
3333 // The VSEL instruction can't use all the usual ARM condition
3334 // codes: it only has two bits to select the condition code, so it's
3335 // constrained to use only GE, GT, VS and EQ.
3337 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3338 // swap the operands of the previous compare instruction (effectively
3339 // inverting the compare condition, swapping 'less' and 'greater') and
3340 // sometimes need to swap the operands to the VSEL (which inverts the
3341 // condition in the sense of firing whenever the previous condition didn't)
3342 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3343 TrueVal.getValueType() == MVT::f64)) {
3344 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3345 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3346 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3347 CC = getInverseCCForVSEL(CC);
3348 std::swap(TrueVal, FalseVal);
3353 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3354 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3355 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3359 ARMCC::CondCodes CondCode, CondCode2;
3360 FPCCToARMCC(CC, CondCode, CondCode2);
3362 // Try to generate VSEL on ARMv8.
3363 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3364 TrueVal.getValueType() == MVT::f64)) {
3365 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3366 // same operands, as follows:
3367 // c = fcmp [ogt, olt, ugt, ult] a, b
3369 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3370 // handled differently than the original code sequence.
3371 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3373 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3374 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3375 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3376 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3379 bool swpCmpOps = false;
3380 bool swpVselOps = false;
3381 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3383 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3384 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3386 std::swap(LHS, RHS);
3388 std::swap(TrueVal, FalseVal);
3392 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3393 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3394 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3395 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3397 if (CondCode2 != ARMCC::AL) {
3398 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3399 // FIXME: Needs another CMP because flag can have but one use.
3400 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3401 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3402 Result, TrueVal, ARMcc2, CCR, Cmp2);
3407 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3408 /// to morph to an integer compare sequence.
3409 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3410 const ARMSubtarget *Subtarget) {
3411 SDNode *N = Op.getNode();
3412 if (!N->hasOneUse())
3413 // Otherwise it requires moving the value from fp to integer registers.
3415 if (!N->getNumValues())
3417 EVT VT = Op.getValueType();
3418 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3419 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3420 // vmrs are very slow, e.g. cortex-a8.
3423 if (isFloatingPointZero(Op)) {
3427 return ISD::isNormalLoad(N);
3430 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3431 if (isFloatingPointZero(Op))
3432 return DAG.getConstant(0, MVT::i32);
3434 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3435 return DAG.getLoad(MVT::i32, SDLoc(Op),
3436 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3437 Ld->isVolatile(), Ld->isNonTemporal(),
3438 Ld->isInvariant(), Ld->getAlignment());
3440 llvm_unreachable("Unknown VFP cmp argument!");
3443 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3444 SDValue &RetVal1, SDValue &RetVal2) {
3445 if (isFloatingPointZero(Op)) {
3446 RetVal1 = DAG.getConstant(0, MVT::i32);
3447 RetVal2 = DAG.getConstant(0, MVT::i32);
3451 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3452 SDValue Ptr = Ld->getBasePtr();
3453 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3454 Ld->getChain(), Ptr,
3455 Ld->getPointerInfo(),
3456 Ld->isVolatile(), Ld->isNonTemporal(),
3457 Ld->isInvariant(), Ld->getAlignment());
3459 EVT PtrType = Ptr.getValueType();
3460 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3461 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3462 PtrType, Ptr, DAG.getConstant(4, PtrType));
3463 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3464 Ld->getChain(), NewPtr,
3465 Ld->getPointerInfo().getWithOffset(4),
3466 Ld->isVolatile(), Ld->isNonTemporal(),
3467 Ld->isInvariant(), NewAlign);
3471 llvm_unreachable("Unknown VFP cmp argument!");
3474 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3475 /// f32 and even f64 comparisons to integer ones.
3477 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3478 SDValue Chain = Op.getOperand(0);
3479 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3480 SDValue LHS = Op.getOperand(2);
3481 SDValue RHS = Op.getOperand(3);
3482 SDValue Dest = Op.getOperand(4);
3485 bool LHSSeenZero = false;
3486 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3487 bool RHSSeenZero = false;
3488 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3489 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3490 // If unsafe fp math optimization is enabled and there are no other uses of
3491 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3492 // to an integer comparison.
3493 if (CC == ISD::SETOEQ)
3495 else if (CC == ISD::SETUNE)
3498 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3500 if (LHS.getValueType() == MVT::f32) {
3501 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3502 bitcastf32Toi32(LHS, DAG), Mask);
3503 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3504 bitcastf32Toi32(RHS, DAG), Mask);
3505 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3506 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3507 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3508 Chain, Dest, ARMcc, CCR, Cmp);
3513 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3514 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3515 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3516 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3517 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3518 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3519 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3520 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3521 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3527 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3528 SDValue Chain = Op.getOperand(0);
3529 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3530 SDValue LHS = Op.getOperand(2);
3531 SDValue RHS = Op.getOperand(3);
3532 SDValue Dest = Op.getOperand(4);
3535 if (LHS.getValueType() == MVT::i32) {
3537 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3538 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3539 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3540 Chain, Dest, ARMcc, CCR, Cmp);
3543 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3545 if (getTargetMachine().Options.UnsafeFPMath &&
3546 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3547 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3548 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3549 if (Result.getNode())
3553 ARMCC::CondCodes CondCode, CondCode2;
3554 FPCCToARMCC(CC, CondCode, CondCode2);
3556 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3557 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3558 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3559 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3560 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3561 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3562 if (CondCode2 != ARMCC::AL) {
3563 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3564 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3565 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3570 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3571 SDValue Chain = Op.getOperand(0);
3572 SDValue Table = Op.getOperand(1);
3573 SDValue Index = Op.getOperand(2);
3576 EVT PTy = getPointerTy();
3577 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3578 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3579 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3580 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3581 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3582 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3583 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3584 if (Subtarget->isThumb2()) {
3585 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3586 // which does another jump to the destination. This also makes it easier
3587 // to translate it to TBB / TBH later.
3588 // FIXME: This might not work if the function is extremely large.
3589 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3590 Addr, Op.getOperand(2), JTI, UId);
3592 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3593 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3594 MachinePointerInfo::getJumpTable(),
3595 false, false, false, 0);
3596 Chain = Addr.getValue(1);
3597 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3598 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3600 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3601 MachinePointerInfo::getJumpTable(),
3602 false, false, false, 0);
3603 Chain = Addr.getValue(1);
3604 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3608 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3609 EVT VT = Op.getValueType();
3612 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3613 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3615 return DAG.UnrollVectorOp(Op.getNode());
3618 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3619 "Invalid type for custom lowering!");
3620 if (VT != MVT::v4i16)
3621 return DAG.UnrollVectorOp(Op.getNode());
3623 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3624 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3627 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3628 EVT VT = Op.getValueType();
3630 return LowerVectorFP_TO_INT(Op, DAG);
3635 switch (Op.getOpcode()) {
3636 default: llvm_unreachable("Invalid opcode!");
3637 case ISD::FP_TO_SINT:
3638 Opc = ARMISD::FTOSI;
3640 case ISD::FP_TO_UINT:
3641 Opc = ARMISD::FTOUI;
3644 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3645 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3648 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3649 EVT VT = Op.getValueType();
3652 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3653 if (VT.getVectorElementType() == MVT::f32)
3655 return DAG.UnrollVectorOp(Op.getNode());
3658 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3659 "Invalid type for custom lowering!");
3660 if (VT != MVT::v4f32)
3661 return DAG.UnrollVectorOp(Op.getNode());
3665 switch (Op.getOpcode()) {
3666 default: llvm_unreachable("Invalid opcode!");
3667 case ISD::SINT_TO_FP:
3668 CastOpc = ISD::SIGN_EXTEND;
3669 Opc = ISD::SINT_TO_FP;
3671 case ISD::UINT_TO_FP:
3672 CastOpc = ISD::ZERO_EXTEND;
3673 Opc = ISD::UINT_TO_FP;
3677 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3678 return DAG.getNode(Opc, dl, VT, Op);
3681 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3682 EVT VT = Op.getValueType();
3684 return LowerVectorINT_TO_FP(Op, DAG);
3689 switch (Op.getOpcode()) {
3690 default: llvm_unreachable("Invalid opcode!");
3691 case ISD::SINT_TO_FP:
3692 Opc = ARMISD::SITOF;
3694 case ISD::UINT_TO_FP:
3695 Opc = ARMISD::UITOF;
3699 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3700 return DAG.getNode(Opc, dl, VT, Op);
3703 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3704 // Implement fcopysign with a fabs and a conditional fneg.
3705 SDValue Tmp0 = Op.getOperand(0);
3706 SDValue Tmp1 = Op.getOperand(1);
3708 EVT VT = Op.getValueType();
3709 EVT SrcVT = Tmp1.getValueType();
3710 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3711 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3712 bool UseNEON = !InGPR && Subtarget->hasNEON();
3715 // Use VBSL to copy the sign bit.
3716 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3717 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3718 DAG.getTargetConstant(EncodedVal, MVT::i32));
3719 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3721 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3722 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3723 DAG.getConstant(32, MVT::i32));
3724 else /*if (VT == MVT::f32)*/
3725 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3726 if (SrcVT == MVT::f32) {
3727 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3729 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3730 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3731 DAG.getConstant(32, MVT::i32));
3732 } else if (VT == MVT::f32)
3733 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3734 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3735 DAG.getConstant(32, MVT::i32));
3736 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3737 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3739 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3741 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3742 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3743 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3745 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3746 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3747 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3748 if (VT == MVT::f32) {
3749 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3750 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3751 DAG.getConstant(0, MVT::i32));
3753 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3759 // Bitcast operand 1 to i32.
3760 if (SrcVT == MVT::f64)
3761 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3762 &Tmp1, 1).getValue(1);
3763 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3765 // Or in the signbit with integer operations.
3766 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3767 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3768 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3769 if (VT == MVT::f32) {
3770 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3771 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3772 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3773 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3776 // f64: Or the high part with signbit and then combine two parts.
3777 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3779 SDValue Lo = Tmp0.getValue(0);
3780 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3781 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3782 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3785 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3786 MachineFunction &MF = DAG.getMachineFunction();
3787 MachineFrameInfo *MFI = MF.getFrameInfo();
3788 MFI->setReturnAddressIsTaken(true);
3790 EVT VT = Op.getValueType();
3792 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3794 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3795 SDValue Offset = DAG.getConstant(4, MVT::i32);
3796 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3797 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3798 MachinePointerInfo(), false, false, false, 0);
3801 // Return LR, which contains the return address. Mark it an implicit live-in.
3802 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3803 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3806 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3807 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3808 MFI->setFrameAddressIsTaken(true);
3810 EVT VT = Op.getValueType();
3811 SDLoc dl(Op); // FIXME probably not meaningful
3812 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3813 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3814 ? ARM::R7 : ARM::R11;
3815 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3817 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3818 MachinePointerInfo(),
3819 false, false, false, 0);
3823 /// ExpandBITCAST - If the target supports VFP, this function is called to
3824 /// expand a bit convert where either the source or destination type is i64 to
3825 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3826 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3827 /// vectors), since the legalizer won't know what to do with that.
3828 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3829 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3831 SDValue Op = N->getOperand(0);
3833 // This function is only supposed to be called for i64 types, either as the
3834 // source or destination of the bit convert.
3835 EVT SrcVT = Op.getValueType();
3836 EVT DstVT = N->getValueType(0);
3837 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3838 "ExpandBITCAST called for non-i64 type");
3840 // Turn i64->f64 into VMOVDRR.
3841 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3842 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3843 DAG.getConstant(0, MVT::i32));
3844 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3845 DAG.getConstant(1, MVT::i32));
3846 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3847 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3850 // Turn f64->i64 into VMOVRRD.
3851 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3852 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3853 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3854 // Merge the pieces into a single i64 value.
3855 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3861 /// getZeroVector - Returns a vector of specified type with all zero elements.
3862 /// Zero vectors are used to represent vector negation and in those cases
3863 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3864 /// not support i64 elements, so sometimes the zero vectors will need to be
3865 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3867 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3868 assert(VT.isVector() && "Expected a vector type");
3869 // The canonical modified immediate encoding of a zero vector is....0!
3870 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3871 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3872 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3873 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3876 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3877 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3878 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3879 SelectionDAG &DAG) const {
3880 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3881 EVT VT = Op.getValueType();
3882 unsigned VTBits = VT.getSizeInBits();
3884 SDValue ShOpLo = Op.getOperand(0);
3885 SDValue ShOpHi = Op.getOperand(1);
3886 SDValue ShAmt = Op.getOperand(2);
3888 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3890 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3892 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3893 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3894 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3895 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3896 DAG.getConstant(VTBits, MVT::i32));
3897 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3898 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3899 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3901 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3902 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3904 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3905 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3908 SDValue Ops[2] = { Lo, Hi };
3909 return DAG.getMergeValues(Ops, 2, dl);
3912 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3913 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3914 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3915 SelectionDAG &DAG) const {
3916 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3917 EVT VT = Op.getValueType();
3918 unsigned VTBits = VT.getSizeInBits();
3920 SDValue ShOpLo = Op.getOperand(0);
3921 SDValue ShOpHi = Op.getOperand(1);
3922 SDValue ShAmt = Op.getOperand(2);
3925 assert(Op.getOpcode() == ISD::SHL_PARTS);
3926 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3927 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3928 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3929 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3930 DAG.getConstant(VTBits, MVT::i32));
3931 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3932 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3934 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3935 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3936 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3938 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3939 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3942 SDValue Ops[2] = { Lo, Hi };
3943 return DAG.getMergeValues(Ops, 2, dl);
3946 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3947 SelectionDAG &DAG) const {
3948 // The rounding mode is in bits 23:22 of the FPSCR.
3949 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3950 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3951 // so that the shift + and get folded into a bitfield extract.
3953 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3954 DAG.getConstant(Intrinsic::arm_get_fpscr,
3956 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3957 DAG.getConstant(1U << 22, MVT::i32));
3958 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3959 DAG.getConstant(22, MVT::i32));
3960 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3961 DAG.getConstant(3, MVT::i32));
3964 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3965 const ARMSubtarget *ST) {
3966 EVT VT = N->getValueType(0);
3969 if (!ST->hasV6T2Ops())
3972 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3973 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3976 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3977 /// for each 16-bit element from operand, repeated. The basic idea is to
3978 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3980 /// Trace for v4i16:
3981 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3982 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3983 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3984 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3985 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3986 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3987 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3988 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3989 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3990 EVT VT = N->getValueType(0);
3993 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3994 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3995 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3996 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3997 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3998 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4001 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4002 /// bit-count for each 16-bit element from the operand. We need slightly
4003 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4004 /// 64/128-bit registers.
4006 /// Trace for v4i16:
4007 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4008 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4009 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4010 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4011 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4012 EVT VT = N->getValueType(0);
4015 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4016 if (VT.is64BitVector()) {
4017 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4018 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4019 DAG.getIntPtrConstant(0));
4021 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4022 BitCounts, DAG.getIntPtrConstant(0));
4023 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4027 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4028 /// bit-count for each 32-bit element from the operand. The idea here is
4029 /// to split the vector into 16-bit elements, leverage the 16-bit count
4030 /// routine, and then combine the results.
4032 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4033 /// input = [v0 v1 ] (vi: 32-bit elements)
4034 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4035 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4036 /// vrev: N0 = [k1 k0 k3 k2 ]
4038 /// N1 =+[k1 k0 k3 k2 ]
4040 /// N2 =+[k1 k3 k0 k2 ]
4042 /// Extended =+[k1 k3 k0 k2 ]
4044 /// Extracted=+[k1 k3 ]
4046 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4047 EVT VT = N->getValueType(0);
4050 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4052 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4053 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4054 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4055 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4056 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4058 if (VT.is64BitVector()) {
4059 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4060 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4061 DAG.getIntPtrConstant(0));
4063 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4064 DAG.getIntPtrConstant(0));
4065 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4069 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4070 const ARMSubtarget *ST) {
4071 EVT VT = N->getValueType(0);
4073 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4074 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4075 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4076 "Unexpected type for custom ctpop lowering");
4078 if (VT.getVectorElementType() == MVT::i32)
4079 return lowerCTPOP32BitElements(N, DAG);
4081 return lowerCTPOP16BitElements(N, DAG);
4084 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4085 const ARMSubtarget *ST) {
4086 EVT VT = N->getValueType(0);
4092 // Lower vector shifts on NEON to use VSHL.
4093 assert(ST->hasNEON() && "unexpected vector shift");
4095 // Left shifts translate directly to the vshiftu intrinsic.
4096 if (N->getOpcode() == ISD::SHL)
4097 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4098 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4099 N->getOperand(0), N->getOperand(1));
4101 assert((N->getOpcode() == ISD::SRA ||
4102 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4104 // NEON uses the same intrinsics for both left and right shifts. For
4105 // right shifts, the shift amounts are negative, so negate the vector of
4107 EVT ShiftVT = N->getOperand(1).getValueType();
4108 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4109 getZeroVector(ShiftVT, DAG, dl),
4111 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4112 Intrinsic::arm_neon_vshifts :
4113 Intrinsic::arm_neon_vshiftu);
4114 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4115 DAG.getConstant(vshiftInt, MVT::i32),
4116 N->getOperand(0), NegatedCount);
4119 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4120 const ARMSubtarget *ST) {
4121 EVT VT = N->getValueType(0);
4124 // We can get here for a node like i32 = ISD::SHL i32, i64
4128 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4129 "Unknown shift to lower!");
4131 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4132 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4133 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4136 // If we are in thumb mode, we don't have RRX.
4137 if (ST->isThumb1Only()) return SDValue();
4139 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4140 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4141 DAG.getConstant(0, MVT::i32));
4142 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4143 DAG.getConstant(1, MVT::i32));
4145 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4146 // captures the result into a carry flag.
4147 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4148 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4150 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4151 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4153 // Merge the pieces into a single i64 value.
4154 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4157 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4158 SDValue TmpOp0, TmpOp1;
4159 bool Invert = false;
4163 SDValue Op0 = Op.getOperand(0);
4164 SDValue Op1 = Op.getOperand(1);
4165 SDValue CC = Op.getOperand(2);
4166 EVT VT = Op.getValueType();
4167 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4170 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4171 switch (SetCCOpcode) {
4172 default: llvm_unreachable("Illegal FP comparison");
4174 case ISD::SETNE: Invert = true; // Fallthrough
4176 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4178 case ISD::SETLT: Swap = true; // Fallthrough
4180 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4182 case ISD::SETLE: Swap = true; // Fallthrough
4184 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4185 case ISD::SETUGE: Swap = true; // Fallthrough
4186 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4187 case ISD::SETUGT: Swap = true; // Fallthrough
4188 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4189 case ISD::SETUEQ: Invert = true; // Fallthrough
4191 // Expand this to (OLT | OGT).
4195 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4196 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4198 case ISD::SETUO: Invert = true; // Fallthrough
4200 // Expand this to (OLT | OGE).
4204 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4205 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4209 // Integer comparisons.
4210 switch (SetCCOpcode) {
4211 default: llvm_unreachable("Illegal integer comparison");
4212 case ISD::SETNE: Invert = true;
4213 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4214 case ISD::SETLT: Swap = true;
4215 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4216 case ISD::SETLE: Swap = true;
4217 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4218 case ISD::SETULT: Swap = true;
4219 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4220 case ISD::SETULE: Swap = true;
4221 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4224 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4225 if (Opc == ARMISD::VCEQ) {
4228 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4230 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4233 // Ignore bitconvert.
4234 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4235 AndOp = AndOp.getOperand(0);
4237 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4239 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4240 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4247 std::swap(Op0, Op1);
4249 // If one of the operands is a constant vector zero, attempt to fold the
4250 // comparison to a specialized compare-against-zero form.
4252 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4254 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4255 if (Opc == ARMISD::VCGE)
4256 Opc = ARMISD::VCLEZ;
4257 else if (Opc == ARMISD::VCGT)
4258 Opc = ARMISD::VCLTZ;
4263 if (SingleOp.getNode()) {
4266 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4268 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4270 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4272 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4274 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4276 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4279 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4283 Result = DAG.getNOT(dl, Result, VT);
4288 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4289 /// valid vector constant for a NEON instruction with a "modified immediate"
4290 /// operand (e.g., VMOV). If so, return the encoded value.
4291 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4292 unsigned SplatBitSize, SelectionDAG &DAG,
4293 EVT &VT, bool is128Bits, NEONModImmType type) {
4294 unsigned OpCmode, Imm;
4296 // SplatBitSize is set to the smallest size that splats the vector, so a
4297 // zero vector will always have SplatBitSize == 8. However, NEON modified
4298 // immediate instructions others than VMOV do not support the 8-bit encoding
4299 // of a zero vector, and the default encoding of zero is supposed to be the
4304 switch (SplatBitSize) {
4306 if (type != VMOVModImm)
4308 // Any 1-byte value is OK. Op=0, Cmode=1110.
4309 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4312 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4316 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4317 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4318 if ((SplatBits & ~0xff) == 0) {
4319 // Value = 0x00nn: Op=x, Cmode=100x.
4324 if ((SplatBits & ~0xff00) == 0) {
4325 // Value = 0xnn00: Op=x, Cmode=101x.
4327 Imm = SplatBits >> 8;
4333 // NEON's 32-bit VMOV supports splat values where:
4334 // * only one byte is nonzero, or
4335 // * the least significant byte is 0xff and the second byte is nonzero, or
4336 // * the least significant 2 bytes are 0xff and the third is nonzero.
4337 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4338 if ((SplatBits & ~0xff) == 0) {
4339 // Value = 0x000000nn: Op=x, Cmode=000x.
4344 if ((SplatBits & ~0xff00) == 0) {
4345 // Value = 0x0000nn00: Op=x, Cmode=001x.
4347 Imm = SplatBits >> 8;
4350 if ((SplatBits & ~0xff0000) == 0) {
4351 // Value = 0x00nn0000: Op=x, Cmode=010x.
4353 Imm = SplatBits >> 16;
4356 if ((SplatBits & ~0xff000000) == 0) {
4357 // Value = 0xnn000000: Op=x, Cmode=011x.
4359 Imm = SplatBits >> 24;
4363 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4364 if (type == OtherModImm) return SDValue();
4366 if ((SplatBits & ~0xffff) == 0 &&
4367 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4368 // Value = 0x0000nnff: Op=x, Cmode=1100.
4370 Imm = SplatBits >> 8;
4375 if ((SplatBits & ~0xffffff) == 0 &&
4376 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4377 // Value = 0x00nnffff: Op=x, Cmode=1101.
4379 Imm = SplatBits >> 16;
4380 SplatBits |= 0xffff;
4384 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4385 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4386 // VMOV.I32. A (very) minor optimization would be to replicate the value
4387 // and fall through here to test for a valid 64-bit splat. But, then the
4388 // caller would also need to check and handle the change in size.
4392 if (type != VMOVModImm)
4394 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4395 uint64_t BitMask = 0xff;
4397 unsigned ImmMask = 1;
4399 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4400 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4403 } else if ((SplatBits & BitMask) != 0) {
4409 // Op=1, Cmode=1110.
4412 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4417 llvm_unreachable("unexpected size for isNEONModifiedImm");
4420 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4421 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4424 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4425 const ARMSubtarget *ST) const {
4429 bool IsDouble = Op.getValueType() == MVT::f64;
4430 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4432 // Try splatting with a VMOV.f32...
4433 APFloat FPVal = CFP->getValueAPF();
4434 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4437 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4438 // We have code in place to select a valid ConstantFP already, no need to
4443 // It's a float and we are trying to use NEON operations where
4444 // possible. Lower it to a splat followed by an extract.
4446 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4447 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4449 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4450 DAG.getConstant(0, MVT::i32));
4453 // The rest of our options are NEON only, make sure that's allowed before
4455 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4459 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4461 // It wouldn't really be worth bothering for doubles except for one very
4462 // important value, which does happen to match: 0.0. So make sure we don't do
4464 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4467 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4468 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4470 if (NewVal != SDValue()) {
4472 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4475 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4477 // It's a float: cast and extract a vector element.
4478 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4480 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4481 DAG.getConstant(0, MVT::i32));
4484 // Finally, try a VMVN.i32
4485 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4487 if (NewVal != SDValue()) {
4489 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4492 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4494 // It's a float: cast and extract a vector element.
4495 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4497 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4498 DAG.getConstant(0, MVT::i32));
4504 // check if an VEXT instruction can handle the shuffle mask when the
4505 // vector sources of the shuffle are the same.
4506 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4507 unsigned NumElts = VT.getVectorNumElements();
4509 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4515 // If this is a VEXT shuffle, the immediate value is the index of the first
4516 // element. The other shuffle indices must be the successive elements after
4518 unsigned ExpectedElt = Imm;
4519 for (unsigned i = 1; i < NumElts; ++i) {
4520 // Increment the expected index. If it wraps around, just follow it
4521 // back to index zero and keep going.
4523 if (ExpectedElt == NumElts)
4526 if (M[i] < 0) continue; // ignore UNDEF indices
4527 if (ExpectedElt != static_cast<unsigned>(M[i]))
4535 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4536 bool &ReverseVEXT, unsigned &Imm) {
4537 unsigned NumElts = VT.getVectorNumElements();
4538 ReverseVEXT = false;
4540 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4546 // If this is a VEXT shuffle, the immediate value is the index of the first
4547 // element. The other shuffle indices must be the successive elements after
4549 unsigned ExpectedElt = Imm;
4550 for (unsigned i = 1; i < NumElts; ++i) {
4551 // Increment the expected index. If it wraps around, it may still be
4552 // a VEXT but the source vectors must be swapped.
4554 if (ExpectedElt == NumElts * 2) {
4559 if (M[i] < 0) continue; // ignore UNDEF indices
4560 if (ExpectedElt != static_cast<unsigned>(M[i]))
4564 // Adjust the index value if the source operands will be swapped.
4571 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4572 /// instruction with the specified blocksize. (The order of the elements
4573 /// within each block of the vector is reversed.)
4574 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4575 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4576 "Only possible block sizes for VREV are: 16, 32, 64");
4578 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4582 unsigned NumElts = VT.getVectorNumElements();
4583 unsigned BlockElts = M[0] + 1;
4584 // If the first shuffle index is UNDEF, be optimistic.
4586 BlockElts = BlockSize / EltSz;
4588 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4591 for (unsigned i = 0; i < NumElts; ++i) {
4592 if (M[i] < 0) continue; // ignore UNDEF indices
4593 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4600 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4601 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4602 // range, then 0 is placed into the resulting vector. So pretty much any mask
4603 // of 8 elements can work here.
4604 return VT == MVT::v8i8 && M.size() == 8;
4607 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4608 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4612 unsigned NumElts = VT.getVectorNumElements();
4613 WhichResult = (M[0] == 0 ? 0 : 1);
4614 for (unsigned i = 0; i < NumElts; i += 2) {
4615 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4616 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4622 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4623 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4624 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4625 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4626 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4630 unsigned NumElts = VT.getVectorNumElements();
4631 WhichResult = (M[0] == 0 ? 0 : 1);
4632 for (unsigned i = 0; i < NumElts; i += 2) {
4633 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4634 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4640 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4641 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4645 unsigned NumElts = VT.getVectorNumElements();
4646 WhichResult = (M[0] == 0 ? 0 : 1);
4647 for (unsigned i = 0; i != NumElts; ++i) {
4648 if (M[i] < 0) continue; // ignore UNDEF indices
4649 if ((unsigned) M[i] != 2 * i + WhichResult)
4653 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4654 if (VT.is64BitVector() && EltSz == 32)
4660 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4661 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4662 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4663 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4664 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4668 unsigned Half = VT.getVectorNumElements() / 2;
4669 WhichResult = (M[0] == 0 ? 0 : 1);
4670 for (unsigned j = 0; j != 2; ++j) {
4671 unsigned Idx = WhichResult;
4672 for (unsigned i = 0; i != Half; ++i) {
4673 int MIdx = M[i + j * Half];
4674 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4680 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4681 if (VT.is64BitVector() && EltSz == 32)
4687 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4688 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4692 unsigned NumElts = VT.getVectorNumElements();
4693 WhichResult = (M[0] == 0 ? 0 : 1);
4694 unsigned Idx = WhichResult * NumElts / 2;
4695 for (unsigned i = 0; i != NumElts; i += 2) {
4696 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4697 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4702 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4703 if (VT.is64BitVector() && EltSz == 32)
4709 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4710 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4711 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4712 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4713 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4717 unsigned NumElts = VT.getVectorNumElements();
4718 WhichResult = (M[0] == 0 ? 0 : 1);
4719 unsigned Idx = WhichResult * NumElts / 2;
4720 for (unsigned i = 0; i != NumElts; i += 2) {
4721 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4722 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4727 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4728 if (VT.is64BitVector() && EltSz == 32)
4734 /// \return true if this is a reverse operation on an vector.
4735 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4736 unsigned NumElts = VT.getVectorNumElements();
4737 // Make sure the mask has the right size.
4738 if (NumElts != M.size())
4741 // Look for <15, ..., 3, -1, 1, 0>.
4742 for (unsigned i = 0; i != NumElts; ++i)
4743 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4749 // If N is an integer constant that can be moved into a register in one
4750 // instruction, return an SDValue of such a constant (will become a MOV
4751 // instruction). Otherwise return null.
4752 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4753 const ARMSubtarget *ST, SDLoc dl) {
4755 if (!isa<ConstantSDNode>(N))
4757 Val = cast<ConstantSDNode>(N)->getZExtValue();
4759 if (ST->isThumb1Only()) {
4760 if (Val <= 255 || ~Val <= 255)
4761 return DAG.getConstant(Val, MVT::i32);
4763 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4764 return DAG.getConstant(Val, MVT::i32);
4769 // If this is a case we can't handle, return null and let the default
4770 // expansion code take care of it.
4771 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4772 const ARMSubtarget *ST) const {
4773 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4775 EVT VT = Op.getValueType();
4777 APInt SplatBits, SplatUndef;
4778 unsigned SplatBitSize;
4780 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4781 if (SplatBitSize <= 64) {
4782 // Check if an immediate VMOV works.
4784 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4785 SplatUndef.getZExtValue(), SplatBitSize,
4786 DAG, VmovVT, VT.is128BitVector(),
4788 if (Val.getNode()) {
4789 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4790 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4793 // Try an immediate VMVN.
4794 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4795 Val = isNEONModifiedImm(NegatedImm,
4796 SplatUndef.getZExtValue(), SplatBitSize,
4797 DAG, VmovVT, VT.is128BitVector(),
4799 if (Val.getNode()) {
4800 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4801 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4804 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4805 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4806 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4808 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4809 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4815 // Scan through the operands to see if only one value is used.
4817 // As an optimisation, even if more than one value is used it may be more
4818 // profitable to splat with one value then change some lanes.
4820 // Heuristically we decide to do this if the vector has a "dominant" value,
4821 // defined as splatted to more than half of the lanes.
4822 unsigned NumElts = VT.getVectorNumElements();
4823 bool isOnlyLowElement = true;
4824 bool usesOnlyOneValue = true;
4825 bool hasDominantValue = false;
4826 bool isConstant = true;
4828 // Map of the number of times a particular SDValue appears in the
4830 DenseMap<SDValue, unsigned> ValueCounts;
4832 for (unsigned i = 0; i < NumElts; ++i) {
4833 SDValue V = Op.getOperand(i);
4834 if (V.getOpcode() == ISD::UNDEF)
4837 isOnlyLowElement = false;
4838 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4841 ValueCounts.insert(std::make_pair(V, 0));
4842 unsigned &Count = ValueCounts[V];
4844 // Is this value dominant? (takes up more than half of the lanes)
4845 if (++Count > (NumElts / 2)) {
4846 hasDominantValue = true;
4850 if (ValueCounts.size() != 1)
4851 usesOnlyOneValue = false;
4852 if (!Value.getNode() && ValueCounts.size() > 0)
4853 Value = ValueCounts.begin()->first;
4855 if (ValueCounts.size() == 0)
4856 return DAG.getUNDEF(VT);
4858 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4859 // Keep going if we are hitting this case.
4860 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4861 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4863 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4865 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4866 // i32 and try again.
4867 if (hasDominantValue && EltSize <= 32) {
4871 // If we are VDUPing a value that comes directly from a vector, that will
4872 // cause an unnecessary move to and from a GPR, where instead we could
4873 // just use VDUPLANE. We can only do this if the lane being extracted
4874 // is at a constant index, as the VDUP from lane instructions only have
4875 // constant-index forms.
4876 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4877 isa<ConstantSDNode>(Value->getOperand(1))) {
4878 // We need to create a new undef vector to use for the VDUPLANE if the
4879 // size of the vector from which we get the value is different than the
4880 // size of the vector that we need to create. We will insert the element
4881 // such that the register coalescer will remove unnecessary copies.
4882 if (VT != Value->getOperand(0).getValueType()) {
4883 ConstantSDNode *constIndex;
4884 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4885 assert(constIndex && "The index is not a constant!");
4886 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4887 VT.getVectorNumElements();
4888 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4889 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4890 Value, DAG.getConstant(index, MVT::i32)),
4891 DAG.getConstant(index, MVT::i32));
4893 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4894 Value->getOperand(0), Value->getOperand(1));
4896 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4898 if (!usesOnlyOneValue) {
4899 // The dominant value was splatted as 'N', but we now have to insert
4900 // all differing elements.
4901 for (unsigned I = 0; I < NumElts; ++I) {
4902 if (Op.getOperand(I) == Value)
4904 SmallVector<SDValue, 3> Ops;
4906 Ops.push_back(Op.getOperand(I));
4907 Ops.push_back(DAG.getConstant(I, MVT::i32));
4908 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4913 if (VT.getVectorElementType().isFloatingPoint()) {
4914 SmallVector<SDValue, 8> Ops;
4915 for (unsigned i = 0; i < NumElts; ++i)
4916 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4918 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4919 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4920 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4922 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4924 if (usesOnlyOneValue) {
4925 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4926 if (isConstant && Val.getNode())
4927 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4931 // If all elements are constants and the case above didn't get hit, fall back
4932 // to the default expansion, which will generate a load from the constant
4937 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4939 SDValue shuffle = ReconstructShuffle(Op, DAG);
4940 if (shuffle != SDValue())
4944 // Vectors with 32- or 64-bit elements can be built by directly assigning
4945 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4946 // will be legalized.
4947 if (EltSize >= 32) {
4948 // Do the expansion with floating-point types, since that is what the VFP
4949 // registers are defined to use, and since i64 is not legal.
4950 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4951 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4952 SmallVector<SDValue, 8> Ops;
4953 for (unsigned i = 0; i < NumElts; ++i)
4954 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4955 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4956 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4959 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4960 // know the default expansion would otherwise fall back on something even
4961 // worse. For a vector with one or two non-undef values, that's
4962 // scalar_to_vector for the elements followed by a shuffle (provided the
4963 // shuffle is valid for the target) and materialization element by element
4964 // on the stack followed by a load for everything else.
4965 if (!isConstant && !usesOnlyOneValue) {
4966 SDValue Vec = DAG.getUNDEF(VT);
4967 for (unsigned i = 0 ; i < NumElts; ++i) {
4968 SDValue V = Op.getOperand(i);
4969 if (V.getOpcode() == ISD::UNDEF)
4971 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4972 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4980 // Gather data to see if the operation can be modelled as a
4981 // shuffle in combination with VEXTs.
4982 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4983 SelectionDAG &DAG) const {
4985 EVT VT = Op.getValueType();
4986 unsigned NumElts = VT.getVectorNumElements();
4988 SmallVector<SDValue, 2> SourceVecs;
4989 SmallVector<unsigned, 2> MinElts;
4990 SmallVector<unsigned, 2> MaxElts;
4992 for (unsigned i = 0; i < NumElts; ++i) {
4993 SDValue V = Op.getOperand(i);
4994 if (V.getOpcode() == ISD::UNDEF)
4996 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4997 // A shuffle can only come from building a vector from various
4998 // elements of other vectors.
5000 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5001 VT.getVectorElementType()) {
5002 // This code doesn't know how to handle shuffles where the vector
5003 // element types do not match (this happens because type legalization
5004 // promotes the return type of EXTRACT_VECTOR_ELT).
5005 // FIXME: It might be appropriate to extend this code to handle
5006 // mismatched types.
5010 // Record this extraction against the appropriate vector if possible...
5011 SDValue SourceVec = V.getOperand(0);
5012 // If the element number isn't a constant, we can't effectively
5013 // analyze what's going on.
5014 if (!isa<ConstantSDNode>(V.getOperand(1)))
5016 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5017 bool FoundSource = false;
5018 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5019 if (SourceVecs[j] == SourceVec) {
5020 if (MinElts[j] > EltNo)
5022 if (MaxElts[j] < EltNo)
5029 // Or record a new source if not...
5031 SourceVecs.push_back(SourceVec);
5032 MinElts.push_back(EltNo);
5033 MaxElts.push_back(EltNo);
5037 // Currently only do something sane when at most two source vectors
5039 if (SourceVecs.size() > 2)
5042 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5043 int VEXTOffsets[2] = {0, 0};
5045 // This loop extracts the usage patterns of the source vectors
5046 // and prepares appropriate SDValues for a shuffle if possible.
5047 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5048 if (SourceVecs[i].getValueType() == VT) {
5049 // No VEXT necessary
5050 ShuffleSrcs[i] = SourceVecs[i];
5053 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5054 // It probably isn't worth padding out a smaller vector just to
5055 // break it down again in a shuffle.
5059 // Since only 64-bit and 128-bit vectors are legal on ARM and
5060 // we've eliminated the other cases...
5061 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5062 "unexpected vector sizes in ReconstructShuffle");
5064 if (MaxElts[i] - MinElts[i] >= NumElts) {
5065 // Span too large for a VEXT to cope
5069 if (MinElts[i] >= NumElts) {
5070 // The extraction can just take the second half
5071 VEXTOffsets[i] = NumElts;
5072 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5074 DAG.getIntPtrConstant(NumElts));
5075 } else if (MaxElts[i] < NumElts) {
5076 // The extraction can just take the first half
5078 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5080 DAG.getIntPtrConstant(0));
5082 // An actual VEXT is needed
5083 VEXTOffsets[i] = MinElts[i];
5084 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5086 DAG.getIntPtrConstant(0));
5087 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5089 DAG.getIntPtrConstant(NumElts));
5090 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5091 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5095 SmallVector<int, 8> Mask;
5097 for (unsigned i = 0; i < NumElts; ++i) {
5098 SDValue Entry = Op.getOperand(i);
5099 if (Entry.getOpcode() == ISD::UNDEF) {
5104 SDValue ExtractVec = Entry.getOperand(0);
5105 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5106 .getOperand(1))->getSExtValue();
5107 if (ExtractVec == SourceVecs[0]) {
5108 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5110 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5114 // Final check before we try to produce nonsense...
5115 if (isShuffleMaskLegal(Mask, VT))
5116 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5122 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5123 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5124 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5125 /// are assumed to be legal.
5127 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5129 if (VT.getVectorNumElements() == 4 &&
5130 (VT.is128BitVector() || VT.is64BitVector())) {
5131 unsigned PFIndexes[4];
5132 for (unsigned i = 0; i != 4; ++i) {
5136 PFIndexes[i] = M[i];
5139 // Compute the index in the perfect shuffle table.
5140 unsigned PFTableIndex =
5141 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5142 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5143 unsigned Cost = (PFEntry >> 30);
5150 unsigned Imm, WhichResult;
5152 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5153 return (EltSize >= 32 ||
5154 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5155 isVREVMask(M, VT, 64) ||
5156 isVREVMask(M, VT, 32) ||
5157 isVREVMask(M, VT, 16) ||
5158 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5159 isVTBLMask(M, VT) ||
5160 isVTRNMask(M, VT, WhichResult) ||
5161 isVUZPMask(M, VT, WhichResult) ||
5162 isVZIPMask(M, VT, WhichResult) ||
5163 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5164 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5165 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5166 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5169 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5170 /// the specified operations to build the shuffle.
5171 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5172 SDValue RHS, SelectionDAG &DAG,
5174 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5175 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5176 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5179 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5188 OP_VUZPL, // VUZP, left result
5189 OP_VUZPR, // VUZP, right result
5190 OP_VZIPL, // VZIP, left result
5191 OP_VZIPR, // VZIP, right result
5192 OP_VTRNL, // VTRN, left result
5193 OP_VTRNR // VTRN, right result
5196 if (OpNum == OP_COPY) {
5197 if (LHSID == (1*9+2)*9+3) return LHS;
5198 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5202 SDValue OpLHS, OpRHS;
5203 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5204 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5205 EVT VT = OpLHS.getValueType();
5208 default: llvm_unreachable("Unknown shuffle opcode!");
5210 // VREV divides the vector in half and swaps within the half.
5211 if (VT.getVectorElementType() == MVT::i32 ||
5212 VT.getVectorElementType() == MVT::f32)
5213 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5214 // vrev <4 x i16> -> VREV32
5215 if (VT.getVectorElementType() == MVT::i16)
5216 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5217 // vrev <4 x i8> -> VREV16
5218 assert(VT.getVectorElementType() == MVT::i8);
5219 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5224 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5225 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5229 return DAG.getNode(ARMISD::VEXT, dl, VT,
5231 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5234 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5235 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5238 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5239 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5242 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5243 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5247 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5248 ArrayRef<int> ShuffleMask,
5249 SelectionDAG &DAG) {
5250 // Check to see if we can use the VTBL instruction.
5251 SDValue V1 = Op.getOperand(0);
5252 SDValue V2 = Op.getOperand(1);
5255 SmallVector<SDValue, 8> VTBLMask;
5256 for (ArrayRef<int>::iterator
5257 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5258 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5260 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5261 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5262 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5265 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5266 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5270 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5271 SelectionDAG &DAG) {
5273 SDValue OpLHS = Op.getOperand(0);
5274 EVT VT = OpLHS.getValueType();
5276 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5277 "Expect an v8i16/v16i8 type");
5278 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5279 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5280 // extract the first 8 bytes into the top double word and the last 8 bytes
5281 // into the bottom double word. The v8i16 case is similar.
5282 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5283 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5284 DAG.getConstant(ExtractNum, MVT::i32));
5287 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5288 SDValue V1 = Op.getOperand(0);
5289 SDValue V2 = Op.getOperand(1);
5291 EVT VT = Op.getValueType();
5292 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5294 // Convert shuffles that are directly supported on NEON to target-specific
5295 // DAG nodes, instead of keeping them as shuffles and matching them again
5296 // during code selection. This is more efficient and avoids the possibility
5297 // of inconsistencies between legalization and selection.
5298 // FIXME: floating-point vectors should be canonicalized to integer vectors
5299 // of the same time so that they get CSEd properly.
5300 ArrayRef<int> ShuffleMask = SVN->getMask();
5302 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5303 if (EltSize <= 32) {
5304 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5305 int Lane = SVN->getSplatIndex();
5306 // If this is undef splat, generate it via "just" vdup, if possible.
5307 if (Lane == -1) Lane = 0;
5309 // Test if V1 is a SCALAR_TO_VECTOR.
5310 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5311 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5313 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5314 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5316 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5317 !isa<ConstantSDNode>(V1.getOperand(0))) {
5318 bool IsScalarToVector = true;
5319 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5320 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5321 IsScalarToVector = false;
5324 if (IsScalarToVector)
5325 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5327 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5328 DAG.getConstant(Lane, MVT::i32));
5333 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5336 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5337 DAG.getConstant(Imm, MVT::i32));
5340 if (isVREVMask(ShuffleMask, VT, 64))
5341 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5342 if (isVREVMask(ShuffleMask, VT, 32))
5343 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5344 if (isVREVMask(ShuffleMask, VT, 16))
5345 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5347 if (V2->getOpcode() == ISD::UNDEF &&
5348 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5349 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5350 DAG.getConstant(Imm, MVT::i32));
5353 // Check for Neon shuffles that modify both input vectors in place.
5354 // If both results are used, i.e., if there are two shuffles with the same
5355 // source operands and with masks corresponding to both results of one of
5356 // these operations, DAG memoization will ensure that a single node is
5357 // used for both shuffles.
5358 unsigned WhichResult;
5359 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5360 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5361 V1, V2).getValue(WhichResult);
5362 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5363 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5364 V1, V2).getValue(WhichResult);
5365 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5366 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5367 V1, V2).getValue(WhichResult);
5369 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5370 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5371 V1, V1).getValue(WhichResult);
5372 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5373 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5374 V1, V1).getValue(WhichResult);
5375 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5376 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5377 V1, V1).getValue(WhichResult);
5380 // If the shuffle is not directly supported and it has 4 elements, use
5381 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5382 unsigned NumElts = VT.getVectorNumElements();
5384 unsigned PFIndexes[4];
5385 for (unsigned i = 0; i != 4; ++i) {
5386 if (ShuffleMask[i] < 0)
5389 PFIndexes[i] = ShuffleMask[i];
5392 // Compute the index in the perfect shuffle table.
5393 unsigned PFTableIndex =
5394 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5395 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5396 unsigned Cost = (PFEntry >> 30);
5399 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5402 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5403 if (EltSize >= 32) {
5404 // Do the expansion with floating-point types, since that is what the VFP
5405 // registers are defined to use, and since i64 is not legal.
5406 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5407 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5408 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5409 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5410 SmallVector<SDValue, 8> Ops;
5411 for (unsigned i = 0; i < NumElts; ++i) {
5412 if (ShuffleMask[i] < 0)
5413 Ops.push_back(DAG.getUNDEF(EltVT));
5415 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5416 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5417 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5420 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5421 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5424 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5425 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5427 if (VT == MVT::v8i8) {
5428 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5429 if (NewOp.getNode())
5436 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5437 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5438 SDValue Lane = Op.getOperand(2);
5439 if (!isa<ConstantSDNode>(Lane))
5445 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5446 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5447 SDValue Lane = Op.getOperand(1);
5448 if (!isa<ConstantSDNode>(Lane))
5451 SDValue Vec = Op.getOperand(0);
5452 if (Op.getValueType() == MVT::i32 &&
5453 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5455 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5461 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5462 // The only time a CONCAT_VECTORS operation can have legal types is when
5463 // two 64-bit vectors are concatenated to a 128-bit vector.
5464 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5465 "unexpected CONCAT_VECTORS");
5467 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5468 SDValue Op0 = Op.getOperand(0);
5469 SDValue Op1 = Op.getOperand(1);
5470 if (Op0.getOpcode() != ISD::UNDEF)
5471 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5472 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5473 DAG.getIntPtrConstant(0));
5474 if (Op1.getOpcode() != ISD::UNDEF)
5475 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5476 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5477 DAG.getIntPtrConstant(1));
5478 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5481 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5482 /// element has been zero/sign-extended, depending on the isSigned parameter,
5483 /// from an integer type half its size.
5484 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5486 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5487 EVT VT = N->getValueType(0);
5488 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5489 SDNode *BVN = N->getOperand(0).getNode();
5490 if (BVN->getValueType(0) != MVT::v4i32 ||
5491 BVN->getOpcode() != ISD::BUILD_VECTOR)
5493 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5494 unsigned HiElt = 1 - LoElt;
5495 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5496 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5497 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5498 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5499 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5502 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5503 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5506 if (Hi0->isNullValue() && Hi1->isNullValue())
5512 if (N->getOpcode() != ISD::BUILD_VECTOR)
5515 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5516 SDNode *Elt = N->getOperand(i).getNode();
5517 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5518 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5519 unsigned HalfSize = EltSize / 2;
5521 if (!isIntN(HalfSize, C->getSExtValue()))
5524 if (!isUIntN(HalfSize, C->getZExtValue()))
5535 /// isSignExtended - Check if a node is a vector value that is sign-extended
5536 /// or a constant BUILD_VECTOR with sign-extended elements.
5537 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5538 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5540 if (isExtendedBUILD_VECTOR(N, DAG, true))
5545 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5546 /// or a constant BUILD_VECTOR with zero-extended elements.
5547 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5548 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5550 if (isExtendedBUILD_VECTOR(N, DAG, false))
5555 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5556 if (OrigVT.getSizeInBits() >= 64)
5559 assert(OrigVT.isSimple() && "Expecting a simple value type");
5561 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5562 switch (OrigSimpleTy) {
5563 default: llvm_unreachable("Unexpected Vector Type");
5572 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5573 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5574 /// We insert the required extension here to get the vector to fill a D register.
5575 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5578 unsigned ExtOpcode) {
5579 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5580 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5581 // 64-bits we need to insert a new extension so that it will be 64-bits.
5582 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5583 if (OrigTy.getSizeInBits() >= 64)
5586 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5587 EVT NewVT = getExtensionTo64Bits(OrigTy);
5589 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5592 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5593 /// does not do any sign/zero extension. If the original vector is less
5594 /// than 64 bits, an appropriate extension will be added after the load to
5595 /// reach a total size of 64 bits. We have to add the extension separately
5596 /// because ARM does not have a sign/zero extending load for vectors.
5597 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5598 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5600 // The load already has the right type.
5601 if (ExtendedTy == LD->getMemoryVT())
5602 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5603 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5604 LD->isNonTemporal(), LD->isInvariant(),
5605 LD->getAlignment());
5607 // We need to create a zextload/sextload. We cannot just create a load
5608 // followed by a zext/zext node because LowerMUL is also run during normal
5609 // operation legalization where we can't create illegal types.
5610 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5611 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5612 LD->getMemoryVT(), LD->isVolatile(),
5613 LD->isNonTemporal(), LD->getAlignment());
5616 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5617 /// extending load, or BUILD_VECTOR with extended elements, return the
5618 /// unextended value. The unextended vector should be 64 bits so that it can
5619 /// be used as an operand to a VMULL instruction. If the original vector size
5620 /// before extension is less than 64 bits we add a an extension to resize
5621 /// the vector to 64 bits.
5622 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5623 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5624 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5625 N->getOperand(0)->getValueType(0),
5629 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5630 return SkipLoadExtensionForVMULL(LD, DAG);
5632 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5633 // have been legalized as a BITCAST from v4i32.
5634 if (N->getOpcode() == ISD::BITCAST) {
5635 SDNode *BVN = N->getOperand(0).getNode();
5636 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5637 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5638 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5639 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5640 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5642 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5643 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5644 EVT VT = N->getValueType(0);
5645 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5646 unsigned NumElts = VT.getVectorNumElements();
5647 MVT TruncVT = MVT::getIntegerVT(EltSize);
5648 SmallVector<SDValue, 8> Ops;
5649 for (unsigned i = 0; i != NumElts; ++i) {
5650 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5651 const APInt &CInt = C->getAPIntValue();
5652 // Element types smaller than 32 bits are not legal, so use i32 elements.
5653 // The values are implicitly truncated so sext vs. zext doesn't matter.
5654 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5656 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5657 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5660 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5661 unsigned Opcode = N->getOpcode();
5662 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5663 SDNode *N0 = N->getOperand(0).getNode();
5664 SDNode *N1 = N->getOperand(1).getNode();
5665 return N0->hasOneUse() && N1->hasOneUse() &&
5666 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5671 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5672 unsigned Opcode = N->getOpcode();
5673 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5674 SDNode *N0 = N->getOperand(0).getNode();
5675 SDNode *N1 = N->getOperand(1).getNode();
5676 return N0->hasOneUse() && N1->hasOneUse() &&
5677 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5682 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5683 // Multiplications are only custom-lowered for 128-bit vectors so that
5684 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5685 EVT VT = Op.getValueType();
5686 assert(VT.is128BitVector() && VT.isInteger() &&
5687 "unexpected type for custom-lowering ISD::MUL");
5688 SDNode *N0 = Op.getOperand(0).getNode();
5689 SDNode *N1 = Op.getOperand(1).getNode();
5690 unsigned NewOpc = 0;
5692 bool isN0SExt = isSignExtended(N0, DAG);
5693 bool isN1SExt = isSignExtended(N1, DAG);
5694 if (isN0SExt && isN1SExt)
5695 NewOpc = ARMISD::VMULLs;
5697 bool isN0ZExt = isZeroExtended(N0, DAG);
5698 bool isN1ZExt = isZeroExtended(N1, DAG);
5699 if (isN0ZExt && isN1ZExt)
5700 NewOpc = ARMISD::VMULLu;
5701 else if (isN1SExt || isN1ZExt) {
5702 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5703 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5704 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5705 NewOpc = ARMISD::VMULLs;
5707 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5708 NewOpc = ARMISD::VMULLu;
5710 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5712 NewOpc = ARMISD::VMULLu;
5718 if (VT == MVT::v2i64)
5719 // Fall through to expand this. It is not legal.
5722 // Other vector multiplications are legal.
5727 // Legalize to a VMULL instruction.
5730 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5732 Op0 = SkipExtensionForVMULL(N0, DAG);
5733 assert(Op0.getValueType().is64BitVector() &&
5734 Op1.getValueType().is64BitVector() &&
5735 "unexpected types for extended operands to VMULL");
5736 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5739 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5740 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5747 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5748 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5749 EVT Op1VT = Op1.getValueType();
5750 return DAG.getNode(N0->getOpcode(), DL, VT,
5751 DAG.getNode(NewOpc, DL, VT,
5752 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5753 DAG.getNode(NewOpc, DL, VT,
5754 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5758 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5760 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5761 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5762 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5763 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5764 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5765 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5766 // Get reciprocal estimate.
5767 // float4 recip = vrecpeq_f32(yf);
5768 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5769 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5770 // Because char has a smaller range than uchar, we can actually get away
5771 // without any newton steps. This requires that we use a weird bias
5772 // of 0xb000, however (again, this has been exhaustively tested).
5773 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5774 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5775 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5776 Y = DAG.getConstant(0xb000, MVT::i32);
5777 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5778 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5779 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5780 // Convert back to short.
5781 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5782 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5787 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5789 // Convert to float.
5790 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5791 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5792 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5793 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5794 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5795 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5797 // Use reciprocal estimate and one refinement step.
5798 // float4 recip = vrecpeq_f32(yf);
5799 // recip *= vrecpsq_f32(yf, recip);
5800 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5801 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5802 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5803 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5805 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5806 // Because short has a smaller range than ushort, we can actually get away
5807 // with only a single newton step. This requires that we use a weird bias
5808 // of 89, however (again, this has been exhaustively tested).
5809 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5810 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5811 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5812 N1 = DAG.getConstant(0x89, MVT::i32);
5813 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5814 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5815 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5816 // Convert back to integer and return.
5817 // return vmovn_s32(vcvt_s32_f32(result));
5818 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5819 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5823 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5824 EVT VT = Op.getValueType();
5825 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5826 "unexpected type for custom-lowering ISD::SDIV");
5829 SDValue N0 = Op.getOperand(0);
5830 SDValue N1 = Op.getOperand(1);
5833 if (VT == MVT::v8i8) {
5834 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5835 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5837 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5838 DAG.getIntPtrConstant(4));
5839 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5840 DAG.getIntPtrConstant(4));
5841 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5842 DAG.getIntPtrConstant(0));
5843 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5844 DAG.getIntPtrConstant(0));
5846 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5847 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5849 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5850 N0 = LowerCONCAT_VECTORS(N0, DAG);
5852 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5855 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5858 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5859 EVT VT = Op.getValueType();
5860 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5861 "unexpected type for custom-lowering ISD::UDIV");
5864 SDValue N0 = Op.getOperand(0);
5865 SDValue N1 = Op.getOperand(1);
5868 if (VT == MVT::v8i8) {
5869 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5870 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5872 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5873 DAG.getIntPtrConstant(4));
5874 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5875 DAG.getIntPtrConstant(4));
5876 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5877 DAG.getIntPtrConstant(0));
5878 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5879 DAG.getIntPtrConstant(0));
5881 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5882 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5884 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5885 N0 = LowerCONCAT_VECTORS(N0, DAG);
5887 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5888 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5893 // v4i16 sdiv ... Convert to float.
5894 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5895 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5896 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5897 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5898 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5899 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5901 // Use reciprocal estimate and two refinement steps.
5902 // float4 recip = vrecpeq_f32(yf);
5903 // recip *= vrecpsq_f32(yf, recip);
5904 // recip *= vrecpsq_f32(yf, recip);
5905 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5906 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5907 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5908 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5910 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5911 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5912 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5914 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5915 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5916 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5917 // and that it will never cause us to return an answer too large).
5918 // float4 result = as_float4(as_int4(xf*recip) + 2);
5919 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5920 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5921 N1 = DAG.getConstant(2, MVT::i32);
5922 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5923 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5924 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5925 // Convert back to integer and return.
5926 // return vmovn_u32(vcvt_s32_f32(result));
5927 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5928 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5932 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5933 EVT VT = Op.getNode()->getValueType(0);
5934 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5937 bool ExtraOp = false;
5938 switch (Op.getOpcode()) {
5939 default: llvm_unreachable("Invalid code");
5940 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5941 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5942 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5943 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5947 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5949 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5950 Op.getOperand(1), Op.getOperand(2));
5953 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5954 // Monotonic load/store is legal for all targets
5955 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5958 // Aquire/Release load/store is not legal for targets without a
5959 // dmb or equivalent available.
5964 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5965 SelectionDAG &DAG) {
5967 assert (Node->getValueType(0) == MVT::i64 &&
5968 "Only know how to expand i64 atomics");
5969 AtomicSDNode *AN = cast<AtomicSDNode>(Node);
5971 SmallVector<SDValue, 6> Ops;
5972 Ops.push_back(Node->getOperand(0)); // Chain
5973 Ops.push_back(Node->getOperand(1)); // Ptr
5974 for(unsigned i=2; i<Node->getNumOperands(); i++) {
5976 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5977 Node->getOperand(i), DAG.getIntPtrConstant(0)));
5979 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5980 Node->getOperand(i), DAG.getIntPtrConstant(1)));
5982 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5984 DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
5985 cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
5986 AN->getSynchScope());
5987 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5988 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5989 Results.push_back(Result.getValue(2));
5992 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5993 SmallVectorImpl<SDValue> &Results,
5995 const ARMSubtarget *Subtarget) {
5997 SDValue Cycles32, OutChain;
5999 if (Subtarget->hasPerfMon()) {
6000 // Under Power Management extensions, the cycle-count is:
6001 // mrc p15, #0, <Rt>, c9, c13, #0
6002 SDValue Ops[] = { N->getOperand(0), // Chain
6003 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6004 DAG.getConstant(15, MVT::i32),
6005 DAG.getConstant(0, MVT::i32),
6006 DAG.getConstant(9, MVT::i32),
6007 DAG.getConstant(13, MVT::i32),
6008 DAG.getConstant(0, MVT::i32)
6011 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6012 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6013 array_lengthof(Ops));
6014 OutChain = Cycles32.getValue(1);
6016 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6017 // there are older ARM CPUs that have implementation-specific ways of
6018 // obtaining this information (FIXME!).
6019 Cycles32 = DAG.getConstant(0, MVT::i32);
6020 OutChain = DAG.getEntryNode();
6024 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6025 Cycles32, DAG.getConstant(0, MVT::i32));
6026 Results.push_back(Cycles64);
6027 Results.push_back(OutChain);
6030 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6031 switch (Op.getOpcode()) {
6032 default: llvm_unreachable("Don't know how to custom lower this!");
6033 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6034 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6035 case ISD::GlobalAddress:
6036 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6037 LowerGlobalAddressELF(Op, DAG);
6038 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6039 case ISD::SELECT: return LowerSELECT(Op, DAG);
6040 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6041 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6042 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6043 case ISD::VASTART: return LowerVASTART(Op, DAG);
6044 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6045 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6046 case ISD::SINT_TO_FP:
6047 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6048 case ISD::FP_TO_SINT:
6049 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6050 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6051 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6052 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6053 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6054 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6055 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6056 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6058 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6061 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6062 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6063 case ISD::SRL_PARTS:
6064 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6065 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6066 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6067 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6068 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6069 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6070 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6071 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6072 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6073 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6074 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6075 case ISD::MUL: return LowerMUL(Op, DAG);
6076 case ISD::SDIV: return LowerSDIV(Op, DAG);
6077 case ISD::UDIV: return LowerUDIV(Op, DAG);
6081 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6082 case ISD::ATOMIC_LOAD:
6083 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6085 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6089 /// ReplaceNodeResults - Replace the results of node with an illegal result
6090 /// type with new values built out of custom code.
6091 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6092 SmallVectorImpl<SDValue>&Results,
6093 SelectionDAG &DAG) const {
6095 switch (N->getOpcode()) {
6097 llvm_unreachable("Don't know how to custom expand this!");
6099 Res = ExpandBITCAST(N, DAG);
6103 Res = Expand64BitShift(N, DAG, Subtarget);
6105 case ISD::READCYCLECOUNTER:
6106 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6108 case ISD::ATOMIC_STORE:
6109 case ISD::ATOMIC_LOAD:
6110 case ISD::ATOMIC_LOAD_ADD:
6111 case ISD::ATOMIC_LOAD_AND:
6112 case ISD::ATOMIC_LOAD_NAND:
6113 case ISD::ATOMIC_LOAD_OR:
6114 case ISD::ATOMIC_LOAD_SUB:
6115 case ISD::ATOMIC_LOAD_XOR:
6116 case ISD::ATOMIC_SWAP:
6117 case ISD::ATOMIC_CMP_SWAP:
6118 case ISD::ATOMIC_LOAD_MIN:
6119 case ISD::ATOMIC_LOAD_UMIN:
6120 case ISD::ATOMIC_LOAD_MAX:
6121 case ISD::ATOMIC_LOAD_UMAX:
6122 ReplaceATOMIC_OP_64(N, Results, DAG);
6126 Results.push_back(Res);
6129 //===----------------------------------------------------------------------===//
6130 // ARM Scheduler Hooks
6131 //===----------------------------------------------------------------------===//
6134 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6135 MachineBasicBlock *BB,
6136 unsigned Size) const {
6137 unsigned dest = MI->getOperand(0).getReg();
6138 unsigned ptr = MI->getOperand(1).getReg();
6139 unsigned oldval = MI->getOperand(2).getReg();
6140 unsigned newval = MI->getOperand(3).getReg();
6141 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6142 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6143 DebugLoc dl = MI->getDebugLoc();
6144 bool isThumb2 = Subtarget->isThumb2();
6146 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6147 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6148 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6149 (const TargetRegisterClass*)&ARM::GPRRegClass);
6152 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6153 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6154 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6157 unsigned ldrOpc, strOpc;
6158 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6160 MachineFunction *MF = BB->getParent();
6161 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6162 MachineFunction::iterator It = BB;
6163 ++It; // insert the new blocks after the current block
6165 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6166 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6167 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6168 MF->insert(It, loop1MBB);
6169 MF->insert(It, loop2MBB);
6170 MF->insert(It, exitMBB);
6172 // Transfer the remainder of BB and its successor edges to exitMBB.
6173 exitMBB->splice(exitMBB->begin(), BB,
6174 llvm::next(MachineBasicBlock::iterator(MI)),
6176 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6180 // fallthrough --> loop1MBB
6181 BB->addSuccessor(loop1MBB);
6184 // ldrex dest, [ptr]
6188 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6189 if (ldrOpc == ARM::t2LDREX)
6191 AddDefaultPred(MIB);
6192 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6193 .addReg(dest).addReg(oldval));
6194 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6195 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6196 BB->addSuccessor(loop2MBB);
6197 BB->addSuccessor(exitMBB);
6200 // strex scratch, newval, [ptr]
6204 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6205 if (strOpc == ARM::t2STREX)
6207 AddDefaultPred(MIB);
6208 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6209 .addReg(scratch).addImm(0));
6210 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6211 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6212 BB->addSuccessor(loop1MBB);
6213 BB->addSuccessor(exitMBB);
6219 MI->eraseFromParent(); // The instruction is gone now.
6225 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6226 unsigned Size, unsigned BinOpcode) const {
6227 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6228 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6230 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6231 MachineFunction *MF = BB->getParent();
6232 MachineFunction::iterator It = BB;
6235 unsigned dest = MI->getOperand(0).getReg();
6236 unsigned ptr = MI->getOperand(1).getReg();
6237 unsigned incr = MI->getOperand(2).getReg();
6238 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6239 DebugLoc dl = MI->getDebugLoc();
6240 bool isThumb2 = Subtarget->isThumb2();
6242 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6244 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6245 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6246 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6249 unsigned ldrOpc, strOpc;
6250 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6252 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6253 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6254 MF->insert(It, loopMBB);
6255 MF->insert(It, exitMBB);
6257 // Transfer the remainder of BB and its successor edges to exitMBB.
6258 exitMBB->splice(exitMBB->begin(), BB,
6259 llvm::next(MachineBasicBlock::iterator(MI)),
6261 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6263 const TargetRegisterClass *TRC = isThumb2 ?
6264 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6265 (const TargetRegisterClass*)&ARM::GPRRegClass;
6266 unsigned scratch = MRI.createVirtualRegister(TRC);
6267 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6271 // fallthrough --> loopMBB
6272 BB->addSuccessor(loopMBB);
6276 // <binop> scratch2, dest, incr
6277 // strex scratch, scratch2, ptr
6280 // fallthrough --> exitMBB
6282 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6283 if (ldrOpc == ARM::t2LDREX)
6285 AddDefaultPred(MIB);
6287 // operand order needs to go the other way for NAND
6288 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6289 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6290 addReg(incr).addReg(dest)).addReg(0);
6292 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6293 addReg(dest).addReg(incr)).addReg(0);
6296 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6297 if (strOpc == ARM::t2STREX)
6299 AddDefaultPred(MIB);
6300 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6301 .addReg(scratch).addImm(0));
6302 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6303 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6305 BB->addSuccessor(loopMBB);
6306 BB->addSuccessor(exitMBB);
6312 MI->eraseFromParent(); // The instruction is gone now.
6318 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6319 MachineBasicBlock *BB,
6322 ARMCC::CondCodes Cond) const {
6323 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6325 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6326 MachineFunction *MF = BB->getParent();
6327 MachineFunction::iterator It = BB;
6330 unsigned dest = MI->getOperand(0).getReg();
6331 unsigned ptr = MI->getOperand(1).getReg();
6332 unsigned incr = MI->getOperand(2).getReg();
6333 unsigned oldval = dest;
6334 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6335 DebugLoc dl = MI->getDebugLoc();
6336 bool isThumb2 = Subtarget->isThumb2();
6338 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6340 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6341 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6342 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6345 unsigned ldrOpc, strOpc, extendOpc;
6346 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6348 default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6350 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6353 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6360 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6361 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6362 MF->insert(It, loopMBB);
6363 MF->insert(It, exitMBB);
6365 // Transfer the remainder of BB and its successor edges to exitMBB.
6366 exitMBB->splice(exitMBB->begin(), BB,
6367 llvm::next(MachineBasicBlock::iterator(MI)),
6369 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6371 const TargetRegisterClass *TRC = isThumb2 ?
6372 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6373 (const TargetRegisterClass*)&ARM::GPRRegClass;
6374 unsigned scratch = MRI.createVirtualRegister(TRC);
6375 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6379 // fallthrough --> loopMBB
6380 BB->addSuccessor(loopMBB);
6384 // (sign extend dest, if required)
6386 // cmov.cond scratch2, incr, dest
6387 // strex scratch, scratch2, ptr
6390 // fallthrough --> exitMBB
6392 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6393 if (ldrOpc == ARM::t2LDREX)
6395 AddDefaultPred(MIB);
6397 // Sign extend the value, if necessary.
6398 if (signExtend && extendOpc) {
6399 oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6400 : &ARM::GPRnopcRegClass);
6402 MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6403 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6408 // Build compare and cmov instructions.
6409 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6410 .addReg(oldval).addReg(incr));
6411 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6412 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6414 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6415 if (strOpc == ARM::t2STREX)
6417 AddDefaultPred(MIB);
6418 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6419 .addReg(scratch).addImm(0));
6420 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6421 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6423 BB->addSuccessor(loopMBB);
6424 BB->addSuccessor(exitMBB);
6430 MI->eraseFromParent(); // The instruction is gone now.
6436 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6437 unsigned Op1, unsigned Op2,
6438 bool NeedsCarry, bool IsCmpxchg,
6439 bool IsMinMax, ARMCC::CondCodes CC) const {
6440 // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6441 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6443 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6444 MachineFunction *MF = BB->getParent();
6445 MachineFunction::iterator It = BB;
6448 bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6449 unsigned offset = (isStore ? -2 : 0);
6450 unsigned destlo = MI->getOperand(0).getReg();
6451 unsigned desthi = MI->getOperand(1).getReg();
6452 unsigned ptr = MI->getOperand(offset+2).getReg();
6453 unsigned vallo = MI->getOperand(offset+3).getReg();
6454 unsigned valhi = MI->getOperand(offset+4).getReg();
6455 unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6456 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6457 DebugLoc dl = MI->getDebugLoc();
6458 bool isThumb2 = Subtarget->isThumb2();
6460 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6462 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6463 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6464 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6465 MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6466 MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6469 unsigned ldrOpc, strOpc;
6470 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6472 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6473 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6474 if (IsCmpxchg || IsMinMax)
6475 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6477 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6478 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6480 MF->insert(It, loopMBB);
6481 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6482 if (IsCmpxchg) MF->insert(It, cont2BB);
6483 MF->insert(It, exitMBB);
6485 // Transfer the remainder of BB and its successor edges to exitMBB.
6486 exitMBB->splice(exitMBB->begin(), BB,
6487 llvm::next(MachineBasicBlock::iterator(MI)),
6489 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6491 const TargetRegisterClass *TRC = isThumb2 ?
6492 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6493 (const TargetRegisterClass*)&ARM::GPRRegClass;
6494 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6498 // fallthrough --> loopMBB
6499 BB->addSuccessor(loopMBB);
6502 // ldrexd r2, r3, ptr
6503 // <binopa> r0, r2, incr
6504 // <binopb> r1, r3, incr
6505 // strexd storesuccess, r0, r1, ptr
6506 // cmp storesuccess, #0
6508 // fallthrough --> exitMBB
6514 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6515 .addReg(destlo, RegState::Define)
6516 .addReg(desthi, RegState::Define)
6519 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6520 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6521 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6522 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6523 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6524 .addReg(GPRPair0, 0, ARM::gsub_0);
6525 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6526 .addReg(GPRPair0, 0, ARM::gsub_1);
6530 unsigned StoreLo, StoreHi;
6533 for (unsigned i = 0; i < 2; i++) {
6534 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6536 .addReg(i == 0 ? destlo : desthi)
6537 .addReg(i == 0 ? vallo : valhi));
6538 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6539 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6540 BB->addSuccessor(exitMBB);
6541 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6542 BB = (i == 0 ? contBB : cont2BB);
6545 // Copy to physregs for strexd
6546 StoreLo = MI->getOperand(5).getReg();
6547 StoreHi = MI->getOperand(6).getReg();
6549 // Perform binary operation
6550 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6551 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6552 .addReg(destlo).addReg(vallo))
6553 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6554 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6555 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6556 .addReg(desthi).addReg(valhi))
6557 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6562 // Copy to physregs for strexd
6567 // Compare and branch to exit block.
6568 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6569 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6570 BB->addSuccessor(exitMBB);
6571 BB->addSuccessor(contBB);
6579 MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6580 MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6581 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6582 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6584 // Marshal a pair...
6585 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6586 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6587 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6588 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6589 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6592 .addImm(ARM::gsub_0);
6593 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6596 .addImm(ARM::gsub_1);
6599 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6600 .addReg(StorePair).addReg(ptr));
6603 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6604 .addReg(storesuccess).addImm(0));
6605 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6606 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6608 BB->addSuccessor(loopMBB);
6609 BB->addSuccessor(exitMBB);
6615 MI->eraseFromParent(); // The instruction is gone now.
6621 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6623 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6625 unsigned destlo = MI->getOperand(0).getReg();
6626 unsigned desthi = MI->getOperand(1).getReg();
6627 unsigned ptr = MI->getOperand(2).getReg();
6628 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6629 DebugLoc dl = MI->getDebugLoc();
6630 bool isThumb2 = Subtarget->isThumb2();
6632 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6634 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6635 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6636 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6638 unsigned ldrOpc, strOpc;
6639 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6641 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6644 MIB.addReg(destlo, RegState::Define)
6645 .addReg(desthi, RegState::Define)
6649 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6650 MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6652 // Copy GPRPair0 into dest. (This copy will normally be coalesced.)
6653 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6654 .addReg(GPRPair0, 0, ARM::gsub_0);
6655 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6656 .addReg(GPRPair0, 0, ARM::gsub_1);
6658 AddDefaultPred(MIB);
6660 MI->eraseFromParent(); // The instruction is gone now.
6665 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6666 /// registers the function context.
6667 void ARMTargetLowering::
6668 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6669 MachineBasicBlock *DispatchBB, int FI) const {
6670 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6671 DebugLoc dl = MI->getDebugLoc();
6672 MachineFunction *MF = MBB->getParent();
6673 MachineRegisterInfo *MRI = &MF->getRegInfo();
6674 MachineConstantPool *MCP = MF->getConstantPool();
6675 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6676 const Function *F = MF->getFunction();
6678 bool isThumb = Subtarget->isThumb();
6679 bool isThumb2 = Subtarget->isThumb2();
6681 unsigned PCLabelId = AFI->createPICLabelUId();
6682 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6683 ARMConstantPoolValue *CPV =
6684 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6685 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6687 const TargetRegisterClass *TRC = isThumb ?
6688 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6689 (const TargetRegisterClass*)&ARM::GPRRegClass;
6691 // Grab constant pool and fixed stack memory operands.
6692 MachineMemOperand *CPMMO =
6693 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6694 MachineMemOperand::MOLoad, 4, 4);
6696 MachineMemOperand *FIMMOSt =
6697 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6698 MachineMemOperand::MOStore, 4, 4);
6700 // Load the address of the dispatch MBB into the jump buffer.
6702 // Incoming value: jbuf
6703 // ldr.n r5, LCPI1_1
6706 // str r5, [$jbuf, #+4] ; &jbuf[1]
6707 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6708 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6709 .addConstantPoolIndex(CPI)
6710 .addMemOperand(CPMMO));
6711 // Set the low bit because of thumb mode.
6712 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6714 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6715 .addReg(NewVReg1, RegState::Kill)
6717 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6718 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6719 .addReg(NewVReg2, RegState::Kill)
6721 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6722 .addReg(NewVReg3, RegState::Kill)
6724 .addImm(36) // &jbuf[1] :: pc
6725 .addMemOperand(FIMMOSt));
6726 } else if (isThumb) {
6727 // Incoming value: jbuf
6728 // ldr.n r1, LCPI1_4
6732 // add r2, $jbuf, #+4 ; &jbuf[1]
6734 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6735 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6736 .addConstantPoolIndex(CPI)
6737 .addMemOperand(CPMMO));
6738 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6739 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6740 .addReg(NewVReg1, RegState::Kill)
6742 // Set the low bit because of thumb mode.
6743 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6744 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6745 .addReg(ARM::CPSR, RegState::Define)
6747 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6748 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6749 .addReg(ARM::CPSR, RegState::Define)
6750 .addReg(NewVReg2, RegState::Kill)
6751 .addReg(NewVReg3, RegState::Kill));
6752 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6753 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6755 .addImm(36)); // &jbuf[1] :: pc
6756 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6757 .addReg(NewVReg4, RegState::Kill)
6758 .addReg(NewVReg5, RegState::Kill)
6760 .addMemOperand(FIMMOSt));
6762 // Incoming value: jbuf
6765 // str r1, [$jbuf, #+4] ; &jbuf[1]
6766 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6767 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6768 .addConstantPoolIndex(CPI)
6770 .addMemOperand(CPMMO));
6771 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6772 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6773 .addReg(NewVReg1, RegState::Kill)
6774 .addImm(PCLabelId));
6775 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6776 .addReg(NewVReg2, RegState::Kill)
6778 .addImm(36) // &jbuf[1] :: pc
6779 .addMemOperand(FIMMOSt));
6783 MachineBasicBlock *ARMTargetLowering::
6784 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6785 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6786 DebugLoc dl = MI->getDebugLoc();
6787 MachineFunction *MF = MBB->getParent();
6788 MachineRegisterInfo *MRI = &MF->getRegInfo();
6789 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6790 MachineFrameInfo *MFI = MF->getFrameInfo();
6791 int FI = MFI->getFunctionContextIndex();
6793 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6794 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6795 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6797 // Get a mapping of the call site numbers to all of the landing pads they're
6799 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6800 unsigned MaxCSNum = 0;
6801 MachineModuleInfo &MMI = MF->getMMI();
6802 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6804 if (!BB->isLandingPad()) continue;
6806 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6808 for (MachineBasicBlock::iterator
6809 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6810 if (!II->isEHLabel()) continue;
6812 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6813 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6815 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6816 for (SmallVectorImpl<unsigned>::iterator
6817 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6818 CSI != CSE; ++CSI) {
6819 CallSiteNumToLPad[*CSI].push_back(BB);
6820 MaxCSNum = std::max(MaxCSNum, *CSI);
6826 // Get an ordered list of the machine basic blocks for the jump table.
6827 std::vector<MachineBasicBlock*> LPadList;
6828 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6829 LPadList.reserve(CallSiteNumToLPad.size());
6830 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6831 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6832 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6833 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6834 LPadList.push_back(*II);
6835 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6839 assert(!LPadList.empty() &&
6840 "No landing pad destinations for the dispatch jump table!");
6842 // Create the jump table and associated information.
6843 MachineJumpTableInfo *JTI =
6844 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6845 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6846 unsigned UId = AFI->createJumpTableUId();
6847 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6849 // Create the MBBs for the dispatch code.
6851 // Shove the dispatch's address into the return slot in the function context.
6852 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6853 DispatchBB->setIsLandingPad();
6855 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6856 unsigned trap_opcode;
6857 if (Subtarget->isThumb())
6858 trap_opcode = ARM::tTRAP;
6860 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6862 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6863 DispatchBB->addSuccessor(TrapBB);
6865 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6866 DispatchBB->addSuccessor(DispContBB);
6869 MF->insert(MF->end(), DispatchBB);
6870 MF->insert(MF->end(), DispContBB);
6871 MF->insert(MF->end(), TrapBB);
6873 // Insert code into the entry block that creates and registers the function
6875 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6877 MachineMemOperand *FIMMOLd =
6878 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6879 MachineMemOperand::MOLoad |
6880 MachineMemOperand::MOVolatile, 4, 4);
6882 MachineInstrBuilder MIB;
6883 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6885 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6886 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6888 // Add a register mask with no preserved registers. This results in all
6889 // registers being marked as clobbered.
6890 MIB.addRegMask(RI.getNoPreservedMask());
6892 unsigned NumLPads = LPadList.size();
6893 if (Subtarget->isThumb2()) {
6894 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6895 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6898 .addMemOperand(FIMMOLd));
6900 if (NumLPads < 256) {
6901 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6903 .addImm(LPadList.size()));
6905 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6906 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6907 .addImm(NumLPads & 0xFFFF));
6909 unsigned VReg2 = VReg1;
6910 if ((NumLPads & 0xFFFF0000) != 0) {
6911 VReg2 = MRI->createVirtualRegister(TRC);
6912 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6914 .addImm(NumLPads >> 16));
6917 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6922 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6927 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6928 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6929 .addJumpTableIndex(MJTI)
6932 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6935 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6936 .addReg(NewVReg3, RegState::Kill)
6938 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6940 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6941 .addReg(NewVReg4, RegState::Kill)
6943 .addJumpTableIndex(MJTI)
6945 } else if (Subtarget->isThumb()) {
6946 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6947 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6950 .addMemOperand(FIMMOLd));
6952 if (NumLPads < 256) {
6953 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6957 MachineConstantPool *ConstantPool = MF->getConstantPool();
6958 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6959 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6961 // MachineConstantPool wants an explicit alignment.
6962 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6964 Align = getDataLayout()->getTypeAllocSize(C->getType());
6965 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6967 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6968 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6969 .addReg(VReg1, RegState::Define)
6970 .addConstantPoolIndex(Idx));
6971 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6976 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6981 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6982 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6983 .addReg(ARM::CPSR, RegState::Define)
6987 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6988 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6989 .addJumpTableIndex(MJTI)
6992 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6993 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6994 .addReg(ARM::CPSR, RegState::Define)
6995 .addReg(NewVReg2, RegState::Kill)
6998 MachineMemOperand *JTMMOLd =
6999 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7000 MachineMemOperand::MOLoad, 4, 4);
7002 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7003 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7004 .addReg(NewVReg4, RegState::Kill)
7006 .addMemOperand(JTMMOLd));
7008 unsigned NewVReg6 = NewVReg5;
7009 if (RelocM == Reloc::PIC_) {
7010 NewVReg6 = MRI->createVirtualRegister(TRC);
7011 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7012 .addReg(ARM::CPSR, RegState::Define)
7013 .addReg(NewVReg5, RegState::Kill)
7017 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7018 .addReg(NewVReg6, RegState::Kill)
7019 .addJumpTableIndex(MJTI)
7022 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7023 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7026 .addMemOperand(FIMMOLd));
7028 if (NumLPads < 256) {
7029 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7032 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7033 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7034 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7035 .addImm(NumLPads & 0xFFFF));
7037 unsigned VReg2 = VReg1;
7038 if ((NumLPads & 0xFFFF0000) != 0) {
7039 VReg2 = MRI->createVirtualRegister(TRC);
7040 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7042 .addImm(NumLPads >> 16));
7045 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7049 MachineConstantPool *ConstantPool = MF->getConstantPool();
7050 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7051 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7053 // MachineConstantPool wants an explicit alignment.
7054 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7056 Align = getDataLayout()->getTypeAllocSize(C->getType());
7057 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7059 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7060 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7061 .addReg(VReg1, RegState::Define)
7062 .addConstantPoolIndex(Idx)
7064 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7066 .addReg(VReg1, RegState::Kill));
7069 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7074 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7076 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7078 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7079 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7080 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7081 .addJumpTableIndex(MJTI)
7084 MachineMemOperand *JTMMOLd =
7085 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7086 MachineMemOperand::MOLoad, 4, 4);
7087 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7089 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7090 .addReg(NewVReg3, RegState::Kill)
7093 .addMemOperand(JTMMOLd));
7095 if (RelocM == Reloc::PIC_) {
7096 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7097 .addReg(NewVReg5, RegState::Kill)
7099 .addJumpTableIndex(MJTI)
7102 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7103 .addReg(NewVReg5, RegState::Kill)
7104 .addJumpTableIndex(MJTI)
7109 // Add the jump table entries as successors to the MBB.
7110 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7111 for (std::vector<MachineBasicBlock*>::iterator
7112 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7113 MachineBasicBlock *CurMBB = *I;
7114 if (SeenMBBs.insert(CurMBB))
7115 DispContBB->addSuccessor(CurMBB);
7118 // N.B. the order the invoke BBs are processed in doesn't matter here.
7119 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7120 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7121 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7122 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7123 MachineBasicBlock *BB = *I;
7125 // Remove the landing pad successor from the invoke block and replace it
7126 // with the new dispatch block.
7127 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7129 while (!Successors.empty()) {
7130 MachineBasicBlock *SMBB = Successors.pop_back_val();
7131 if (SMBB->isLandingPad()) {
7132 BB->removeSuccessor(SMBB);
7133 MBBLPads.push_back(SMBB);
7137 BB->addSuccessor(DispatchBB);
7139 // Find the invoke call and mark all of the callee-saved registers as
7140 // 'implicit defined' so that they're spilled. This prevents code from
7141 // moving instructions to before the EH block, where they will never be
7143 for (MachineBasicBlock::reverse_iterator
7144 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7145 if (!II->isCall()) continue;
7147 DenseMap<unsigned, bool> DefRegs;
7148 for (MachineInstr::mop_iterator
7149 OI = II->operands_begin(), OE = II->operands_end();
7151 if (!OI->isReg()) continue;
7152 DefRegs[OI->getReg()] = true;
7155 MachineInstrBuilder MIB(*MF, &*II);
7157 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7158 unsigned Reg = SavedRegs[i];
7159 if (Subtarget->isThumb2() &&
7160 !ARM::tGPRRegClass.contains(Reg) &&
7161 !ARM::hGPRRegClass.contains(Reg))
7163 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7165 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7168 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7175 // Mark all former landing pads as non-landing pads. The dispatch is the only
7177 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7178 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7179 (*I)->setIsLandingPad(false);
7181 // The instruction is gone now.
7182 MI->eraseFromParent();
7188 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7189 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7190 E = MBB->succ_end(); I != E; ++I)
7193 llvm_unreachable("Expecting a BB with two successors!");
7196 /// Return the load opcode for a given load size. If load size >= 8,
7197 /// neon opcode will be returned.
7198 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7200 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7201 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7203 return LdSize == 4 ? ARM::tLDRi
7204 : LdSize == 2 ? ARM::tLDRHi
7205 : LdSize == 1 ? ARM::tLDRBi : 0;
7207 return LdSize == 4 ? ARM::t2LDR_POST
7208 : LdSize == 2 ? ARM::t2LDRH_POST
7209 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7210 return LdSize == 4 ? ARM::LDR_POST_IMM
7211 : LdSize == 2 ? ARM::LDRH_POST
7212 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7215 /// Return the store opcode for a given store size. If store size >= 8,
7216 /// neon opcode will be returned.
7217 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7219 return StSize == 16 ? ARM::VST1q32wb_fixed
7220 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7222 return StSize == 4 ? ARM::tSTRi
7223 : StSize == 2 ? ARM::tSTRHi
7224 : StSize == 1 ? ARM::tSTRBi : 0;
7226 return StSize == 4 ? ARM::t2STR_POST
7227 : StSize == 2 ? ARM::t2STRH_POST
7228 : StSize == 1 ? ARM::t2STRB_POST : 0;
7229 return StSize == 4 ? ARM::STR_POST_IMM
7230 : StSize == 2 ? ARM::STRH_POST
7231 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7234 /// Emit a post-increment load operation with given size. The instructions
7235 /// will be added to BB at Pos.
7236 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7237 const TargetInstrInfo *TII, DebugLoc dl,
7238 unsigned LdSize, unsigned Data, unsigned AddrIn,
7239 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7240 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7241 assert(LdOpc != 0 && "Should have a load opcode");
7243 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7244 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7246 } else if (IsThumb1) {
7247 // load + update AddrIn
7248 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7249 .addReg(AddrIn).addImm(0));
7250 MachineInstrBuilder MIB =
7251 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7252 MIB = AddDefaultT1CC(MIB);
7253 MIB.addReg(AddrIn).addImm(LdSize);
7254 AddDefaultPred(MIB);
7255 } else if (IsThumb2) {
7256 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7257 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7260 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7261 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7262 .addReg(0).addImm(LdSize));
7266 /// Emit a post-increment store operation with given size. The instructions
7267 /// will be added to BB at Pos.
7268 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7269 const TargetInstrInfo *TII, DebugLoc dl,
7270 unsigned StSize, unsigned Data, unsigned AddrIn,
7271 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7272 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7273 assert(StOpc != 0 && "Should have a store opcode");
7275 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7276 .addReg(AddrIn).addImm(0).addReg(Data));
7277 } else if (IsThumb1) {
7278 // store + update AddrIn
7279 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7280 .addReg(AddrIn).addImm(0));
7281 MachineInstrBuilder MIB =
7282 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7283 MIB = AddDefaultT1CC(MIB);
7284 MIB.addReg(AddrIn).addImm(StSize);
7285 AddDefaultPred(MIB);
7286 } else if (IsThumb2) {
7287 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7288 .addReg(Data).addReg(AddrIn).addImm(StSize));
7290 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7291 .addReg(Data).addReg(AddrIn).addReg(0)
7297 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7298 MachineBasicBlock *BB) const {
7299 // This pseudo instruction has 3 operands: dst, src, size
7300 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7301 // Otherwise, we will generate unrolled scalar copies.
7302 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7303 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7304 MachineFunction::iterator It = BB;
7307 unsigned dest = MI->getOperand(0).getReg();
7308 unsigned src = MI->getOperand(1).getReg();
7309 unsigned SizeVal = MI->getOperand(2).getImm();
7310 unsigned Align = MI->getOperand(3).getImm();
7311 DebugLoc dl = MI->getDebugLoc();
7313 MachineFunction *MF = BB->getParent();
7314 MachineRegisterInfo &MRI = MF->getRegInfo();
7315 unsigned UnitSize = 0;
7316 const TargetRegisterClass *TRC = 0;
7317 const TargetRegisterClass *VecTRC = 0;
7319 bool IsThumb1 = Subtarget->isThumb1Only();
7320 bool IsThumb2 = Subtarget->isThumb2();
7324 } else if (Align & 2) {
7327 // Check whether we can use NEON instructions.
7328 if (!MF->getFunction()->getAttributes().
7329 hasAttribute(AttributeSet::FunctionIndex,
7330 Attribute::NoImplicitFloat) &&
7331 Subtarget->hasNEON()) {
7332 if ((Align % 16 == 0) && SizeVal >= 16)
7334 else if ((Align % 8 == 0) && SizeVal >= 8)
7337 // Can't use NEON instructions.
7342 // Select the correct opcode and register class for unit size load/store
7343 bool IsNeon = UnitSize >= 8;
7344 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7345 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7347 VecTRC = UnitSize == 16
7348 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7350 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7353 unsigned BytesLeft = SizeVal % UnitSize;
7354 unsigned LoopSize = SizeVal - BytesLeft;
7356 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7357 // Use LDR and STR to copy.
7358 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7359 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7360 unsigned srcIn = src;
7361 unsigned destIn = dest;
7362 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7363 unsigned srcOut = MRI.createVirtualRegister(TRC);
7364 unsigned destOut = MRI.createVirtualRegister(TRC);
7365 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7366 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7367 IsThumb1, IsThumb2);
7368 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7369 IsThumb1, IsThumb2);
7374 // Handle the leftover bytes with LDRB and STRB.
7375 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7376 // [destOut] = STRB_POST(scratch, destIn, 1)
7377 for (unsigned i = 0; i < BytesLeft; i++) {
7378 unsigned srcOut = MRI.createVirtualRegister(TRC);
7379 unsigned destOut = MRI.createVirtualRegister(TRC);
7380 unsigned scratch = MRI.createVirtualRegister(TRC);
7381 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7382 IsThumb1, IsThumb2);
7383 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7384 IsThumb1, IsThumb2);
7388 MI->eraseFromParent(); // The instruction is gone now.
7392 // Expand the pseudo op to a loop.
7395 // movw varEnd, # --> with thumb2
7397 // ldrcp varEnd, idx --> without thumb2
7398 // fallthrough --> loopMBB
7400 // PHI varPhi, varEnd, varLoop
7401 // PHI srcPhi, src, srcLoop
7402 // PHI destPhi, dst, destLoop
7403 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7404 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7405 // subs varLoop, varPhi, #UnitSize
7407 // fallthrough --> exitMBB
7409 // epilogue to handle left-over bytes
7410 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7411 // [destOut] = STRB_POST(scratch, destLoop, 1)
7412 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7413 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7414 MF->insert(It, loopMBB);
7415 MF->insert(It, exitMBB);
7417 // Transfer the remainder of BB and its successor edges to exitMBB.
7418 exitMBB->splice(exitMBB->begin(), BB,
7419 llvm::next(MachineBasicBlock::iterator(MI)),
7421 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7423 // Load an immediate to varEnd.
7424 unsigned varEnd = MRI.createVirtualRegister(TRC);
7426 unsigned Vtmp = varEnd;
7427 if ((LoopSize & 0xFFFF0000) != 0)
7428 Vtmp = MRI.createVirtualRegister(TRC);
7429 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7430 .addImm(LoopSize & 0xFFFF));
7432 if ((LoopSize & 0xFFFF0000) != 0)
7433 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7434 .addReg(Vtmp).addImm(LoopSize >> 16));
7436 MachineConstantPool *ConstantPool = MF->getConstantPool();
7437 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7438 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7440 // MachineConstantPool wants an explicit alignment.
7441 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7443 Align = getDataLayout()->getTypeAllocSize(C->getType());
7444 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7447 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7448 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7450 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7451 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7453 BB->addSuccessor(loopMBB);
7455 // Generate the loop body:
7456 // varPhi = PHI(varLoop, varEnd)
7457 // srcPhi = PHI(srcLoop, src)
7458 // destPhi = PHI(destLoop, dst)
7459 MachineBasicBlock *entryBB = BB;
7461 unsigned varLoop = MRI.createVirtualRegister(TRC);
7462 unsigned varPhi = MRI.createVirtualRegister(TRC);
7463 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7464 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7465 unsigned destLoop = MRI.createVirtualRegister(TRC);
7466 unsigned destPhi = MRI.createVirtualRegister(TRC);
7468 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7469 .addReg(varLoop).addMBB(loopMBB)
7470 .addReg(varEnd).addMBB(entryBB);
7471 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7472 .addReg(srcLoop).addMBB(loopMBB)
7473 .addReg(src).addMBB(entryBB);
7474 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7475 .addReg(destLoop).addMBB(loopMBB)
7476 .addReg(dest).addMBB(entryBB);
7478 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7479 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7480 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7481 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7482 IsThumb1, IsThumb2);
7483 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7484 IsThumb1, IsThumb2);
7486 // Decrement loop variable by UnitSize.
7488 MachineInstrBuilder MIB =
7489 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7490 MIB = AddDefaultT1CC(MIB);
7491 MIB.addReg(varPhi).addImm(UnitSize);
7492 AddDefaultPred(MIB);
7494 MachineInstrBuilder MIB =
7495 BuildMI(*BB, BB->end(), dl,
7496 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7497 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7498 MIB->getOperand(5).setReg(ARM::CPSR);
7499 MIB->getOperand(5).setIsDef(true);
7501 BuildMI(*BB, BB->end(), dl,
7502 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7503 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7505 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7506 BB->addSuccessor(loopMBB);
7507 BB->addSuccessor(exitMBB);
7509 // Add epilogue to handle BytesLeft.
7511 MachineInstr *StartOfExit = exitMBB->begin();
7513 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7514 // [destOut] = STRB_POST(scratch, destLoop, 1)
7515 unsigned srcIn = srcLoop;
7516 unsigned destIn = destLoop;
7517 for (unsigned i = 0; i < BytesLeft; i++) {
7518 unsigned srcOut = MRI.createVirtualRegister(TRC);
7519 unsigned destOut = MRI.createVirtualRegister(TRC);
7520 unsigned scratch = MRI.createVirtualRegister(TRC);
7521 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7522 IsThumb1, IsThumb2);
7523 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7524 IsThumb1, IsThumb2);
7529 MI->eraseFromParent(); // The instruction is gone now.
7534 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7535 MachineBasicBlock *BB) const {
7536 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7537 DebugLoc dl = MI->getDebugLoc();
7538 bool isThumb2 = Subtarget->isThumb2();
7539 switch (MI->getOpcode()) {
7542 llvm_unreachable("Unexpected instr type to insert");
7544 // The Thumb2 pre-indexed stores have the same MI operands, they just
7545 // define them differently in the .td files from the isel patterns, so
7546 // they need pseudos.
7547 case ARM::t2STR_preidx:
7548 MI->setDesc(TII->get(ARM::t2STR_PRE));
7550 case ARM::t2STRB_preidx:
7551 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7553 case ARM::t2STRH_preidx:
7554 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7557 case ARM::STRi_preidx:
7558 case ARM::STRBi_preidx: {
7559 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7560 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7561 // Decode the offset.
7562 unsigned Offset = MI->getOperand(4).getImm();
7563 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7564 Offset = ARM_AM::getAM2Offset(Offset);
7568 MachineMemOperand *MMO = *MI->memoperands_begin();
7569 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7570 .addOperand(MI->getOperand(0)) // Rn_wb
7571 .addOperand(MI->getOperand(1)) // Rt
7572 .addOperand(MI->getOperand(2)) // Rn
7573 .addImm(Offset) // offset (skip GPR==zero_reg)
7574 .addOperand(MI->getOperand(5)) // pred
7575 .addOperand(MI->getOperand(6))
7576 .addMemOperand(MMO);
7577 MI->eraseFromParent();
7580 case ARM::STRr_preidx:
7581 case ARM::STRBr_preidx:
7582 case ARM::STRH_preidx: {
7584 switch (MI->getOpcode()) {
7585 default: llvm_unreachable("unexpected opcode!");
7586 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7587 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7588 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7590 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7591 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7592 MIB.addOperand(MI->getOperand(i));
7593 MI->eraseFromParent();
7596 case ARM::ATOMIC_LOAD_ADD_I8:
7597 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7598 case ARM::ATOMIC_LOAD_ADD_I16:
7599 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7600 case ARM::ATOMIC_LOAD_ADD_I32:
7601 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7603 case ARM::ATOMIC_LOAD_AND_I8:
7604 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7605 case ARM::ATOMIC_LOAD_AND_I16:
7606 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7607 case ARM::ATOMIC_LOAD_AND_I32:
7608 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7610 case ARM::ATOMIC_LOAD_OR_I8:
7611 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7612 case ARM::ATOMIC_LOAD_OR_I16:
7613 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7614 case ARM::ATOMIC_LOAD_OR_I32:
7615 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7617 case ARM::ATOMIC_LOAD_XOR_I8:
7618 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7619 case ARM::ATOMIC_LOAD_XOR_I16:
7620 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7621 case ARM::ATOMIC_LOAD_XOR_I32:
7622 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7624 case ARM::ATOMIC_LOAD_NAND_I8:
7625 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7626 case ARM::ATOMIC_LOAD_NAND_I16:
7627 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7628 case ARM::ATOMIC_LOAD_NAND_I32:
7629 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7631 case ARM::ATOMIC_LOAD_SUB_I8:
7632 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7633 case ARM::ATOMIC_LOAD_SUB_I16:
7634 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7635 case ARM::ATOMIC_LOAD_SUB_I32:
7636 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7638 case ARM::ATOMIC_LOAD_MIN_I8:
7639 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7640 case ARM::ATOMIC_LOAD_MIN_I16:
7641 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7642 case ARM::ATOMIC_LOAD_MIN_I32:
7643 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7645 case ARM::ATOMIC_LOAD_MAX_I8:
7646 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7647 case ARM::ATOMIC_LOAD_MAX_I16:
7648 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7649 case ARM::ATOMIC_LOAD_MAX_I32:
7650 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7652 case ARM::ATOMIC_LOAD_UMIN_I8:
7653 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7654 case ARM::ATOMIC_LOAD_UMIN_I16:
7655 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7656 case ARM::ATOMIC_LOAD_UMIN_I32:
7657 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7659 case ARM::ATOMIC_LOAD_UMAX_I8:
7660 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7661 case ARM::ATOMIC_LOAD_UMAX_I16:
7662 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7663 case ARM::ATOMIC_LOAD_UMAX_I32:
7664 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7666 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7667 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7668 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7670 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7671 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7672 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7674 case ARM::ATOMIC_LOAD_I64:
7675 return EmitAtomicLoad64(MI, BB);
7677 case ARM::ATOMIC_LOAD_ADD_I64:
7678 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7679 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7680 /*NeedsCarry*/ true);
7681 case ARM::ATOMIC_LOAD_SUB_I64:
7682 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7683 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7684 /*NeedsCarry*/ true);
7685 case ARM::ATOMIC_LOAD_OR_I64:
7686 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7687 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7688 case ARM::ATOMIC_LOAD_XOR_I64:
7689 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7690 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7691 case ARM::ATOMIC_LOAD_AND_I64:
7692 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7693 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7694 case ARM::ATOMIC_STORE_I64:
7695 case ARM::ATOMIC_SWAP_I64:
7696 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7697 case ARM::ATOMIC_CMP_SWAP_I64:
7698 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7699 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7700 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7701 case ARM::ATOMIC_LOAD_MIN_I64:
7702 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7703 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7704 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7705 /*IsMinMax*/ true, ARMCC::LT);
7706 case ARM::ATOMIC_LOAD_MAX_I64:
7707 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7708 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7709 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7710 /*IsMinMax*/ true, ARMCC::GE);
7711 case ARM::ATOMIC_LOAD_UMIN_I64:
7712 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7713 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7714 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7715 /*IsMinMax*/ true, ARMCC::LO);
7716 case ARM::ATOMIC_LOAD_UMAX_I64:
7717 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7718 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7719 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7720 /*IsMinMax*/ true, ARMCC::HS);
7722 case ARM::tMOVCCr_pseudo: {
7723 // To "insert" a SELECT_CC instruction, we actually have to insert the
7724 // diamond control-flow pattern. The incoming instruction knows the
7725 // destination vreg to set, the condition code register to branch on, the
7726 // true/false values to select between, and a branch opcode to use.
7727 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7728 MachineFunction::iterator It = BB;
7734 // cmpTY ccX, r1, r2
7736 // fallthrough --> copy0MBB
7737 MachineBasicBlock *thisMBB = BB;
7738 MachineFunction *F = BB->getParent();
7739 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7740 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7741 F->insert(It, copy0MBB);
7742 F->insert(It, sinkMBB);
7744 // Transfer the remainder of BB and its successor edges to sinkMBB.
7745 sinkMBB->splice(sinkMBB->begin(), BB,
7746 llvm::next(MachineBasicBlock::iterator(MI)),
7748 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7750 BB->addSuccessor(copy0MBB);
7751 BB->addSuccessor(sinkMBB);
7753 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7754 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7757 // %FalseValue = ...
7758 // # fallthrough to sinkMBB
7761 // Update machine-CFG edges
7762 BB->addSuccessor(sinkMBB);
7765 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7768 BuildMI(*BB, BB->begin(), dl,
7769 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7770 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7771 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7773 MI->eraseFromParent(); // The pseudo instruction is gone now.
7778 case ARM::BCCZi64: {
7779 // If there is an unconditional branch to the other successor, remove it.
7780 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7782 // Compare both parts that make up the double comparison separately for
7784 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7786 unsigned LHS1 = MI->getOperand(1).getReg();
7787 unsigned LHS2 = MI->getOperand(2).getReg();
7789 AddDefaultPred(BuildMI(BB, dl,
7790 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7791 .addReg(LHS1).addImm(0));
7792 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7793 .addReg(LHS2).addImm(0)
7794 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7796 unsigned RHS1 = MI->getOperand(3).getReg();
7797 unsigned RHS2 = MI->getOperand(4).getReg();
7798 AddDefaultPred(BuildMI(BB, dl,
7799 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7800 .addReg(LHS1).addReg(RHS1));
7801 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7802 .addReg(LHS2).addReg(RHS2)
7803 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7806 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7807 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7808 if (MI->getOperand(0).getImm() == ARMCC::NE)
7809 std::swap(destMBB, exitMBB);
7811 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7812 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7814 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7816 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7818 MI->eraseFromParent(); // The pseudo instruction is gone now.
7822 case ARM::Int_eh_sjlj_setjmp:
7823 case ARM::Int_eh_sjlj_setjmp_nofp:
7824 case ARM::tInt_eh_sjlj_setjmp:
7825 case ARM::t2Int_eh_sjlj_setjmp:
7826 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7827 EmitSjLjDispatchBlock(MI, BB);
7832 // To insert an ABS instruction, we have to insert the
7833 // diamond control-flow pattern. The incoming instruction knows the
7834 // source vreg to test against 0, the destination vreg to set,
7835 // the condition code register to branch on, the
7836 // true/false values to select between, and a branch opcode to use.
7841 // BCC (branch to SinkBB if V0 >= 0)
7842 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7843 // SinkBB: V1 = PHI(V2, V3)
7844 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7845 MachineFunction::iterator BBI = BB;
7847 MachineFunction *Fn = BB->getParent();
7848 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7849 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7850 Fn->insert(BBI, RSBBB);
7851 Fn->insert(BBI, SinkBB);
7853 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7854 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7855 bool isThumb2 = Subtarget->isThumb2();
7856 MachineRegisterInfo &MRI = Fn->getRegInfo();
7857 // In Thumb mode S must not be specified if source register is the SP or
7858 // PC and if destination register is the SP, so restrict register class
7859 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7860 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7861 (const TargetRegisterClass*)&ARM::GPRRegClass);
7863 // Transfer the remainder of BB and its successor edges to sinkMBB.
7864 SinkBB->splice(SinkBB->begin(), BB,
7865 llvm::next(MachineBasicBlock::iterator(MI)),
7867 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7869 BB->addSuccessor(RSBBB);
7870 BB->addSuccessor(SinkBB);
7872 // fall through to SinkMBB
7873 RSBBB->addSuccessor(SinkBB);
7875 // insert a cmp at the end of BB
7876 AddDefaultPred(BuildMI(BB, dl,
7877 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7878 .addReg(ABSSrcReg).addImm(0));
7880 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7882 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7883 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7885 // insert rsbri in RSBBB
7886 // Note: BCC and rsbri will be converted into predicated rsbmi
7887 // by if-conversion pass
7888 BuildMI(*RSBBB, RSBBB->begin(), dl,
7889 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7890 .addReg(ABSSrcReg, RegState::Kill)
7891 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7893 // insert PHI in SinkBB,
7894 // reuse ABSDstReg to not change uses of ABS instruction
7895 BuildMI(*SinkBB, SinkBB->begin(), dl,
7896 TII->get(ARM::PHI), ABSDstReg)
7897 .addReg(NewRsbDstReg).addMBB(RSBBB)
7898 .addReg(ABSSrcReg).addMBB(BB);
7900 // remove ABS instruction
7901 MI->eraseFromParent();
7903 // return last added BB
7906 case ARM::COPY_STRUCT_BYVAL_I32:
7908 return EmitStructByval(MI, BB);
7912 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7913 SDNode *Node) const {
7914 if (!MI->hasPostISelHook()) {
7915 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7916 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7920 const MCInstrDesc *MCID = &MI->getDesc();
7921 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7922 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7923 // operand is still set to noreg. If needed, set the optional operand's
7924 // register to CPSR, and remove the redundant implicit def.
7926 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7928 // Rename pseudo opcodes.
7929 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7931 const ARMBaseInstrInfo *TII =
7932 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7933 MCID = &TII->get(NewOpc);
7935 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7936 "converted opcode should be the same except for cc_out");
7940 // Add the optional cc_out operand
7941 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7943 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7945 // Any ARM instruction that sets the 's' bit should specify an optional
7946 // "cc_out" operand in the last operand position.
7947 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7948 assert(!NewOpc && "Optional cc_out operand required");
7951 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7952 // since we already have an optional CPSR def.
7953 bool definesCPSR = false;
7954 bool deadCPSR = false;
7955 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7957 const MachineOperand &MO = MI->getOperand(i);
7958 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7962 MI->RemoveOperand(i);
7967 assert(!NewOpc && "Optional cc_out operand required");
7970 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7972 assert(!MI->getOperand(ccOutIdx).getReg() &&
7973 "expect uninitialized optional cc_out operand");
7977 // If this instruction was defined with an optional CPSR def and its dag node
7978 // had a live implicit CPSR def, then activate the optional CPSR def.
7979 MachineOperand &MO = MI->getOperand(ccOutIdx);
7980 MO.setReg(ARM::CPSR);
7984 //===----------------------------------------------------------------------===//
7985 // ARM Optimization Hooks
7986 //===----------------------------------------------------------------------===//
7988 // Helper function that checks if N is a null or all ones constant.
7989 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7990 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7993 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7996 // Return true if N is conditionally 0 or all ones.
7997 // Detects these expressions where cc is an i1 value:
7999 // (select cc 0, y) [AllOnes=0]
8000 // (select cc y, 0) [AllOnes=0]
8001 // (zext cc) [AllOnes=0]
8002 // (sext cc) [AllOnes=0/1]
8003 // (select cc -1, y) [AllOnes=1]
8004 // (select cc y, -1) [AllOnes=1]
8006 // Invert is set when N is the null/all ones constant when CC is false.
8007 // OtherOp is set to the alternative value of N.
8008 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8009 SDValue &CC, bool &Invert,
8011 SelectionDAG &DAG) {
8012 switch (N->getOpcode()) {
8013 default: return false;
8015 CC = N->getOperand(0);
8016 SDValue N1 = N->getOperand(1);
8017 SDValue N2 = N->getOperand(2);
8018 if (isZeroOrAllOnes(N1, AllOnes)) {
8023 if (isZeroOrAllOnes(N2, AllOnes)) {
8030 case ISD::ZERO_EXTEND:
8031 // (zext cc) can never be the all ones value.
8035 case ISD::SIGN_EXTEND: {
8036 EVT VT = N->getValueType(0);
8037 CC = N->getOperand(0);
8038 if (CC.getValueType() != MVT::i1)
8042 // When looking for an AllOnes constant, N is an sext, and the 'other'
8044 OtherOp = DAG.getConstant(0, VT);
8045 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8046 // When looking for a 0 constant, N can be zext or sext.
8047 OtherOp = DAG.getConstant(1, VT);
8049 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8055 // Combine a constant select operand into its use:
8057 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8058 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8059 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8060 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8061 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8063 // The transform is rejected if the select doesn't have a constant operand that
8064 // is null, or all ones when AllOnes is set.
8066 // Also recognize sext/zext from i1:
8068 // (add (zext cc), x) -> (select cc (add x, 1), x)
8069 // (add (sext cc), x) -> (select cc (add x, -1), x)
8071 // These transformations eventually create predicated instructions.
8073 // @param N The node to transform.
8074 // @param Slct The N operand that is a select.
8075 // @param OtherOp The other N operand (x above).
8076 // @param DCI Context.
8077 // @param AllOnes Require the select constant to be all ones instead of null.
8078 // @returns The new node, or SDValue() on failure.
8080 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8081 TargetLowering::DAGCombinerInfo &DCI,
8082 bool AllOnes = false) {
8083 SelectionDAG &DAG = DCI.DAG;
8084 EVT VT = N->getValueType(0);
8085 SDValue NonConstantVal;
8088 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8089 NonConstantVal, DAG))
8092 // Slct is now know to be the desired identity constant when CC is true.
8093 SDValue TrueVal = OtherOp;
8094 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8095 OtherOp, NonConstantVal);
8096 // Unless SwapSelectOps says CC should be false.
8098 std::swap(TrueVal, FalseVal);
8100 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8101 CCOp, TrueVal, FalseVal);
8104 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8106 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8107 TargetLowering::DAGCombinerInfo &DCI) {
8108 SDValue N0 = N->getOperand(0);
8109 SDValue N1 = N->getOperand(1);
8110 if (N0.getNode()->hasOneUse()) {
8111 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8112 if (Result.getNode())
8115 if (N1.getNode()->hasOneUse()) {
8116 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8117 if (Result.getNode())
8123 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8124 // (only after legalization).
8125 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8126 TargetLowering::DAGCombinerInfo &DCI,
8127 const ARMSubtarget *Subtarget) {
8129 // Only perform optimization if after legalize, and if NEON is available. We
8130 // also expected both operands to be BUILD_VECTORs.
8131 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8132 || N0.getOpcode() != ISD::BUILD_VECTOR
8133 || N1.getOpcode() != ISD::BUILD_VECTOR)
8136 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8137 EVT VT = N->getValueType(0);
8138 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8141 // Check that the vector operands are of the right form.
8142 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8143 // operands, where N is the size of the formed vector.
8144 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8145 // index such that we have a pair wise add pattern.
8147 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8148 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8150 SDValue Vec = N0->getOperand(0)->getOperand(0);
8151 SDNode *V = Vec.getNode();
8152 unsigned nextIndex = 0;
8154 // For each operands to the ADD which are BUILD_VECTORs,
8155 // check to see if each of their operands are an EXTRACT_VECTOR with
8156 // the same vector and appropriate index.
8157 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8158 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8159 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8161 SDValue ExtVec0 = N0->getOperand(i);
8162 SDValue ExtVec1 = N1->getOperand(i);
8164 // First operand is the vector, verify its the same.
8165 if (V != ExtVec0->getOperand(0).getNode() ||
8166 V != ExtVec1->getOperand(0).getNode())
8169 // Second is the constant, verify its correct.
8170 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8171 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8173 // For the constant, we want to see all the even or all the odd.
8174 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8175 || C1->getZExtValue() != nextIndex+1)
8184 // Create VPADDL node.
8185 SelectionDAG &DAG = DCI.DAG;
8186 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8188 // Build operand list.
8189 SmallVector<SDValue, 8> Ops;
8190 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8191 TLI.getPointerTy()));
8193 // Input is the vector.
8196 // Get widened type and narrowed type.
8198 unsigned numElem = VT.getVectorNumElements();
8199 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8200 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8201 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8202 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8204 llvm_unreachable("Invalid vector element type for padd optimization.");
8207 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8208 widenType, &Ops[0], Ops.size());
8209 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8212 static SDValue findMUL_LOHI(SDValue V) {
8213 if (V->getOpcode() == ISD::UMUL_LOHI ||
8214 V->getOpcode() == ISD::SMUL_LOHI)
8219 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8220 TargetLowering::DAGCombinerInfo &DCI,
8221 const ARMSubtarget *Subtarget) {
8223 if (Subtarget->isThumb1Only()) return SDValue();
8225 // Only perform the checks after legalize when the pattern is available.
8226 if (DCI.isBeforeLegalize()) return SDValue();
8228 // Look for multiply add opportunities.
8229 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8230 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8231 // a glue link from the first add to the second add.
8232 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8233 // a S/UMLAL instruction.
8236 // \ / \ [no multiline comment]
8242 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8243 SDValue AddcOp0 = AddcNode->getOperand(0);
8244 SDValue AddcOp1 = AddcNode->getOperand(1);
8246 // Check if the two operands are from the same mul_lohi node.
8247 if (AddcOp0.getNode() == AddcOp1.getNode())
8250 assert(AddcNode->getNumValues() == 2 &&
8251 AddcNode->getValueType(0) == MVT::i32 &&
8252 "Expect ADDC with two result values. First: i32");
8254 // Check that we have a glued ADDC node.
8255 if (AddcNode->getValueType(1) != MVT::Glue)
8258 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8259 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8260 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8261 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8262 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8265 // Look for the glued ADDE.
8266 SDNode* AddeNode = AddcNode->getGluedUser();
8267 if (AddeNode == NULL)
8270 // Make sure it is really an ADDE.
8271 if (AddeNode->getOpcode() != ISD::ADDE)
8274 assert(AddeNode->getNumOperands() == 3 &&
8275 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8276 "ADDE node has the wrong inputs");
8278 // Check for the triangle shape.
8279 SDValue AddeOp0 = AddeNode->getOperand(0);
8280 SDValue AddeOp1 = AddeNode->getOperand(1);
8282 // Make sure that the ADDE operands are not coming from the same node.
8283 if (AddeOp0.getNode() == AddeOp1.getNode())
8286 // Find the MUL_LOHI node walking up ADDE's operands.
8287 bool IsLeftOperandMUL = false;
8288 SDValue MULOp = findMUL_LOHI(AddeOp0);
8289 if (MULOp == SDValue())
8290 MULOp = findMUL_LOHI(AddeOp1);
8292 IsLeftOperandMUL = true;
8293 if (MULOp == SDValue())
8296 // Figure out the right opcode.
8297 unsigned Opc = MULOp->getOpcode();
8298 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8300 // Figure out the high and low input values to the MLAL node.
8301 SDValue* HiMul = &MULOp;
8302 SDValue* HiAdd = NULL;
8303 SDValue* LoMul = NULL;
8304 SDValue* LowAdd = NULL;
8306 if (IsLeftOperandMUL)
8312 if (AddcOp0->getOpcode() == Opc) {
8316 if (AddcOp1->getOpcode() == Opc) {
8324 if (LoMul->getNode() != HiMul->getNode())
8327 // Create the merged node.
8328 SelectionDAG &DAG = DCI.DAG;
8330 // Build operand list.
8331 SmallVector<SDValue, 8> Ops;
8332 Ops.push_back(LoMul->getOperand(0));
8333 Ops.push_back(LoMul->getOperand(1));
8334 Ops.push_back(*LowAdd);
8335 Ops.push_back(*HiAdd);
8337 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8338 DAG.getVTList(MVT::i32, MVT::i32),
8339 &Ops[0], Ops.size());
8341 // Replace the ADDs' nodes uses by the MLA node's values.
8342 SDValue HiMLALResult(MLALNode.getNode(), 1);
8343 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8345 SDValue LoMLALResult(MLALNode.getNode(), 0);
8346 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8348 // Return original node to notify the driver to stop replacing.
8349 SDValue resNode(AddcNode, 0);
8353 /// PerformADDCCombine - Target-specific dag combine transform from
8354 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8355 static SDValue PerformADDCCombine(SDNode *N,
8356 TargetLowering::DAGCombinerInfo &DCI,
8357 const ARMSubtarget *Subtarget) {
8359 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8363 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8364 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8365 /// called with the default operands, and if that fails, with commuted
8367 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8368 TargetLowering::DAGCombinerInfo &DCI,
8369 const ARMSubtarget *Subtarget){
8371 // Attempt to create vpaddl for this add.
8372 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8373 if (Result.getNode())
8376 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8377 if (N0.getNode()->hasOneUse()) {
8378 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8379 if (Result.getNode()) return Result;
8384 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8386 static SDValue PerformADDCombine(SDNode *N,
8387 TargetLowering::DAGCombinerInfo &DCI,
8388 const ARMSubtarget *Subtarget) {
8389 SDValue N0 = N->getOperand(0);
8390 SDValue N1 = N->getOperand(1);
8392 // First try with the default operand order.
8393 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8394 if (Result.getNode())
8397 // If that didn't work, try again with the operands commuted.
8398 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8401 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8403 static SDValue PerformSUBCombine(SDNode *N,
8404 TargetLowering::DAGCombinerInfo &DCI) {
8405 SDValue N0 = N->getOperand(0);
8406 SDValue N1 = N->getOperand(1);
8408 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8409 if (N1.getNode()->hasOneUse()) {
8410 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8411 if (Result.getNode()) return Result;
8417 /// PerformVMULCombine
8418 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8419 /// special multiplier accumulator forwarding.
8425 // However, for (A + B) * (A + B),
8432 static SDValue PerformVMULCombine(SDNode *N,
8433 TargetLowering::DAGCombinerInfo &DCI,
8434 const ARMSubtarget *Subtarget) {
8435 if (!Subtarget->hasVMLxForwarding())
8438 SelectionDAG &DAG = DCI.DAG;
8439 SDValue N0 = N->getOperand(0);
8440 SDValue N1 = N->getOperand(1);
8441 unsigned Opcode = N0.getOpcode();
8442 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8443 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8444 Opcode = N1.getOpcode();
8445 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8446 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8454 EVT VT = N->getValueType(0);
8456 SDValue N00 = N0->getOperand(0);
8457 SDValue N01 = N0->getOperand(1);
8458 return DAG.getNode(Opcode, DL, VT,
8459 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8460 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8463 static SDValue PerformMULCombine(SDNode *N,
8464 TargetLowering::DAGCombinerInfo &DCI,
8465 const ARMSubtarget *Subtarget) {
8466 SelectionDAG &DAG = DCI.DAG;
8468 if (Subtarget->isThumb1Only())
8471 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8474 EVT VT = N->getValueType(0);
8475 if (VT.is64BitVector() || VT.is128BitVector())
8476 return PerformVMULCombine(N, DCI, Subtarget);
8480 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8484 int64_t MulAmt = C->getSExtValue();
8485 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8487 ShiftAmt = ShiftAmt & (32 - 1);
8488 SDValue V = N->getOperand(0);
8492 MulAmt >>= ShiftAmt;
8495 if (isPowerOf2_32(MulAmt - 1)) {
8496 // (mul x, 2^N + 1) => (add (shl x, N), x)
8497 Res = DAG.getNode(ISD::ADD, DL, VT,
8499 DAG.getNode(ISD::SHL, DL, VT,
8501 DAG.getConstant(Log2_32(MulAmt - 1),
8503 } else if (isPowerOf2_32(MulAmt + 1)) {
8504 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8505 Res = DAG.getNode(ISD::SUB, DL, VT,
8506 DAG.getNode(ISD::SHL, DL, VT,
8508 DAG.getConstant(Log2_32(MulAmt + 1),
8514 uint64_t MulAmtAbs = -MulAmt;
8515 if (isPowerOf2_32(MulAmtAbs + 1)) {
8516 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8517 Res = DAG.getNode(ISD::SUB, DL, VT,
8519 DAG.getNode(ISD::SHL, DL, VT,
8521 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8523 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8524 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8525 Res = DAG.getNode(ISD::ADD, DL, VT,
8527 DAG.getNode(ISD::SHL, DL, VT,
8529 DAG.getConstant(Log2_32(MulAmtAbs-1),
8531 Res = DAG.getNode(ISD::SUB, DL, VT,
8532 DAG.getConstant(0, MVT::i32),Res);
8539 Res = DAG.getNode(ISD::SHL, DL, VT,
8540 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8542 // Do not add new nodes to DAG combiner worklist.
8543 DCI.CombineTo(N, Res, false);
8547 static SDValue PerformANDCombine(SDNode *N,
8548 TargetLowering::DAGCombinerInfo &DCI,
8549 const ARMSubtarget *Subtarget) {
8551 // Attempt to use immediate-form VBIC
8552 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8554 EVT VT = N->getValueType(0);
8555 SelectionDAG &DAG = DCI.DAG;
8557 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8560 APInt SplatBits, SplatUndef;
8561 unsigned SplatBitSize;
8564 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8565 if (SplatBitSize <= 64) {
8567 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8568 SplatUndef.getZExtValue(), SplatBitSize,
8569 DAG, VbicVT, VT.is128BitVector(),
8571 if (Val.getNode()) {
8573 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8574 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8575 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8580 if (!Subtarget->isThumb1Only()) {
8581 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8582 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8583 if (Result.getNode())
8590 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8591 static SDValue PerformORCombine(SDNode *N,
8592 TargetLowering::DAGCombinerInfo &DCI,
8593 const ARMSubtarget *Subtarget) {
8594 // Attempt to use immediate-form VORR
8595 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8597 EVT VT = N->getValueType(0);
8598 SelectionDAG &DAG = DCI.DAG;
8600 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8603 APInt SplatBits, SplatUndef;
8604 unsigned SplatBitSize;
8606 if (BVN && Subtarget->hasNEON() &&
8607 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8608 if (SplatBitSize <= 64) {
8610 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8611 SplatUndef.getZExtValue(), SplatBitSize,
8612 DAG, VorrVT, VT.is128BitVector(),
8614 if (Val.getNode()) {
8616 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8617 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8618 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8623 if (!Subtarget->isThumb1Only()) {
8624 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8625 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8626 if (Result.getNode())
8630 // The code below optimizes (or (and X, Y), Z).
8631 // The AND operand needs to have a single user to make these optimizations
8633 SDValue N0 = N->getOperand(0);
8634 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8636 SDValue N1 = N->getOperand(1);
8638 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8639 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8640 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8642 unsigned SplatBitSize;
8645 APInt SplatBits0, SplatBits1;
8646 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8647 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8648 // Ensure that the second operand of both ands are constants
8649 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8650 HasAnyUndefs) && !HasAnyUndefs) {
8651 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8652 HasAnyUndefs) && !HasAnyUndefs) {
8653 // Ensure that the bit width of the constants are the same and that
8654 // the splat arguments are logical inverses as per the pattern we
8655 // are trying to simplify.
8656 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8657 SplatBits0 == ~SplatBits1) {
8658 // Canonicalize the vector type to make instruction selection
8660 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8661 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8665 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8671 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8674 // BFI is only available on V6T2+
8675 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8679 // 1) or (and A, mask), val => ARMbfi A, val, mask
8680 // iff (val & mask) == val
8682 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8683 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8684 // && mask == ~mask2
8685 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8686 // && ~mask == mask2
8687 // (i.e., copy a bitfield value into another bitfield of the same width)
8692 SDValue N00 = N0.getOperand(0);
8694 // The value and the mask need to be constants so we can verify this is
8695 // actually a bitfield set. If the mask is 0xffff, we can do better
8696 // via a movt instruction, so don't use BFI in that case.
8697 SDValue MaskOp = N0.getOperand(1);
8698 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8701 unsigned Mask = MaskC->getZExtValue();
8705 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8706 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8708 unsigned Val = N1C->getZExtValue();
8709 if ((Val & ~Mask) != Val)
8712 if (ARM::isBitFieldInvertedMask(Mask)) {
8713 Val >>= countTrailingZeros(~Mask);
8715 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8716 DAG.getConstant(Val, MVT::i32),
8717 DAG.getConstant(Mask, MVT::i32));
8719 // Do not add new nodes to DAG combiner worklist.
8720 DCI.CombineTo(N, Res, false);
8723 } else if (N1.getOpcode() == ISD::AND) {
8724 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8725 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8728 unsigned Mask2 = N11C->getZExtValue();
8730 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8732 if (ARM::isBitFieldInvertedMask(Mask) &&
8734 // The pack halfword instruction works better for masks that fit it,
8735 // so use that when it's available.
8736 if (Subtarget->hasT2ExtractPack() &&
8737 (Mask == 0xffff || Mask == 0xffff0000))
8740 unsigned amt = countTrailingZeros(Mask2);
8741 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8742 DAG.getConstant(amt, MVT::i32));
8743 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8744 DAG.getConstant(Mask, MVT::i32));
8745 // Do not add new nodes to DAG combiner worklist.
8746 DCI.CombineTo(N, Res, false);
8748 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8750 // The pack halfword instruction works better for masks that fit it,
8751 // so use that when it's available.
8752 if (Subtarget->hasT2ExtractPack() &&
8753 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8756 unsigned lsb = countTrailingZeros(Mask);
8757 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8758 DAG.getConstant(lsb, MVT::i32));
8759 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8760 DAG.getConstant(Mask2, MVT::i32));
8761 // Do not add new nodes to DAG combiner worklist.
8762 DCI.CombineTo(N, Res, false);
8767 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8768 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8769 ARM::isBitFieldInvertedMask(~Mask)) {
8770 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8771 // where lsb(mask) == #shamt and masked bits of B are known zero.
8772 SDValue ShAmt = N00.getOperand(1);
8773 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8774 unsigned LSB = countTrailingZeros(Mask);
8778 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8779 DAG.getConstant(~Mask, MVT::i32));
8781 // Do not add new nodes to DAG combiner worklist.
8782 DCI.CombineTo(N, Res, false);
8788 static SDValue PerformXORCombine(SDNode *N,
8789 TargetLowering::DAGCombinerInfo &DCI,
8790 const ARMSubtarget *Subtarget) {
8791 EVT VT = N->getValueType(0);
8792 SelectionDAG &DAG = DCI.DAG;
8794 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8797 if (!Subtarget->isThumb1Only()) {
8798 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8799 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8800 if (Result.getNode())
8807 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8808 /// the bits being cleared by the AND are not demanded by the BFI.
8809 static SDValue PerformBFICombine(SDNode *N,
8810 TargetLowering::DAGCombinerInfo &DCI) {
8811 SDValue N1 = N->getOperand(1);
8812 if (N1.getOpcode() == ISD::AND) {
8813 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8816 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8817 unsigned LSB = countTrailingZeros(~InvMask);
8818 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8819 unsigned Mask = (1 << Width)-1;
8820 unsigned Mask2 = N11C->getZExtValue();
8821 if ((Mask & (~Mask2)) == 0)
8822 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8823 N->getOperand(0), N1.getOperand(0),
8829 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8830 /// ARMISD::VMOVRRD.
8831 static SDValue PerformVMOVRRDCombine(SDNode *N,
8832 TargetLowering::DAGCombinerInfo &DCI) {
8833 // vmovrrd(vmovdrr x, y) -> x,y
8834 SDValue InDouble = N->getOperand(0);
8835 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8836 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8838 // vmovrrd(load f64) -> (load i32), (load i32)
8839 SDNode *InNode = InDouble.getNode();
8840 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8841 InNode->getValueType(0) == MVT::f64 &&
8842 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8843 !cast<LoadSDNode>(InNode)->isVolatile()) {
8844 // TODO: Should this be done for non-FrameIndex operands?
8845 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8847 SelectionDAG &DAG = DCI.DAG;
8849 SDValue BasePtr = LD->getBasePtr();
8850 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8851 LD->getPointerInfo(), LD->isVolatile(),
8852 LD->isNonTemporal(), LD->isInvariant(),
8853 LD->getAlignment());
8855 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8856 DAG.getConstant(4, MVT::i32));
8857 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8858 LD->getPointerInfo(), LD->isVolatile(),
8859 LD->isNonTemporal(), LD->isInvariant(),
8860 std::min(4U, LD->getAlignment() / 2));
8862 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8863 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8864 DCI.RemoveFromWorklist(LD);
8872 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8873 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8874 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8875 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8876 SDValue Op0 = N->getOperand(0);
8877 SDValue Op1 = N->getOperand(1);
8878 if (Op0.getOpcode() == ISD::BITCAST)
8879 Op0 = Op0.getOperand(0);
8880 if (Op1.getOpcode() == ISD::BITCAST)
8881 Op1 = Op1.getOperand(0);
8882 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8883 Op0.getNode() == Op1.getNode() &&
8884 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8885 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8886 N->getValueType(0), Op0.getOperand(0));
8890 /// PerformSTORECombine - Target-specific dag combine xforms for
8892 static SDValue PerformSTORECombine(SDNode *N,
8893 TargetLowering::DAGCombinerInfo &DCI) {
8894 StoreSDNode *St = cast<StoreSDNode>(N);
8895 if (St->isVolatile())
8898 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8899 // pack all of the elements in one place. Next, store to memory in fewer
8901 SDValue StVal = St->getValue();
8902 EVT VT = StVal.getValueType();
8903 if (St->isTruncatingStore() && VT.isVector()) {
8904 SelectionDAG &DAG = DCI.DAG;
8905 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8906 EVT StVT = St->getMemoryVT();
8907 unsigned NumElems = VT.getVectorNumElements();
8908 assert(StVT != VT && "Cannot truncate to the same type");
8909 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8910 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8912 // From, To sizes and ElemCount must be pow of two
8913 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8915 // We are going to use the original vector elt for storing.
8916 // Accumulated smaller vector elements must be a multiple of the store size.
8917 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8919 unsigned SizeRatio = FromEltSz / ToEltSz;
8920 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8922 // Create a type on which we perform the shuffle.
8923 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8924 NumElems*SizeRatio);
8925 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8928 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8929 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8930 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8932 // Can't shuffle using an illegal type.
8933 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8935 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8936 DAG.getUNDEF(WideVec.getValueType()),
8938 // At this point all of the data is stored at the bottom of the
8939 // register. We now need to save it to mem.
8941 // Find the largest store unit
8942 MVT StoreType = MVT::i8;
8943 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8944 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8945 MVT Tp = (MVT::SimpleValueType)tp;
8946 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8949 // Didn't find a legal store type.
8950 if (!TLI.isTypeLegal(StoreType))
8953 // Bitcast the original vector into a vector of store-size units
8954 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8955 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8956 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8957 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8958 SmallVector<SDValue, 8> Chains;
8959 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8960 TLI.getPointerTy());
8961 SDValue BasePtr = St->getBasePtr();
8963 // Perform one or more big stores into memory.
8964 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8965 for (unsigned I = 0; I < E; I++) {
8966 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8967 StoreType, ShuffWide,
8968 DAG.getIntPtrConstant(I));
8969 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8970 St->getPointerInfo(), St->isVolatile(),
8971 St->isNonTemporal(), St->getAlignment());
8972 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8974 Chains.push_back(Ch);
8976 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8980 if (!ISD::isNormalStore(St))
8983 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8984 // ARM stores of arguments in the same cache line.
8985 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8986 StVal.getNode()->hasOneUse()) {
8987 SelectionDAG &DAG = DCI.DAG;
8989 SDValue BasePtr = St->getBasePtr();
8990 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8991 StVal.getNode()->getOperand(0), BasePtr,
8992 St->getPointerInfo(), St->isVolatile(),
8993 St->isNonTemporal(), St->getAlignment());
8995 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8996 DAG.getConstant(4, MVT::i32));
8997 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8998 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8999 St->isNonTemporal(),
9000 std::min(4U, St->getAlignment() / 2));
9003 if (StVal.getValueType() != MVT::i64 ||
9004 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9007 // Bitcast an i64 store extracted from a vector to f64.
9008 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9009 SelectionDAG &DAG = DCI.DAG;
9011 SDValue IntVec = StVal.getOperand(0);
9012 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9013 IntVec.getValueType().getVectorNumElements());
9014 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9015 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9016 Vec, StVal.getOperand(1));
9018 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9019 // Make the DAGCombiner fold the bitcasts.
9020 DCI.AddToWorklist(Vec.getNode());
9021 DCI.AddToWorklist(ExtElt.getNode());
9022 DCI.AddToWorklist(V.getNode());
9023 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9024 St->getPointerInfo(), St->isVolatile(),
9025 St->isNonTemporal(), St->getAlignment(),
9029 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9030 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9031 /// i64 vector to have f64 elements, since the value can then be loaded
9032 /// directly into a VFP register.
9033 static bool hasNormalLoadOperand(SDNode *N) {
9034 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9035 for (unsigned i = 0; i < NumElts; ++i) {
9036 SDNode *Elt = N->getOperand(i).getNode();
9037 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9043 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9044 /// ISD::BUILD_VECTOR.
9045 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9046 TargetLowering::DAGCombinerInfo &DCI){
9047 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9048 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9049 // into a pair of GPRs, which is fine when the value is used as a scalar,
9050 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9051 SelectionDAG &DAG = DCI.DAG;
9052 if (N->getNumOperands() == 2) {
9053 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9058 // Load i64 elements as f64 values so that type legalization does not split
9059 // them up into i32 values.
9060 EVT VT = N->getValueType(0);
9061 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9064 SmallVector<SDValue, 8> Ops;
9065 unsigned NumElts = VT.getVectorNumElements();
9066 for (unsigned i = 0; i < NumElts; ++i) {
9067 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9069 // Make the DAGCombiner fold the bitcast.
9070 DCI.AddToWorklist(V.getNode());
9072 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9073 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9074 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9077 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9079 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9080 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9081 // At that time, we may have inserted bitcasts from integer to float.
9082 // If these bitcasts have survived DAGCombine, change the lowering of this
9083 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9084 // force to use floating point types.
9086 // Make sure we can change the type of the vector.
9087 // This is possible iff:
9088 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9089 // 1.1. Vector is used only once.
9090 // 1.2. Use is a bit convert to an integer type.
9091 // 2. The size of its operands are 32-bits (64-bits are not legal).
9092 EVT VT = N->getValueType(0);
9093 EVT EltVT = VT.getVectorElementType();
9095 // Check 1.1. and 2.
9096 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9099 // By construction, the input type must be float.
9100 assert(EltVT == MVT::f32 && "Unexpected type!");
9103 SDNode *Use = *N->use_begin();
9104 if (Use->getOpcode() != ISD::BITCAST ||
9105 Use->getValueType(0).isFloatingPoint())
9108 // Check profitability.
9109 // Model is, if more than half of the relevant operands are bitcast from
9110 // i32, turn the build_vector into a sequence of insert_vector_elt.
9111 // Relevant operands are everything that is not statically
9112 // (i.e., at compile time) bitcasted.
9113 unsigned NumOfBitCastedElts = 0;
9114 unsigned NumElts = VT.getVectorNumElements();
9115 unsigned NumOfRelevantElts = NumElts;
9116 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9117 SDValue Elt = N->getOperand(Idx);
9118 if (Elt->getOpcode() == ISD::BITCAST) {
9119 // Assume only bit cast to i32 will go away.
9120 if (Elt->getOperand(0).getValueType() == MVT::i32)
9121 ++NumOfBitCastedElts;
9122 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9123 // Constants are statically casted, thus do not count them as
9124 // relevant operands.
9125 --NumOfRelevantElts;
9128 // Check if more than half of the elements require a non-free bitcast.
9129 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9132 SelectionDAG &DAG = DCI.DAG;
9133 // Create the new vector type.
9134 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9135 // Check if the type is legal.
9136 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9137 if (!TLI.isTypeLegal(VecVT))
9141 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9142 // => BITCAST INSERT_VECTOR_ELT
9143 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9145 SDValue Vec = DAG.getUNDEF(VecVT);
9147 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9148 SDValue V = N->getOperand(Idx);
9149 if (V.getOpcode() == ISD::UNDEF)
9151 if (V.getOpcode() == ISD::BITCAST &&
9152 V->getOperand(0).getValueType() == MVT::i32)
9153 // Fold obvious case.
9154 V = V.getOperand(0);
9156 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9157 // Make the DAGCombiner fold the bitcasts.
9158 DCI.AddToWorklist(V.getNode());
9160 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9161 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9163 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9164 // Make the DAGCombiner fold the bitcasts.
9165 DCI.AddToWorklist(Vec.getNode());
9169 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9170 /// ISD::INSERT_VECTOR_ELT.
9171 static SDValue PerformInsertEltCombine(SDNode *N,
9172 TargetLowering::DAGCombinerInfo &DCI) {
9173 // Bitcast an i64 load inserted into a vector to f64.
9174 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9175 EVT VT = N->getValueType(0);
9176 SDNode *Elt = N->getOperand(1).getNode();
9177 if (VT.getVectorElementType() != MVT::i64 ||
9178 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9181 SelectionDAG &DAG = DCI.DAG;
9183 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9184 VT.getVectorNumElements());
9185 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9186 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9187 // Make the DAGCombiner fold the bitcasts.
9188 DCI.AddToWorklist(Vec.getNode());
9189 DCI.AddToWorklist(V.getNode());
9190 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9191 Vec, V, N->getOperand(2));
9192 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9195 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9196 /// ISD::VECTOR_SHUFFLE.
9197 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9198 // The LLVM shufflevector instruction does not require the shuffle mask
9199 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9200 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9201 // operands do not match the mask length, they are extended by concatenating
9202 // them with undef vectors. That is probably the right thing for other
9203 // targets, but for NEON it is better to concatenate two double-register
9204 // size vector operands into a single quad-register size vector. Do that
9205 // transformation here:
9206 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9207 // shuffle(concat(v1, v2), undef)
9208 SDValue Op0 = N->getOperand(0);
9209 SDValue Op1 = N->getOperand(1);
9210 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9211 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9212 Op0.getNumOperands() != 2 ||
9213 Op1.getNumOperands() != 2)
9215 SDValue Concat0Op1 = Op0.getOperand(1);
9216 SDValue Concat1Op1 = Op1.getOperand(1);
9217 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9218 Concat1Op1.getOpcode() != ISD::UNDEF)
9220 // Skip the transformation if any of the types are illegal.
9221 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9222 EVT VT = N->getValueType(0);
9223 if (!TLI.isTypeLegal(VT) ||
9224 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9225 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9228 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9229 Op0.getOperand(0), Op1.getOperand(0));
9230 // Translate the shuffle mask.
9231 SmallVector<int, 16> NewMask;
9232 unsigned NumElts = VT.getVectorNumElements();
9233 unsigned HalfElts = NumElts/2;
9234 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9235 for (unsigned n = 0; n < NumElts; ++n) {
9236 int MaskElt = SVN->getMaskElt(n);
9238 if (MaskElt < (int)HalfElts)
9240 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9241 NewElt = HalfElts + MaskElt - NumElts;
9242 NewMask.push_back(NewElt);
9244 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9245 DAG.getUNDEF(VT), NewMask.data());
9248 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9249 /// NEON load/store intrinsics to merge base address updates.
9250 static SDValue CombineBaseUpdate(SDNode *N,
9251 TargetLowering::DAGCombinerInfo &DCI) {
9252 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9255 SelectionDAG &DAG = DCI.DAG;
9256 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9257 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9258 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9259 SDValue Addr = N->getOperand(AddrOpIdx);
9261 // Search for a use of the address operand that is an increment.
9262 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9263 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9265 if (User->getOpcode() != ISD::ADD ||
9266 UI.getUse().getResNo() != Addr.getResNo())
9269 // Check that the add is independent of the load/store. Otherwise, folding
9270 // it would create a cycle.
9271 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9274 // Find the new opcode for the updating load/store.
9276 bool isLaneOp = false;
9277 unsigned NewOpc = 0;
9278 unsigned NumVecs = 0;
9280 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9282 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9283 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9285 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9287 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9289 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9291 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9292 NumVecs = 2; isLaneOp = true; break;
9293 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9294 NumVecs = 3; isLaneOp = true; break;
9295 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9296 NumVecs = 4; isLaneOp = true; break;
9297 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9298 NumVecs = 1; isLoad = false; break;
9299 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9300 NumVecs = 2; isLoad = false; break;
9301 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9302 NumVecs = 3; isLoad = false; break;
9303 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9304 NumVecs = 4; isLoad = false; break;
9305 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9306 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9307 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9308 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9309 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9310 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9314 switch (N->getOpcode()) {
9315 default: llvm_unreachable("unexpected opcode for Neon base update");
9316 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9317 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9318 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9322 // Find the size of memory referenced by the load/store.
9325 VecTy = N->getValueType(0);
9327 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9328 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9330 NumBytes /= VecTy.getVectorNumElements();
9332 // If the increment is a constant, it must match the memory ref size.
9333 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9334 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9335 uint64_t IncVal = CInc->getZExtValue();
9336 if (IncVal != NumBytes)
9338 } else if (NumBytes >= 3 * 16) {
9339 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9340 // separate instructions that make it harder to use a non-constant update.
9344 // Create the new updating load/store node.
9346 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9348 for (n = 0; n < NumResultVecs; ++n)
9350 Tys[n++] = MVT::i32;
9351 Tys[n] = MVT::Other;
9352 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9353 SmallVector<SDValue, 8> Ops;
9354 Ops.push_back(N->getOperand(0)); // incoming chain
9355 Ops.push_back(N->getOperand(AddrOpIdx));
9357 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9358 Ops.push_back(N->getOperand(i));
9360 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9361 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9362 Ops.data(), Ops.size(),
9363 MemInt->getMemoryVT(),
9364 MemInt->getMemOperand());
9367 std::vector<SDValue> NewResults;
9368 for (unsigned i = 0; i < NumResultVecs; ++i) {
9369 NewResults.push_back(SDValue(UpdN.getNode(), i));
9371 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9372 DCI.CombineTo(N, NewResults);
9373 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9380 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9381 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9382 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9384 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9385 SelectionDAG &DAG = DCI.DAG;
9386 EVT VT = N->getValueType(0);
9387 // vldN-dup instructions only support 64-bit vectors for N > 1.
9388 if (!VT.is64BitVector())
9391 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9392 SDNode *VLD = N->getOperand(0).getNode();
9393 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9395 unsigned NumVecs = 0;
9396 unsigned NewOpc = 0;
9397 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9398 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9400 NewOpc = ARMISD::VLD2DUP;
9401 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9403 NewOpc = ARMISD::VLD3DUP;
9404 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9406 NewOpc = ARMISD::VLD4DUP;
9411 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9412 // numbers match the load.
9413 unsigned VLDLaneNo =
9414 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9415 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9417 // Ignore uses of the chain result.
9418 if (UI.getUse().getResNo() == NumVecs)
9421 if (User->getOpcode() != ARMISD::VDUPLANE ||
9422 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9426 // Create the vldN-dup node.
9429 for (n = 0; n < NumVecs; ++n)
9431 Tys[n] = MVT::Other;
9432 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9433 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9434 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9435 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9436 Ops, 2, VLDMemInt->getMemoryVT(),
9437 VLDMemInt->getMemOperand());
9440 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9442 unsigned ResNo = UI.getUse().getResNo();
9443 // Ignore uses of the chain result.
9444 if (ResNo == NumVecs)
9447 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9450 // Now the vldN-lane intrinsic is dead except for its chain result.
9451 // Update uses of the chain.
9452 std::vector<SDValue> VLDDupResults;
9453 for (unsigned n = 0; n < NumVecs; ++n)
9454 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9455 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9456 DCI.CombineTo(VLD, VLDDupResults);
9461 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9462 /// ARMISD::VDUPLANE.
9463 static SDValue PerformVDUPLANECombine(SDNode *N,
9464 TargetLowering::DAGCombinerInfo &DCI) {
9465 SDValue Op = N->getOperand(0);
9467 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9468 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9469 if (CombineVLDDUP(N, DCI))
9470 return SDValue(N, 0);
9472 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9473 // redundant. Ignore bit_converts for now; element sizes are checked below.
9474 while (Op.getOpcode() == ISD::BITCAST)
9475 Op = Op.getOperand(0);
9476 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9479 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9480 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9481 // The canonical VMOV for a zero vector uses a 32-bit element size.
9482 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9484 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9486 EVT VT = N->getValueType(0);
9487 if (EltSize > VT.getVectorElementType().getSizeInBits())
9490 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9493 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9494 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9495 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9499 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9501 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9506 APFloat APF = C->getValueAPF();
9507 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9508 != APFloat::opOK || !isExact)
9511 c0 = (I == 0) ? cN : c0;
9512 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9519 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9520 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9521 /// when the VMUL has a constant operand that is a power of 2.
9523 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9524 /// vmul.f32 d16, d17, d16
9525 /// vcvt.s32.f32 d16, d16
9527 /// vcvt.s32.f32 d16, d16, #3
9528 static SDValue PerformVCVTCombine(SDNode *N,
9529 TargetLowering::DAGCombinerInfo &DCI,
9530 const ARMSubtarget *Subtarget) {
9531 SelectionDAG &DAG = DCI.DAG;
9532 SDValue Op = N->getOperand(0);
9534 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9535 Op.getOpcode() != ISD::FMUL)
9539 SDValue N0 = Op->getOperand(0);
9540 SDValue ConstVec = Op->getOperand(1);
9541 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9543 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9544 !isConstVecPow2(ConstVec, isSigned, C))
9547 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9548 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9549 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9550 // These instructions only exist converting from f32 to i32. We can handle
9551 // smaller integers by generating an extra truncate, but larger ones would
9556 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9557 Intrinsic::arm_neon_vcvtfp2fxu;
9558 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9559 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9560 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9561 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9562 DAG.getConstant(Log2_64(C), MVT::i32));
9564 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9565 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9570 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9571 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9572 /// when the VDIV has a constant operand that is a power of 2.
9574 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9575 /// vcvt.f32.s32 d16, d16
9576 /// vdiv.f32 d16, d17, d16
9578 /// vcvt.f32.s32 d16, d16, #3
9579 static SDValue PerformVDIVCombine(SDNode *N,
9580 TargetLowering::DAGCombinerInfo &DCI,
9581 const ARMSubtarget *Subtarget) {
9582 SelectionDAG &DAG = DCI.DAG;
9583 SDValue Op = N->getOperand(0);
9584 unsigned OpOpcode = Op.getNode()->getOpcode();
9586 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9587 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9591 SDValue ConstVec = N->getOperand(1);
9592 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9594 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9595 !isConstVecPow2(ConstVec, isSigned, C))
9598 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9599 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9600 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9601 // These instructions only exist converting from i32 to f32. We can handle
9602 // smaller integers by generating an extra extend, but larger ones would
9607 SDValue ConvInput = Op.getOperand(0);
9608 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9609 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9610 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9611 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9614 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9615 Intrinsic::arm_neon_vcvtfxu2fp;
9616 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9618 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9619 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9622 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9623 /// operand of a vector shift operation, where all the elements of the
9624 /// build_vector must have the same constant integer value.
9625 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9626 // Ignore bit_converts.
9627 while (Op.getOpcode() == ISD::BITCAST)
9628 Op = Op.getOperand(0);
9629 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9630 APInt SplatBits, SplatUndef;
9631 unsigned SplatBitSize;
9633 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9634 HasAnyUndefs, ElementBits) ||
9635 SplatBitSize > ElementBits)
9637 Cnt = SplatBits.getSExtValue();
9641 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9642 /// operand of a vector shift left operation. That value must be in the range:
9643 /// 0 <= Value < ElementBits for a left shift; or
9644 /// 0 <= Value <= ElementBits for a long left shift.
9645 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9646 assert(VT.isVector() && "vector shift count is not a vector type");
9647 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9648 if (! getVShiftImm(Op, ElementBits, Cnt))
9650 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9653 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9654 /// operand of a vector shift right operation. For a shift opcode, the value
9655 /// is positive, but for an intrinsic the value count must be negative. The
9656 /// absolute value must be in the range:
9657 /// 1 <= |Value| <= ElementBits for a right shift; or
9658 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9659 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9661 assert(VT.isVector() && "vector shift count is not a vector type");
9662 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9663 if (! getVShiftImm(Op, ElementBits, Cnt))
9667 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9670 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9671 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9672 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9675 // Don't do anything for most intrinsics.
9678 // Vector shifts: check for immediate versions and lower them.
9679 // Note: This is done during DAG combining instead of DAG legalizing because
9680 // the build_vectors for 64-bit vector element shift counts are generally
9681 // not legal, and it is hard to see their values after they get legalized to
9682 // loads from a constant pool.
9683 case Intrinsic::arm_neon_vshifts:
9684 case Intrinsic::arm_neon_vshiftu:
9685 case Intrinsic::arm_neon_vshiftls:
9686 case Intrinsic::arm_neon_vshiftlu:
9687 case Intrinsic::arm_neon_vshiftn:
9688 case Intrinsic::arm_neon_vrshifts:
9689 case Intrinsic::arm_neon_vrshiftu:
9690 case Intrinsic::arm_neon_vrshiftn:
9691 case Intrinsic::arm_neon_vqshifts:
9692 case Intrinsic::arm_neon_vqshiftu:
9693 case Intrinsic::arm_neon_vqshiftsu:
9694 case Intrinsic::arm_neon_vqshiftns:
9695 case Intrinsic::arm_neon_vqshiftnu:
9696 case Intrinsic::arm_neon_vqshiftnsu:
9697 case Intrinsic::arm_neon_vqrshiftns:
9698 case Intrinsic::arm_neon_vqrshiftnu:
9699 case Intrinsic::arm_neon_vqrshiftnsu: {
9700 EVT VT = N->getOperand(1).getValueType();
9702 unsigned VShiftOpc = 0;
9705 case Intrinsic::arm_neon_vshifts:
9706 case Intrinsic::arm_neon_vshiftu:
9707 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9708 VShiftOpc = ARMISD::VSHL;
9711 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9712 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9713 ARMISD::VSHRs : ARMISD::VSHRu);
9718 case Intrinsic::arm_neon_vshiftls:
9719 case Intrinsic::arm_neon_vshiftlu:
9720 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9722 llvm_unreachable("invalid shift count for vshll intrinsic");
9724 case Intrinsic::arm_neon_vrshifts:
9725 case Intrinsic::arm_neon_vrshiftu:
9726 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9730 case Intrinsic::arm_neon_vqshifts:
9731 case Intrinsic::arm_neon_vqshiftu:
9732 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9736 case Intrinsic::arm_neon_vqshiftsu:
9737 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9739 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9741 case Intrinsic::arm_neon_vshiftn:
9742 case Intrinsic::arm_neon_vrshiftn:
9743 case Intrinsic::arm_neon_vqshiftns:
9744 case Intrinsic::arm_neon_vqshiftnu:
9745 case Intrinsic::arm_neon_vqshiftnsu:
9746 case Intrinsic::arm_neon_vqrshiftns:
9747 case Intrinsic::arm_neon_vqrshiftnu:
9748 case Intrinsic::arm_neon_vqrshiftnsu:
9749 // Narrowing shifts require an immediate right shift.
9750 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9752 llvm_unreachable("invalid shift count for narrowing vector shift "
9756 llvm_unreachable("unhandled vector shift");
9760 case Intrinsic::arm_neon_vshifts:
9761 case Intrinsic::arm_neon_vshiftu:
9762 // Opcode already set above.
9764 case Intrinsic::arm_neon_vshiftls:
9765 case Intrinsic::arm_neon_vshiftlu:
9766 if (Cnt == VT.getVectorElementType().getSizeInBits())
9767 VShiftOpc = ARMISD::VSHLLi;
9769 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9770 ARMISD::VSHLLs : ARMISD::VSHLLu);
9772 case Intrinsic::arm_neon_vshiftn:
9773 VShiftOpc = ARMISD::VSHRN; break;
9774 case Intrinsic::arm_neon_vrshifts:
9775 VShiftOpc = ARMISD::VRSHRs; break;
9776 case Intrinsic::arm_neon_vrshiftu:
9777 VShiftOpc = ARMISD::VRSHRu; break;
9778 case Intrinsic::arm_neon_vrshiftn:
9779 VShiftOpc = ARMISD::VRSHRN; break;
9780 case Intrinsic::arm_neon_vqshifts:
9781 VShiftOpc = ARMISD::VQSHLs; break;
9782 case Intrinsic::arm_neon_vqshiftu:
9783 VShiftOpc = ARMISD::VQSHLu; break;
9784 case Intrinsic::arm_neon_vqshiftsu:
9785 VShiftOpc = ARMISD::VQSHLsu; break;
9786 case Intrinsic::arm_neon_vqshiftns:
9787 VShiftOpc = ARMISD::VQSHRNs; break;
9788 case Intrinsic::arm_neon_vqshiftnu:
9789 VShiftOpc = ARMISD::VQSHRNu; break;
9790 case Intrinsic::arm_neon_vqshiftnsu:
9791 VShiftOpc = ARMISD::VQSHRNsu; break;
9792 case Intrinsic::arm_neon_vqrshiftns:
9793 VShiftOpc = ARMISD::VQRSHRNs; break;
9794 case Intrinsic::arm_neon_vqrshiftnu:
9795 VShiftOpc = ARMISD::VQRSHRNu; break;
9796 case Intrinsic::arm_neon_vqrshiftnsu:
9797 VShiftOpc = ARMISD::VQRSHRNsu; break;
9800 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9801 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9804 case Intrinsic::arm_neon_vshiftins: {
9805 EVT VT = N->getOperand(1).getValueType();
9807 unsigned VShiftOpc = 0;
9809 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9810 VShiftOpc = ARMISD::VSLI;
9811 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9812 VShiftOpc = ARMISD::VSRI;
9814 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9817 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9818 N->getOperand(1), N->getOperand(2),
9819 DAG.getConstant(Cnt, MVT::i32));
9822 case Intrinsic::arm_neon_vqrshifts:
9823 case Intrinsic::arm_neon_vqrshiftu:
9824 // No immediate versions of these to check for.
9831 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9832 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9833 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9834 /// vector element shift counts are generally not legal, and it is hard to see
9835 /// their values after they get legalized to loads from a constant pool.
9836 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9837 const ARMSubtarget *ST) {
9838 EVT VT = N->getValueType(0);
9839 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9840 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9841 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9842 SDValue N1 = N->getOperand(1);
9843 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9844 SDValue N0 = N->getOperand(0);
9845 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9846 DAG.MaskedValueIsZero(N0.getOperand(0),
9847 APInt::getHighBitsSet(32, 16)))
9848 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9852 // Nothing to be done for scalar shifts.
9853 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9854 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9857 assert(ST->hasNEON() && "unexpected vector shift");
9860 switch (N->getOpcode()) {
9861 default: llvm_unreachable("unexpected shift opcode");
9864 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9865 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9866 DAG.getConstant(Cnt, MVT::i32));
9871 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9872 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9873 ARMISD::VSHRs : ARMISD::VSHRu);
9874 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9875 DAG.getConstant(Cnt, MVT::i32));
9881 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9882 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9883 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9884 const ARMSubtarget *ST) {
9885 SDValue N0 = N->getOperand(0);
9887 // Check for sign- and zero-extensions of vector extract operations of 8-
9888 // and 16-bit vector elements. NEON supports these directly. They are
9889 // handled during DAG combining because type legalization will promote them
9890 // to 32-bit types and it is messy to recognize the operations after that.
9891 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9892 SDValue Vec = N0.getOperand(0);
9893 SDValue Lane = N0.getOperand(1);
9894 EVT VT = N->getValueType(0);
9895 EVT EltVT = N0.getValueType();
9896 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9898 if (VT == MVT::i32 &&
9899 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9900 TLI.isTypeLegal(Vec.getValueType()) &&
9901 isa<ConstantSDNode>(Lane)) {
9904 switch (N->getOpcode()) {
9905 default: llvm_unreachable("unexpected opcode");
9906 case ISD::SIGN_EXTEND:
9907 Opc = ARMISD::VGETLANEs;
9909 case ISD::ZERO_EXTEND:
9910 case ISD::ANY_EXTEND:
9911 Opc = ARMISD::VGETLANEu;
9914 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9921 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9922 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9923 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9924 const ARMSubtarget *ST) {
9925 // If the target supports NEON, try to use vmax/vmin instructions for f32
9926 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9927 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9928 // a NaN; only do the transformation when it matches that behavior.
9930 // For now only do this when using NEON for FP operations; if using VFP, it
9931 // is not obvious that the benefit outweighs the cost of switching to the
9933 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9934 N->getValueType(0) != MVT::f32)
9937 SDValue CondLHS = N->getOperand(0);
9938 SDValue CondRHS = N->getOperand(1);
9939 SDValue LHS = N->getOperand(2);
9940 SDValue RHS = N->getOperand(3);
9941 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9943 unsigned Opcode = 0;
9945 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9946 IsReversed = false; // x CC y ? x : y
9947 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9948 IsReversed = true ; // x CC y ? y : x
9962 // If LHS is NaN, an ordered comparison will be false and the result will
9963 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9964 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9965 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9966 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9968 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9969 // will return -0, so vmin can only be used for unsafe math or if one of
9970 // the operands is known to be nonzero.
9971 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9972 !DAG.getTarget().Options.UnsafeFPMath &&
9973 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9975 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9984 // If LHS is NaN, an ordered comparison will be false and the result will
9985 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9986 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9987 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9988 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9990 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9991 // will return +0, so vmax can only be used for unsafe math or if one of
9992 // the operands is known to be nonzero.
9993 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9994 !DAG.getTarget().Options.UnsafeFPMath &&
9995 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9997 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10003 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10006 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10008 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10009 SDValue Cmp = N->getOperand(4);
10010 if (Cmp.getOpcode() != ARMISD::CMPZ)
10011 // Only looking at EQ and NE cases.
10014 EVT VT = N->getValueType(0);
10016 SDValue LHS = Cmp.getOperand(0);
10017 SDValue RHS = Cmp.getOperand(1);
10018 SDValue FalseVal = N->getOperand(0);
10019 SDValue TrueVal = N->getOperand(1);
10020 SDValue ARMcc = N->getOperand(2);
10021 ARMCC::CondCodes CC =
10022 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10040 /// FIXME: Turn this into a target neutral optimization?
10042 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10043 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10044 N->getOperand(3), Cmp);
10045 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10047 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10048 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10049 N->getOperand(3), NewCmp);
10052 if (Res.getNode()) {
10053 APInt KnownZero, KnownOne;
10054 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10055 // Capture demanded bits information that would be otherwise lost.
10056 if (KnownZero == 0xfffffffe)
10057 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10058 DAG.getValueType(MVT::i1));
10059 else if (KnownZero == 0xffffff00)
10060 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10061 DAG.getValueType(MVT::i8));
10062 else if (KnownZero == 0xffff0000)
10063 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10064 DAG.getValueType(MVT::i16));
10070 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10071 DAGCombinerInfo &DCI) const {
10072 switch (N->getOpcode()) {
10074 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10075 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10076 case ISD::SUB: return PerformSUBCombine(N, DCI);
10077 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10078 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10079 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10080 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10081 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10082 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10083 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10084 case ISD::STORE: return PerformSTORECombine(N, DCI);
10085 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10086 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10087 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10088 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10089 case ISD::FP_TO_SINT:
10090 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10091 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10092 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10095 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10096 case ISD::SIGN_EXTEND:
10097 case ISD::ZERO_EXTEND:
10098 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10099 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10100 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10101 case ARMISD::VLD2DUP:
10102 case ARMISD::VLD3DUP:
10103 case ARMISD::VLD4DUP:
10104 return CombineBaseUpdate(N, DCI);
10105 case ARMISD::BUILD_VECTOR:
10106 return PerformARMBUILD_VECTORCombine(N, DCI);
10107 case ISD::INTRINSIC_VOID:
10108 case ISD::INTRINSIC_W_CHAIN:
10109 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10110 case Intrinsic::arm_neon_vld1:
10111 case Intrinsic::arm_neon_vld2:
10112 case Intrinsic::arm_neon_vld3:
10113 case Intrinsic::arm_neon_vld4:
10114 case Intrinsic::arm_neon_vld2lane:
10115 case Intrinsic::arm_neon_vld3lane:
10116 case Intrinsic::arm_neon_vld4lane:
10117 case Intrinsic::arm_neon_vst1:
10118 case Intrinsic::arm_neon_vst2:
10119 case Intrinsic::arm_neon_vst3:
10120 case Intrinsic::arm_neon_vst4:
10121 case Intrinsic::arm_neon_vst2lane:
10122 case Intrinsic::arm_neon_vst3lane:
10123 case Intrinsic::arm_neon_vst4lane:
10124 return CombineBaseUpdate(N, DCI);
10132 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10134 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10137 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10138 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10139 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10141 switch (VT.getSimpleVT().SimpleTy) {
10147 // Unaligned access can use (for example) LRDB, LRDH, LDR
10148 if (AllowsUnaligned) {
10150 *Fast = Subtarget->hasV7Ops();
10157 // For any little-endian targets with neon, we can support unaligned ld/st
10158 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10159 // A big-endian target may also explictly support unaligned accesses
10160 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10170 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10171 unsigned AlignCheck) {
10172 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10173 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10176 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10177 unsigned DstAlign, unsigned SrcAlign,
10178 bool IsMemset, bool ZeroMemset,
10180 MachineFunction &MF) const {
10181 const Function *F = MF.getFunction();
10183 // See if we can use NEON instructions for this...
10184 if ((!IsMemset || ZeroMemset) &&
10185 Subtarget->hasNEON() &&
10186 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10187 Attribute::NoImplicitFloat)) {
10190 (memOpAlign(SrcAlign, DstAlign, 16) ||
10191 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10193 } else if (Size >= 8 &&
10194 (memOpAlign(SrcAlign, DstAlign, 8) ||
10195 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10200 // Lowering to i32/i16 if the size permits.
10203 else if (Size >= 2)
10206 // Let the target-independent logic figure it out.
10210 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10211 if (Val.getOpcode() != ISD::LOAD)
10214 EVT VT1 = Val.getValueType();
10215 if (!VT1.isSimple() || !VT1.isInteger() ||
10216 !VT2.isSimple() || !VT2.isInteger())
10219 switch (VT1.getSimpleVT().SimpleTy) {
10224 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10231 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10232 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10235 if (!isTypeLegal(EVT::getEVT(Ty1)))
10238 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10240 // Assuming the caller doesn't have a zeroext or signext return parameter,
10241 // truncation all the way down to i1 is valid.
10246 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10250 unsigned Scale = 1;
10251 switch (VT.getSimpleVT().SimpleTy) {
10252 default: return false;
10267 if ((V & (Scale - 1)) != 0)
10270 return V == (V & ((1LL << 5) - 1));
10273 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10274 const ARMSubtarget *Subtarget) {
10275 bool isNeg = false;
10281 switch (VT.getSimpleVT().SimpleTy) {
10282 default: return false;
10287 // + imm12 or - imm8
10289 return V == (V & ((1LL << 8) - 1));
10290 return V == (V & ((1LL << 12) - 1));
10293 // Same as ARM mode. FIXME: NEON?
10294 if (!Subtarget->hasVFP2())
10299 return V == (V & ((1LL << 8) - 1));
10303 /// isLegalAddressImmediate - Return true if the integer value can be used
10304 /// as the offset of the target addressing mode for load / store of the
10306 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10307 const ARMSubtarget *Subtarget) {
10311 if (!VT.isSimple())
10314 if (Subtarget->isThumb1Only())
10315 return isLegalT1AddressImmediate(V, VT);
10316 else if (Subtarget->isThumb2())
10317 return isLegalT2AddressImmediate(V, VT, Subtarget);
10322 switch (VT.getSimpleVT().SimpleTy) {
10323 default: return false;
10328 return V == (V & ((1LL << 12) - 1));
10331 return V == (V & ((1LL << 8) - 1));
10334 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10339 return V == (V & ((1LL << 8) - 1));
10343 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10345 int Scale = AM.Scale;
10349 switch (VT.getSimpleVT().SimpleTy) {
10350 default: return false;
10358 Scale = Scale & ~1;
10359 return Scale == 2 || Scale == 4 || Scale == 8;
10362 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10366 // Note, we allow "void" uses (basically, uses that aren't loads or
10367 // stores), because arm allows folding a scale into many arithmetic
10368 // operations. This should be made more precise and revisited later.
10370 // Allow r << imm, but the imm has to be a multiple of two.
10371 if (Scale & 1) return false;
10372 return isPowerOf2_32(Scale);
10376 /// isLegalAddressingMode - Return true if the addressing mode represented
10377 /// by AM is legal for this target, for a load/store of the specified type.
10378 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10380 EVT VT = getValueType(Ty, true);
10381 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10384 // Can never fold addr of global into load/store.
10388 switch (AM.Scale) {
10389 case 0: // no scale reg, must be "r+i" or "r", or "i".
10392 if (Subtarget->isThumb1Only())
10396 // ARM doesn't support any R+R*scale+imm addr modes.
10400 if (!VT.isSimple())
10403 if (Subtarget->isThumb2())
10404 return isLegalT2ScaledAddressingMode(AM, VT);
10406 int Scale = AM.Scale;
10407 switch (VT.getSimpleVT().SimpleTy) {
10408 default: return false;
10412 if (Scale < 0) Scale = -Scale;
10416 return isPowerOf2_32(Scale & ~1);
10420 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10425 // Note, we allow "void" uses (basically, uses that aren't loads or
10426 // stores), because arm allows folding a scale into many arithmetic
10427 // operations. This should be made more precise and revisited later.
10429 // Allow r << imm, but the imm has to be a multiple of two.
10430 if (Scale & 1) return false;
10431 return isPowerOf2_32(Scale);
10437 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10438 /// icmp immediate, that is the target has icmp instructions which can compare
10439 /// a register against the immediate without having to materialize the
10440 /// immediate into a register.
10441 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10442 // Thumb2 and ARM modes can use cmn for negative immediates.
10443 if (!Subtarget->isThumb())
10444 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10445 if (Subtarget->isThumb2())
10446 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10447 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10448 return Imm >= 0 && Imm <= 255;
10451 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10452 /// *or sub* immediate, that is the target has add or sub instructions which can
10453 /// add a register with the immediate without having to materialize the
10454 /// immediate into a register.
10455 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10456 // Same encoding for add/sub, just flip the sign.
10457 int64_t AbsImm = llvm::abs64(Imm);
10458 if (!Subtarget->isThumb())
10459 return ARM_AM::getSOImmVal(AbsImm) != -1;
10460 if (Subtarget->isThumb2())
10461 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10462 // Thumb1 only has 8-bit unsigned immediate.
10463 return AbsImm >= 0 && AbsImm <= 255;
10466 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10467 bool isSEXTLoad, SDValue &Base,
10468 SDValue &Offset, bool &isInc,
10469 SelectionDAG &DAG) {
10470 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10473 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10474 // AddressingMode 3
10475 Base = Ptr->getOperand(0);
10476 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10477 int RHSC = (int)RHS->getZExtValue();
10478 if (RHSC < 0 && RHSC > -256) {
10479 assert(Ptr->getOpcode() == ISD::ADD);
10481 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10485 isInc = (Ptr->getOpcode() == ISD::ADD);
10486 Offset = Ptr->getOperand(1);
10488 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10489 // AddressingMode 2
10490 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10491 int RHSC = (int)RHS->getZExtValue();
10492 if (RHSC < 0 && RHSC > -0x1000) {
10493 assert(Ptr->getOpcode() == ISD::ADD);
10495 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10496 Base = Ptr->getOperand(0);
10501 if (Ptr->getOpcode() == ISD::ADD) {
10503 ARM_AM::ShiftOpc ShOpcVal=
10504 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10505 if (ShOpcVal != ARM_AM::no_shift) {
10506 Base = Ptr->getOperand(1);
10507 Offset = Ptr->getOperand(0);
10509 Base = Ptr->getOperand(0);
10510 Offset = Ptr->getOperand(1);
10515 isInc = (Ptr->getOpcode() == ISD::ADD);
10516 Base = Ptr->getOperand(0);
10517 Offset = Ptr->getOperand(1);
10521 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10525 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10526 bool isSEXTLoad, SDValue &Base,
10527 SDValue &Offset, bool &isInc,
10528 SelectionDAG &DAG) {
10529 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10532 Base = Ptr->getOperand(0);
10533 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10534 int RHSC = (int)RHS->getZExtValue();
10535 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10536 assert(Ptr->getOpcode() == ISD::ADD);
10538 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10540 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10541 isInc = Ptr->getOpcode() == ISD::ADD;
10542 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10550 /// getPreIndexedAddressParts - returns true by value, base pointer and
10551 /// offset pointer and addressing mode by reference if the node's address
10552 /// can be legally represented as pre-indexed load / store address.
10554 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10556 ISD::MemIndexedMode &AM,
10557 SelectionDAG &DAG) const {
10558 if (Subtarget->isThumb1Only())
10563 bool isSEXTLoad = false;
10564 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10565 Ptr = LD->getBasePtr();
10566 VT = LD->getMemoryVT();
10567 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10568 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10569 Ptr = ST->getBasePtr();
10570 VT = ST->getMemoryVT();
10575 bool isLegal = false;
10576 if (Subtarget->isThumb2())
10577 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10578 Offset, isInc, DAG);
10580 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10581 Offset, isInc, DAG);
10585 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10589 /// getPostIndexedAddressParts - returns true by value, base pointer and
10590 /// offset pointer and addressing mode by reference if this node can be
10591 /// combined with a load / store to form a post-indexed load / store.
10592 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10595 ISD::MemIndexedMode &AM,
10596 SelectionDAG &DAG) const {
10597 if (Subtarget->isThumb1Only())
10602 bool isSEXTLoad = false;
10603 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10604 VT = LD->getMemoryVT();
10605 Ptr = LD->getBasePtr();
10606 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10607 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10608 VT = ST->getMemoryVT();
10609 Ptr = ST->getBasePtr();
10614 bool isLegal = false;
10615 if (Subtarget->isThumb2())
10616 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10619 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10625 // Swap base ptr and offset to catch more post-index load / store when
10626 // it's legal. In Thumb2 mode, offset must be an immediate.
10627 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10628 !Subtarget->isThumb2())
10629 std::swap(Base, Offset);
10631 // Post-indexed load / store update the base pointer.
10636 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10640 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10643 const SelectionDAG &DAG,
10644 unsigned Depth) const {
10645 unsigned BitWidth = KnownOne.getBitWidth();
10646 KnownZero = KnownOne = APInt(BitWidth, 0);
10647 switch (Op.getOpcode()) {
10653 // These nodes' second result is a boolean
10654 if (Op.getResNo() == 0)
10656 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10658 case ARMISD::CMOV: {
10659 // Bits are known zero/one if known on the LHS and RHS.
10660 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10661 if (KnownZero == 0 && KnownOne == 0) return;
10663 APInt KnownZeroRHS, KnownOneRHS;
10664 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10665 KnownZero &= KnownZeroRHS;
10666 KnownOne &= KnownOneRHS;
10672 //===----------------------------------------------------------------------===//
10673 // ARM Inline Assembly Support
10674 //===----------------------------------------------------------------------===//
10676 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10677 // Looking for "rev" which is V6+.
10678 if (!Subtarget->hasV6Ops())
10681 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10682 std::string AsmStr = IA->getAsmString();
10683 SmallVector<StringRef, 4> AsmPieces;
10684 SplitString(AsmStr, AsmPieces, ";\n");
10686 switch (AsmPieces.size()) {
10687 default: return false;
10689 AsmStr = AsmPieces[0];
10691 SplitString(AsmStr, AsmPieces, " \t,");
10694 if (AsmPieces.size() == 3 &&
10695 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10696 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10697 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10698 if (Ty && Ty->getBitWidth() == 32)
10699 return IntrinsicLowering::LowerToByteSwap(CI);
10707 /// getConstraintType - Given a constraint letter, return the type of
10708 /// constraint it is for this target.
10709 ARMTargetLowering::ConstraintType
10710 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10711 if (Constraint.size() == 1) {
10712 switch (Constraint[0]) {
10714 case 'l': return C_RegisterClass;
10715 case 'w': return C_RegisterClass;
10716 case 'h': return C_RegisterClass;
10717 case 'x': return C_RegisterClass;
10718 case 't': return C_RegisterClass;
10719 case 'j': return C_Other; // Constant for movw.
10720 // An address with a single base register. Due to the way we
10721 // currently handle addresses it is the same as an 'r' memory constraint.
10722 case 'Q': return C_Memory;
10724 } else if (Constraint.size() == 2) {
10725 switch (Constraint[0]) {
10727 // All 'U+' constraints are addresses.
10728 case 'U': return C_Memory;
10731 return TargetLowering::getConstraintType(Constraint);
10734 /// Examine constraint type and operand type and determine a weight value.
10735 /// This object must already have been set up with the operand type
10736 /// and the current alternative constraint selected.
10737 TargetLowering::ConstraintWeight
10738 ARMTargetLowering::getSingleConstraintMatchWeight(
10739 AsmOperandInfo &info, const char *constraint) const {
10740 ConstraintWeight weight = CW_Invalid;
10741 Value *CallOperandVal = info.CallOperandVal;
10742 // If we don't have a value, we can't do a match,
10743 // but allow it at the lowest weight.
10744 if (CallOperandVal == NULL)
10746 Type *type = CallOperandVal->getType();
10747 // Look at the constraint type.
10748 switch (*constraint) {
10750 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10753 if (type->isIntegerTy()) {
10754 if (Subtarget->isThumb())
10755 weight = CW_SpecificReg;
10757 weight = CW_Register;
10761 if (type->isFloatingPointTy())
10762 weight = CW_Register;
10768 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10770 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10772 if (Constraint.size() == 1) {
10773 // GCC ARM Constraint Letters
10774 switch (Constraint[0]) {
10775 case 'l': // Low regs or general regs.
10776 if (Subtarget->isThumb())
10777 return RCPair(0U, &ARM::tGPRRegClass);
10778 return RCPair(0U, &ARM::GPRRegClass);
10779 case 'h': // High regs or no regs.
10780 if (Subtarget->isThumb())
10781 return RCPair(0U, &ARM::hGPRRegClass);
10784 return RCPair(0U, &ARM::GPRRegClass);
10786 if (VT == MVT::f32)
10787 return RCPair(0U, &ARM::SPRRegClass);
10788 if (VT.getSizeInBits() == 64)
10789 return RCPair(0U, &ARM::DPRRegClass);
10790 if (VT.getSizeInBits() == 128)
10791 return RCPair(0U, &ARM::QPRRegClass);
10794 if (VT == MVT::f32)
10795 return RCPair(0U, &ARM::SPR_8RegClass);
10796 if (VT.getSizeInBits() == 64)
10797 return RCPair(0U, &ARM::DPR_8RegClass);
10798 if (VT.getSizeInBits() == 128)
10799 return RCPair(0U, &ARM::QPR_8RegClass);
10802 if (VT == MVT::f32)
10803 return RCPair(0U, &ARM::SPRRegClass);
10807 if (StringRef("{cc}").equals_lower(Constraint))
10808 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10810 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10813 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10814 /// vector. If it is invalid, don't add anything to Ops.
10815 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10816 std::string &Constraint,
10817 std::vector<SDValue>&Ops,
10818 SelectionDAG &DAG) const {
10819 SDValue Result(0, 0);
10821 // Currently only support length 1 constraints.
10822 if (Constraint.length() != 1) return;
10824 char ConstraintLetter = Constraint[0];
10825 switch (ConstraintLetter) {
10828 case 'I': case 'J': case 'K': case 'L':
10829 case 'M': case 'N': case 'O':
10830 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10834 int64_t CVal64 = C->getSExtValue();
10835 int CVal = (int) CVal64;
10836 // None of these constraints allow values larger than 32 bits. Check
10837 // that the value fits in an int.
10838 if (CVal != CVal64)
10841 switch (ConstraintLetter) {
10843 // Constant suitable for movw, must be between 0 and
10845 if (Subtarget->hasV6T2Ops())
10846 if (CVal >= 0 && CVal <= 65535)
10850 if (Subtarget->isThumb1Only()) {
10851 // This must be a constant between 0 and 255, for ADD
10853 if (CVal >= 0 && CVal <= 255)
10855 } else if (Subtarget->isThumb2()) {
10856 // A constant that can be used as an immediate value in a
10857 // data-processing instruction.
10858 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10861 // A constant that can be used as an immediate value in a
10862 // data-processing instruction.
10863 if (ARM_AM::getSOImmVal(CVal) != -1)
10869 if (Subtarget->isThumb()) { // FIXME thumb2
10870 // This must be a constant between -255 and -1, for negated ADD
10871 // immediates. This can be used in GCC with an "n" modifier that
10872 // prints the negated value, for use with SUB instructions. It is
10873 // not useful otherwise but is implemented for compatibility.
10874 if (CVal >= -255 && CVal <= -1)
10877 // This must be a constant between -4095 and 4095. It is not clear
10878 // what this constraint is intended for. Implemented for
10879 // compatibility with GCC.
10880 if (CVal >= -4095 && CVal <= 4095)
10886 if (Subtarget->isThumb1Only()) {
10887 // A 32-bit value where only one byte has a nonzero value. Exclude
10888 // zero to match GCC. This constraint is used by GCC internally for
10889 // constants that can be loaded with a move/shift combination.
10890 // It is not useful otherwise but is implemented for compatibility.
10891 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10893 } else if (Subtarget->isThumb2()) {
10894 // A constant whose bitwise inverse can be used as an immediate
10895 // value in a data-processing instruction. This can be used in GCC
10896 // with a "B" modifier that prints the inverted value, for use with
10897 // BIC and MVN instructions. It is not useful otherwise but is
10898 // implemented for compatibility.
10899 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10902 // A constant whose bitwise inverse can be used as an immediate
10903 // value in a data-processing instruction. This can be used in GCC
10904 // with a "B" modifier that prints the inverted value, for use with
10905 // BIC and MVN instructions. It is not useful otherwise but is
10906 // implemented for compatibility.
10907 if (ARM_AM::getSOImmVal(~CVal) != -1)
10913 if (Subtarget->isThumb1Only()) {
10914 // This must be a constant between -7 and 7,
10915 // for 3-operand ADD/SUB immediate instructions.
10916 if (CVal >= -7 && CVal < 7)
10918 } else if (Subtarget->isThumb2()) {
10919 // A constant whose negation can be used as an immediate value in a
10920 // data-processing instruction. This can be used in GCC with an "n"
10921 // modifier that prints the negated value, for use with SUB
10922 // instructions. It is not useful otherwise but is implemented for
10924 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10927 // A constant whose negation can be used as an immediate value in a
10928 // data-processing instruction. This can be used in GCC with an "n"
10929 // modifier that prints the negated value, for use with SUB
10930 // instructions. It is not useful otherwise but is implemented for
10932 if (ARM_AM::getSOImmVal(-CVal) != -1)
10938 if (Subtarget->isThumb()) { // FIXME thumb2
10939 // This must be a multiple of 4 between 0 and 1020, for
10940 // ADD sp + immediate.
10941 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10944 // A power of two or a constant between 0 and 32. This is used in
10945 // GCC for the shift amount on shifted register operands, but it is
10946 // useful in general for any shift amounts.
10947 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10953 if (Subtarget->isThumb()) { // FIXME thumb2
10954 // This must be a constant between 0 and 31, for shift amounts.
10955 if (CVal >= 0 && CVal <= 31)
10961 if (Subtarget->isThumb()) { // FIXME thumb2
10962 // This must be a multiple of 4 between -508 and 508, for
10963 // ADD/SUB sp = sp + immediate.
10964 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10969 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10973 if (Result.getNode()) {
10974 Ops.push_back(Result);
10977 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10980 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10981 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10982 unsigned Opcode = Op->getOpcode();
10983 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10984 "Invalid opcode for Div/Rem lowering");
10985 bool isSigned = (Opcode == ISD::SDIVREM);
10986 EVT VT = Op->getValueType(0);
10987 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10990 switch (VT.getSimpleVT().SimpleTy) {
10991 default: llvm_unreachable("Unexpected request for libcall!");
10992 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10993 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10994 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10995 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10998 SDValue InChain = DAG.getEntryNode();
11000 TargetLowering::ArgListTy Args;
11001 TargetLowering::ArgListEntry Entry;
11002 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11003 EVT ArgVT = Op->getOperand(i).getValueType();
11004 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11005 Entry.Node = Op->getOperand(i);
11007 Entry.isSExt = isSigned;
11008 Entry.isZExt = !isSigned;
11009 Args.push_back(Entry);
11012 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11015 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11019 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11020 0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11021 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11022 Callee, Args, DAG, dl);
11023 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11025 return CallInfo.first;
11029 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11030 // The ARM target isn't yet aware of offsets.
11034 bool ARM::isBitFieldInvertedMask(unsigned v) {
11035 if (v == 0xffffffff)
11038 // there can be 1's on either or both "outsides", all the "inside"
11039 // bits must be 0's
11040 unsigned TO = CountTrailingOnes_32(v);
11041 unsigned LO = CountLeadingOnes_32(v);
11042 v = (v >> TO) << TO;
11043 v = (v << LO) >> LO;
11047 /// isFPImmLegal - Returns true if the target can instruction select the
11048 /// specified FP immediate natively. If false, the legalizer will
11049 /// materialize the FP immediate as a load from a constant pool.
11050 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11051 if (!Subtarget->hasVFP3())
11053 if (VT == MVT::f32)
11054 return ARM_AM::getFP32Imm(Imm) != -1;
11055 if (VT == MVT::f64)
11056 return ARM_AM::getFP64Imm(Imm) != -1;
11060 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11061 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11062 /// specified in the intrinsic calls.
11063 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11065 unsigned Intrinsic) const {
11066 switch (Intrinsic) {
11067 case Intrinsic::arm_neon_vld1:
11068 case Intrinsic::arm_neon_vld2:
11069 case Intrinsic::arm_neon_vld3:
11070 case Intrinsic::arm_neon_vld4:
11071 case Intrinsic::arm_neon_vld2lane:
11072 case Intrinsic::arm_neon_vld3lane:
11073 case Intrinsic::arm_neon_vld4lane: {
11074 Info.opc = ISD::INTRINSIC_W_CHAIN;
11075 // Conservatively set memVT to the entire set of vectors loaded.
11076 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11077 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11078 Info.ptrVal = I.getArgOperand(0);
11080 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11081 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11082 Info.vol = false; // volatile loads with NEON intrinsics not supported
11083 Info.readMem = true;
11084 Info.writeMem = false;
11087 case Intrinsic::arm_neon_vst1:
11088 case Intrinsic::arm_neon_vst2:
11089 case Intrinsic::arm_neon_vst3:
11090 case Intrinsic::arm_neon_vst4:
11091 case Intrinsic::arm_neon_vst2lane:
11092 case Intrinsic::arm_neon_vst3lane:
11093 case Intrinsic::arm_neon_vst4lane: {
11094 Info.opc = ISD::INTRINSIC_VOID;
11095 // Conservatively set memVT to the entire set of vectors stored.
11096 unsigned NumElts = 0;
11097 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11098 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11099 if (!ArgTy->isVectorTy())
11101 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11103 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11104 Info.ptrVal = I.getArgOperand(0);
11106 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11107 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11108 Info.vol = false; // volatile stores with NEON intrinsics not supported
11109 Info.readMem = false;
11110 Info.writeMem = true;
11113 case Intrinsic::arm_ldrex: {
11114 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11115 Info.opc = ISD::INTRINSIC_W_CHAIN;
11116 Info.memVT = MVT::getVT(PtrTy->getElementType());
11117 Info.ptrVal = I.getArgOperand(0);
11119 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11121 Info.readMem = true;
11122 Info.writeMem = false;
11125 case Intrinsic::arm_strex: {
11126 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11127 Info.opc = ISD::INTRINSIC_W_CHAIN;
11128 Info.memVT = MVT::getVT(PtrTy->getElementType());
11129 Info.ptrVal = I.getArgOperand(1);
11131 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11133 Info.readMem = false;
11134 Info.writeMem = true;
11137 case Intrinsic::arm_strexd: {
11138 Info.opc = ISD::INTRINSIC_W_CHAIN;
11139 Info.memVT = MVT::i64;
11140 Info.ptrVal = I.getArgOperand(2);
11144 Info.readMem = false;
11145 Info.writeMem = true;
11148 case Intrinsic::arm_ldrexd: {
11149 Info.opc = ISD::INTRINSIC_W_CHAIN;
11150 Info.memVT = MVT::i64;
11151 Info.ptrVal = I.getArgOperand(0);
11155 Info.readMem = true;
11156 Info.writeMem = false;