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 // Combine sin / cos into one node or libcall if possible.
874 if (Subtarget->hasSinCos()) {
875 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
876 setLibcallName(RTLIB::SINCOS_F64, "sincos");
877 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
878 // For iOS, we don't want to the normal expansion of a libcall to
879 // sincos. We want to issue a libcall to __sincos_stret.
880 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
881 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
885 // We have target-specific dag combine patterns for the following nodes:
886 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
887 setTargetDAGCombine(ISD::ADD);
888 setTargetDAGCombine(ISD::SUB);
889 setTargetDAGCombine(ISD::MUL);
890 setTargetDAGCombine(ISD::AND);
891 setTargetDAGCombine(ISD::OR);
892 setTargetDAGCombine(ISD::XOR);
894 if (Subtarget->hasV6Ops())
895 setTargetDAGCombine(ISD::SRL);
897 setStackPointerRegisterToSaveRestore(ARM::SP);
899 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
900 !Subtarget->hasVFP2())
901 setSchedulingPreference(Sched::RegPressure);
903 setSchedulingPreference(Sched::Hybrid);
905 //// temporary - rewrite interface to use type
906 MaxStoresPerMemset = 8;
907 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
908 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
909 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
910 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
911 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
913 // On ARM arguments smaller than 4 bytes are extended, so all arguments
914 // are at least 4 bytes aligned.
915 setMinStackArgumentAlignment(4);
917 // Prefer likely predicted branches to selects on out-of-order cores.
918 PredictableSelectIsExpensive = Subtarget->isLikeA9();
920 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
923 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
924 bool isThumb2, unsigned &LdrOpc,
926 static const unsigned LoadBares[4][2] = {{ARM::LDREXB, ARM::t2LDREXB},
927 {ARM::LDREXH, ARM::t2LDREXH},
928 {ARM::LDREX, ARM::t2LDREX},
929 {ARM::LDREXD, ARM::t2LDREXD}};
930 static const unsigned LoadAcqs[4][2] = {{ARM::LDAEXB, ARM::t2LDAEXB},
931 {ARM::LDAEXH, ARM::t2LDAEXH},
932 {ARM::LDAEX, ARM::t2LDAEX},
933 {ARM::LDAEXD, ARM::t2LDAEXD}};
934 static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
935 {ARM::STREXH, ARM::t2STREXH},
936 {ARM::STREX, ARM::t2STREX},
937 {ARM::STREXD, ARM::t2STREXD}};
938 static const unsigned StoreRels[4][2] = {{ARM::STLEXB, ARM::t2STLEXB},
939 {ARM::STLEXH, ARM::t2STLEXH},
940 {ARM::STLEX, ARM::t2STLEX},
941 {ARM::STLEXD, ARM::t2STLEXD}};
943 const unsigned (*LoadOps)[2], (*StoreOps)[2];
944 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
949 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
950 StoreOps = StoreRels;
952 StoreOps = StoreBares;
954 assert(isPowerOf2_32(Size) && Size <= 8 &&
955 "unsupported size for atomic binary op!");
957 LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
958 StrOpc = StoreOps[Log2_32(Size)][isThumb2];
961 // FIXME: It might make sense to define the representative register class as the
962 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
963 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
964 // SPR's representative would be DPR_VFP2. This should work well if register
965 // pressure tracking were modified such that a register use would increment the
966 // pressure of the register class's representative and all of it's super
967 // classes' representatives transitively. We have not implemented this because
968 // of the difficulty prior to coalescing of modeling operand register classes
969 // due to the common occurrence of cross class copies and subregister insertions
971 std::pair<const TargetRegisterClass*, uint8_t>
972 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
973 const TargetRegisterClass *RRC = 0;
975 switch (VT.SimpleTy) {
977 return TargetLowering::findRepresentativeClass(VT);
978 // Use DPR as representative register class for all floating point
979 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
980 // the cost is 1 for both f32 and f64.
981 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
982 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
983 RRC = &ARM::DPRRegClass;
984 // When NEON is used for SP, only half of the register file is available
985 // because operations that define both SP and DP results will be constrained
986 // to the VFP2 class (D0-D15). We currently model this constraint prior to
987 // coalescing by double-counting the SP regs. See the FIXME above.
988 if (Subtarget->useNEONForSinglePrecisionFP())
991 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
992 case MVT::v4f32: case MVT::v2f64:
993 RRC = &ARM::DPRRegClass;
997 RRC = &ARM::DPRRegClass;
1001 RRC = &ARM::DPRRegClass;
1005 return std::make_pair(RRC, Cost);
1008 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1011 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1012 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1013 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1014 case ARMISD::CALL: return "ARMISD::CALL";
1015 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1016 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1017 case ARMISD::tCALL: return "ARMISD::tCALL";
1018 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1019 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1020 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1021 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1022 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1023 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1024 case ARMISD::CMP: return "ARMISD::CMP";
1025 case ARMISD::CMN: return "ARMISD::CMN";
1026 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1027 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1028 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1029 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1030 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1032 case ARMISD::CMOV: return "ARMISD::CMOV";
1034 case ARMISD::RBIT: return "ARMISD::RBIT";
1036 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1037 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1038 case ARMISD::SITOF: return "ARMISD::SITOF";
1039 case ARMISD::UITOF: return "ARMISD::UITOF";
1041 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1042 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1043 case ARMISD::RRX: return "ARMISD::RRX";
1045 case ARMISD::ADDC: return "ARMISD::ADDC";
1046 case ARMISD::ADDE: return "ARMISD::ADDE";
1047 case ARMISD::SUBC: return "ARMISD::SUBC";
1048 case ARMISD::SUBE: return "ARMISD::SUBE";
1050 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1051 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1053 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1054 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1056 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1058 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1060 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1062 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1064 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1066 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1067 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1068 case ARMISD::VCGE: return "ARMISD::VCGE";
1069 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1070 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1071 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1072 case ARMISD::VCGT: return "ARMISD::VCGT";
1073 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1074 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1075 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1076 case ARMISD::VTST: return "ARMISD::VTST";
1078 case ARMISD::VSHL: return "ARMISD::VSHL";
1079 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1080 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1081 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
1082 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
1083 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
1084 case ARMISD::VSHRN: return "ARMISD::VSHRN";
1085 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1086 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1087 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1088 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1089 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1090 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1091 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1092 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1093 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1094 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1095 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1096 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1097 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1098 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1099 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1100 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1101 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1102 case ARMISD::VDUP: return "ARMISD::VDUP";
1103 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1104 case ARMISD::VEXT: return "ARMISD::VEXT";
1105 case ARMISD::VREV64: return "ARMISD::VREV64";
1106 case ARMISD::VREV32: return "ARMISD::VREV32";
1107 case ARMISD::VREV16: return "ARMISD::VREV16";
1108 case ARMISD::VZIP: return "ARMISD::VZIP";
1109 case ARMISD::VUZP: return "ARMISD::VUZP";
1110 case ARMISD::VTRN: return "ARMISD::VTRN";
1111 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1112 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1113 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1114 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1115 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1116 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1117 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1118 case ARMISD::FMAX: return "ARMISD::FMAX";
1119 case ARMISD::FMIN: return "ARMISD::FMIN";
1120 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1121 case ARMISD::VMINNM: return "ARMISD::VMIN";
1122 case ARMISD::BFI: return "ARMISD::BFI";
1123 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1124 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1125 case ARMISD::VBSL: return "ARMISD::VBSL";
1126 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1127 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1128 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1129 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1130 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1131 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1132 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1133 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1134 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1135 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1136 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1137 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1138 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1139 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1140 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1141 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1142 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1143 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1144 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1145 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1149 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1150 if (!VT.isVector()) return getPointerTy();
1151 return VT.changeVectorElementTypeToInteger();
1154 /// getRegClassFor - Return the register class that should be used for the
1155 /// specified value type.
1156 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1157 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1158 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1159 // load / store 4 to 8 consecutive D registers.
1160 if (Subtarget->hasNEON()) {
1161 if (VT == MVT::v4i64)
1162 return &ARM::QQPRRegClass;
1163 if (VT == MVT::v8i64)
1164 return &ARM::QQQQPRRegClass;
1166 return TargetLowering::getRegClassFor(VT);
1169 // Create a fast isel object.
1171 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1172 const TargetLibraryInfo *libInfo) const {
1173 return ARM::createFastISel(funcInfo, libInfo);
1176 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1177 /// be used for loads / stores from the global.
1178 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1179 return (Subtarget->isThumb1Only() ? 127 : 4095);
1182 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1183 unsigned NumVals = N->getNumValues();
1185 return Sched::RegPressure;
1187 for (unsigned i = 0; i != NumVals; ++i) {
1188 EVT VT = N->getValueType(i);
1189 if (VT == MVT::Glue || VT == MVT::Other)
1191 if (VT.isFloatingPoint() || VT.isVector())
1195 if (!N->isMachineOpcode())
1196 return Sched::RegPressure;
1198 // Load are scheduled for latency even if there instruction itinerary
1199 // is not available.
1200 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1201 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1203 if (MCID.getNumDefs() == 0)
1204 return Sched::RegPressure;
1205 if (!Itins->isEmpty() &&
1206 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1209 return Sched::RegPressure;
1212 //===----------------------------------------------------------------------===//
1214 //===----------------------------------------------------------------------===//
1216 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1217 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1219 default: llvm_unreachable("Unknown condition code!");
1220 case ISD::SETNE: return ARMCC::NE;
1221 case ISD::SETEQ: return ARMCC::EQ;
1222 case ISD::SETGT: return ARMCC::GT;
1223 case ISD::SETGE: return ARMCC::GE;
1224 case ISD::SETLT: return ARMCC::LT;
1225 case ISD::SETLE: return ARMCC::LE;
1226 case ISD::SETUGT: return ARMCC::HI;
1227 case ISD::SETUGE: return ARMCC::HS;
1228 case ISD::SETULT: return ARMCC::LO;
1229 case ISD::SETULE: return ARMCC::LS;
1233 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1234 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1235 ARMCC::CondCodes &CondCode2) {
1236 CondCode2 = ARMCC::AL;
1238 default: llvm_unreachable("Unknown FP condition!");
1240 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1242 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1244 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1245 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1246 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1247 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1248 case ISD::SETO: CondCode = ARMCC::VC; break;
1249 case ISD::SETUO: CondCode = ARMCC::VS; break;
1250 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1251 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1252 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1254 case ISD::SETULT: CondCode = ARMCC::LT; break;
1256 case ISD::SETULE: CondCode = ARMCC::LE; break;
1258 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1262 //===----------------------------------------------------------------------===//
1263 // Calling Convention Implementation
1264 //===----------------------------------------------------------------------===//
1266 #include "ARMGenCallingConv.inc"
1268 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1269 /// given CallingConvention value.
1270 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1272 bool isVarArg) const {
1275 llvm_unreachable("Unsupported calling convention");
1276 case CallingConv::Fast:
1277 if (Subtarget->hasVFP2() && !isVarArg) {
1278 if (!Subtarget->isAAPCS_ABI())
1279 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1280 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1281 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1284 case CallingConv::C: {
1285 // Use target triple & subtarget features to do actual dispatch.
1286 if (!Subtarget->isAAPCS_ABI())
1287 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1288 else if (Subtarget->hasVFP2() &&
1289 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1291 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1292 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1294 case CallingConv::ARM_AAPCS_VFP:
1296 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1298 case CallingConv::ARM_AAPCS:
1299 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1300 case CallingConv::ARM_APCS:
1301 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1302 case CallingConv::GHC:
1303 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1307 /// LowerCallResult - Lower the result values of a call into the
1308 /// appropriate copies out of appropriate physical registers.
1310 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1311 CallingConv::ID CallConv, bool isVarArg,
1312 const SmallVectorImpl<ISD::InputArg> &Ins,
1313 SDLoc dl, SelectionDAG &DAG,
1314 SmallVectorImpl<SDValue> &InVals,
1315 bool isThisReturn, SDValue ThisVal) const {
1317 // Assign locations to each value returned by this call.
1318 SmallVector<CCValAssign, 16> RVLocs;
1319 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1320 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1321 CCInfo.AnalyzeCallResult(Ins,
1322 CCAssignFnForNode(CallConv, /* Return*/ true,
1325 // Copy all of the result registers out of their specified physreg.
1326 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1327 CCValAssign VA = RVLocs[i];
1329 // Pass 'this' value directly from the argument to return value, to avoid
1330 // reg unit interference
1331 if (i == 0 && isThisReturn) {
1332 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1333 "unexpected return calling convention register assignment");
1334 InVals.push_back(ThisVal);
1339 if (VA.needsCustom()) {
1340 // Handle f64 or half of a v2f64.
1341 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1343 Chain = Lo.getValue(1);
1344 InFlag = Lo.getValue(2);
1345 VA = RVLocs[++i]; // skip ahead to next loc
1346 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1348 Chain = Hi.getValue(1);
1349 InFlag = Hi.getValue(2);
1350 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1352 if (VA.getLocVT() == MVT::v2f64) {
1353 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1354 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1355 DAG.getConstant(0, MVT::i32));
1357 VA = RVLocs[++i]; // skip ahead to next loc
1358 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1359 Chain = Lo.getValue(1);
1360 InFlag = Lo.getValue(2);
1361 VA = RVLocs[++i]; // skip ahead to next loc
1362 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1363 Chain = Hi.getValue(1);
1364 InFlag = Hi.getValue(2);
1365 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1366 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1367 DAG.getConstant(1, MVT::i32));
1370 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1372 Chain = Val.getValue(1);
1373 InFlag = Val.getValue(2);
1376 switch (VA.getLocInfo()) {
1377 default: llvm_unreachable("Unknown loc info!");
1378 case CCValAssign::Full: break;
1379 case CCValAssign::BCvt:
1380 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1384 InVals.push_back(Val);
1390 /// LowerMemOpCallTo - Store the argument to the stack.
1392 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1393 SDValue StackPtr, SDValue Arg,
1394 SDLoc dl, SelectionDAG &DAG,
1395 const CCValAssign &VA,
1396 ISD::ArgFlagsTy Flags) const {
1397 unsigned LocMemOffset = VA.getLocMemOffset();
1398 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1399 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1400 return DAG.getStore(Chain, dl, Arg, PtrOff,
1401 MachinePointerInfo::getStack(LocMemOffset),
1405 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1406 SDValue Chain, SDValue &Arg,
1407 RegsToPassVector &RegsToPass,
1408 CCValAssign &VA, CCValAssign &NextVA,
1410 SmallVectorImpl<SDValue> &MemOpChains,
1411 ISD::ArgFlagsTy Flags) const {
1413 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1414 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1415 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1417 if (NextVA.isRegLoc())
1418 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1420 assert(NextVA.isMemLoc());
1421 if (StackPtr.getNode() == 0)
1422 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1424 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1430 /// LowerCall - Lowering a call into a callseq_start <-
1431 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1434 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1435 SmallVectorImpl<SDValue> &InVals) const {
1436 SelectionDAG &DAG = CLI.DAG;
1438 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1439 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1440 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1441 SDValue Chain = CLI.Chain;
1442 SDValue Callee = CLI.Callee;
1443 bool &isTailCall = CLI.IsTailCall;
1444 CallingConv::ID CallConv = CLI.CallConv;
1445 bool doesNotRet = CLI.DoesNotReturn;
1446 bool isVarArg = CLI.IsVarArg;
1448 MachineFunction &MF = DAG.getMachineFunction();
1449 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1450 bool isThisReturn = false;
1451 bool isSibCall = false;
1452 // Disable tail calls if they're not supported.
1453 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1456 // Check if it's really possible to do a tail call.
1457 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1458 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1459 Outs, OutVals, Ins, DAG);
1460 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1461 // detected sibcalls.
1468 // Analyze operands of the call, assigning locations to each operand.
1469 SmallVector<CCValAssign, 16> ArgLocs;
1470 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1471 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1472 CCInfo.AnalyzeCallOperands(Outs,
1473 CCAssignFnForNode(CallConv, /* Return*/ false,
1476 // Get a count of how many bytes are to be pushed on the stack.
1477 unsigned NumBytes = CCInfo.getNextStackOffset();
1479 // For tail calls, memory operands are available in our caller's stack.
1483 // Adjust the stack pointer for the new arguments...
1484 // These operations are automatically eliminated by the prolog/epilog pass
1486 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1489 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1491 RegsToPassVector RegsToPass;
1492 SmallVector<SDValue, 8> MemOpChains;
1494 // Walk the register/memloc assignments, inserting copies/loads. In the case
1495 // of tail call optimization, arguments are handled later.
1496 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1498 ++i, ++realArgIdx) {
1499 CCValAssign &VA = ArgLocs[i];
1500 SDValue Arg = OutVals[realArgIdx];
1501 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1502 bool isByVal = Flags.isByVal();
1504 // Promote the value if needed.
1505 switch (VA.getLocInfo()) {
1506 default: llvm_unreachable("Unknown loc info!");
1507 case CCValAssign::Full: break;
1508 case CCValAssign::SExt:
1509 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1511 case CCValAssign::ZExt:
1512 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1514 case CCValAssign::AExt:
1515 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1517 case CCValAssign::BCvt:
1518 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1522 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1523 if (VA.needsCustom()) {
1524 if (VA.getLocVT() == MVT::v2f64) {
1525 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1526 DAG.getConstant(0, MVT::i32));
1527 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1528 DAG.getConstant(1, MVT::i32));
1530 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1531 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1533 VA = ArgLocs[++i]; // skip ahead to next loc
1534 if (VA.isRegLoc()) {
1535 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1536 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1538 assert(VA.isMemLoc());
1540 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1541 dl, DAG, VA, Flags));
1544 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1545 StackPtr, MemOpChains, Flags);
1547 } else if (VA.isRegLoc()) {
1548 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1549 assert(VA.getLocVT() == MVT::i32 &&
1550 "unexpected calling convention register assignment");
1551 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1552 "unexpected use of 'returned'");
1553 isThisReturn = true;
1555 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1556 } else if (isByVal) {
1557 assert(VA.isMemLoc());
1558 unsigned offset = 0;
1560 // True if this byval aggregate will be split between registers
1562 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1563 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1565 if (CurByValIdx < ByValArgsCount) {
1567 unsigned RegBegin, RegEnd;
1568 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1570 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1572 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1573 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1574 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1575 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1576 MachinePointerInfo(),
1577 false, false, false,
1578 DAG.InferPtrAlignment(AddArg));
1579 MemOpChains.push_back(Load.getValue(1));
1580 RegsToPass.push_back(std::make_pair(j, Load));
1583 // If parameter size outsides register area, "offset" value
1584 // helps us to calculate stack slot for remained part properly.
1585 offset = RegEnd - RegBegin;
1587 CCInfo.nextInRegsParam();
1590 if (Flags.getByValSize() > 4*offset) {
1591 unsigned LocMemOffset = VA.getLocMemOffset();
1592 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1593 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1595 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1596 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1597 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1599 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1601 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1602 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1603 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1604 Ops, array_lengthof(Ops)));
1606 } else if (!isSibCall) {
1607 assert(VA.isMemLoc());
1609 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1610 dl, DAG, VA, Flags));
1614 if (!MemOpChains.empty())
1615 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1616 &MemOpChains[0], MemOpChains.size());
1618 // Build a sequence of copy-to-reg nodes chained together with token chain
1619 // and flag operands which copy the outgoing args into the appropriate regs.
1621 // Tail call byval lowering might overwrite argument registers so in case of
1622 // tail call optimization the copies to registers are lowered later.
1624 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1625 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1626 RegsToPass[i].second, InFlag);
1627 InFlag = Chain.getValue(1);
1630 // For tail calls lower the arguments to the 'real' stack slot.
1632 // Force all the incoming stack arguments to be loaded from the stack
1633 // before any new outgoing arguments are stored to the stack, because the
1634 // outgoing stack slots may alias the incoming argument stack slots, and
1635 // the alias isn't otherwise explicit. This is slightly more conservative
1636 // than necessary, because it means that each store effectively depends
1637 // on every argument instead of just those arguments it would clobber.
1639 // Do not flag preceding copytoreg stuff together with the following stuff.
1641 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1642 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1643 RegsToPass[i].second, InFlag);
1644 InFlag = Chain.getValue(1);
1649 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1650 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1651 // node so that legalize doesn't hack it.
1652 bool isDirect = false;
1653 bool isARMFunc = false;
1654 bool isLocalARMFunc = false;
1655 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1657 if (EnableARMLongCalls) {
1658 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1659 && "long-calls with non-static relocation model!");
1660 // Handle a global address or an external symbol. If it's not one of
1661 // those, the target's already in a register, so we don't need to do
1663 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1664 const GlobalValue *GV = G->getGlobal();
1665 // Create a constant pool entry for the callee address
1666 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1667 ARMConstantPoolValue *CPV =
1668 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1670 // Get the address of the callee into a register
1671 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1672 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1673 Callee = DAG.getLoad(getPointerTy(), dl,
1674 DAG.getEntryNode(), CPAddr,
1675 MachinePointerInfo::getConstantPool(),
1676 false, false, false, 0);
1677 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1678 const char *Sym = S->getSymbol();
1680 // Create a constant pool entry for the callee address
1681 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1682 ARMConstantPoolValue *CPV =
1683 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1684 ARMPCLabelIndex, 0);
1685 // Get the address of the callee into a register
1686 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1687 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1688 Callee = DAG.getLoad(getPointerTy(), dl,
1689 DAG.getEntryNode(), CPAddr,
1690 MachinePointerInfo::getConstantPool(),
1691 false, false, false, 0);
1693 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1694 const GlobalValue *GV = G->getGlobal();
1696 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1697 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1698 getTargetMachine().getRelocationModel() != Reloc::Static;
1699 isARMFunc = !Subtarget->isThumb() || isStub;
1700 // ARM call to a local ARM function is predicable.
1701 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1702 // tBX takes a register source operand.
1703 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1704 assert(Subtarget->isTargetDarwin() && "WrapperPIC use on non-Darwin?");
1705 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1706 DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1708 // On ELF targets for PIC code, direct calls should go through the PLT
1709 unsigned OpFlags = 0;
1710 if (Subtarget->isTargetELF() &&
1711 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1712 OpFlags = ARMII::MO_PLT;
1713 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1715 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1717 bool isStub = Subtarget->isTargetDarwin() &&
1718 getTargetMachine().getRelocationModel() != Reloc::Static;
1719 isARMFunc = !Subtarget->isThumb() || isStub;
1720 // tBX takes a register source operand.
1721 const char *Sym = S->getSymbol();
1722 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1723 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1724 ARMConstantPoolValue *CPV =
1725 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1726 ARMPCLabelIndex, 4);
1727 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1728 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1729 Callee = DAG.getLoad(getPointerTy(), dl,
1730 DAG.getEntryNode(), CPAddr,
1731 MachinePointerInfo::getConstantPool(),
1732 false, false, false, 0);
1733 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1734 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1735 getPointerTy(), Callee, PICLabel);
1737 unsigned OpFlags = 0;
1738 // On ELF targets for PIC code, direct calls should go through the PLT
1739 if (Subtarget->isTargetELF() &&
1740 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1741 OpFlags = ARMII::MO_PLT;
1742 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1746 // FIXME: handle tail calls differently.
1748 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1749 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1750 if (Subtarget->isThumb()) {
1751 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1752 CallOpc = ARMISD::CALL_NOLINK;
1754 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1756 if (!isDirect && !Subtarget->hasV5TOps())
1757 CallOpc = ARMISD::CALL_NOLINK;
1758 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1759 // Emit regular call when code size is the priority
1761 // "mov lr, pc; b _foo" to avoid confusing the RSP
1762 CallOpc = ARMISD::CALL_NOLINK;
1764 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1767 std::vector<SDValue> Ops;
1768 Ops.push_back(Chain);
1769 Ops.push_back(Callee);
1771 // Add argument registers to the end of the list so that they are known live
1773 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1774 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1775 RegsToPass[i].second.getValueType()));
1777 // Add a register mask operand representing the call-preserved registers.
1779 const uint32_t *Mask;
1780 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1781 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1783 // For 'this' returns, use the R0-preserving mask if applicable
1784 Mask = ARI->getThisReturnPreservedMask(CallConv);
1786 // Set isThisReturn to false if the calling convention is not one that
1787 // allows 'returned' to be modeled in this way, so LowerCallResult does
1788 // not try to pass 'this' straight through
1789 isThisReturn = false;
1790 Mask = ARI->getCallPreservedMask(CallConv);
1793 Mask = ARI->getCallPreservedMask(CallConv);
1795 assert(Mask && "Missing call preserved mask for calling convention");
1796 Ops.push_back(DAG.getRegisterMask(Mask));
1799 if (InFlag.getNode())
1800 Ops.push_back(InFlag);
1802 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1804 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1806 // Returns a chain and a flag for retval copy to use.
1807 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1808 InFlag = Chain.getValue(1);
1810 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1811 DAG.getIntPtrConstant(0, true), InFlag, dl);
1813 InFlag = Chain.getValue(1);
1815 // Handle result values, copying them out of physregs into vregs that we
1817 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1818 InVals, isThisReturn,
1819 isThisReturn ? OutVals[0] : SDValue());
1822 /// HandleByVal - Every parameter *after* a byval parameter is passed
1823 /// on the stack. Remember the next parameter register to allocate,
1824 /// and then confiscate the rest of the parameter registers to insure
1827 ARMTargetLowering::HandleByVal(
1828 CCState *State, unsigned &size, unsigned Align) const {
1829 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1830 assert((State->getCallOrPrologue() == Prologue ||
1831 State->getCallOrPrologue() == Call) &&
1832 "unhandled ParmContext");
1834 // For in-prologue parameters handling, we also introduce stack offset
1835 // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1836 // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1837 // NSAA should be evaluted (NSAA means "next stacked argument address").
1838 // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1839 // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1840 unsigned NSAAOffset = State->getNextStackOffset();
1841 if (State->getCallOrPrologue() != Call) {
1842 for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1844 State->getInRegsParamInfo(i, RB, RE);
1845 assert(NSAAOffset >= (RE-RB)*4 &&
1846 "Stack offset for byval regs doesn't introduced anymore?");
1847 NSAAOffset -= (RE-RB)*4;
1850 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1851 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1852 unsigned AlignInRegs = Align / 4;
1853 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1854 for (unsigned i = 0; i < Waste; ++i)
1855 reg = State->AllocateReg(GPRArgRegs, 4);
1858 unsigned excess = 4 * (ARM::R4 - reg);
1860 // Special case when NSAA != SP and parameter size greater than size of
1861 // all remained GPR regs. In that case we can't split parameter, we must
1862 // send it to stack. We also must set NCRN to R4, so waste all
1863 // remained registers.
1864 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1865 while (State->AllocateReg(GPRArgRegs, 4))
1870 // First register for byval parameter is the first register that wasn't
1871 // allocated before this method call, so it would be "reg".
1872 // If parameter is small enough to be saved in range [reg, r4), then
1873 // the end (first after last) register would be reg + param-size-in-regs,
1874 // else parameter would be splitted between registers and stack,
1875 // end register would be r4 in this case.
1876 unsigned ByValRegBegin = reg;
1877 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1878 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1879 // Note, first register is allocated in the beginning of function already,
1880 // allocate remained amount of registers we need.
1881 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1882 State->AllocateReg(GPRArgRegs, 4);
1883 // At a call site, a byval parameter that is split between
1884 // registers and memory needs its size truncated here. In a
1885 // function prologue, such byval parameters are reassembled in
1886 // memory, and are not truncated.
1887 if (State->getCallOrPrologue() == Call) {
1888 // Make remained size equal to 0 in case, when
1889 // the whole structure may be stored into registers.
1899 /// MatchingStackOffset - Return true if the given stack call argument is
1900 /// already available in the same position (relatively) of the caller's
1901 /// incoming argument stack.
1903 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1904 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1905 const TargetInstrInfo *TII) {
1906 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1908 if (Arg.getOpcode() == ISD::CopyFromReg) {
1909 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1910 if (!TargetRegisterInfo::isVirtualRegister(VR))
1912 MachineInstr *Def = MRI->getVRegDef(VR);
1915 if (!Flags.isByVal()) {
1916 if (!TII->isLoadFromStackSlot(Def, FI))
1921 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1922 if (Flags.isByVal())
1923 // ByVal argument is passed in as a pointer but it's now being
1924 // dereferenced. e.g.
1925 // define @foo(%struct.X* %A) {
1926 // tail call @bar(%struct.X* byval %A)
1929 SDValue Ptr = Ld->getBasePtr();
1930 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1933 FI = FINode->getIndex();
1937 assert(FI != INT_MAX);
1938 if (!MFI->isFixedObjectIndex(FI))
1940 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1943 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1944 /// for tail call optimization. Targets which want to do tail call
1945 /// optimization should implement this function.
1947 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1948 CallingConv::ID CalleeCC,
1950 bool isCalleeStructRet,
1951 bool isCallerStructRet,
1952 const SmallVectorImpl<ISD::OutputArg> &Outs,
1953 const SmallVectorImpl<SDValue> &OutVals,
1954 const SmallVectorImpl<ISD::InputArg> &Ins,
1955 SelectionDAG& DAG) const {
1956 const Function *CallerF = DAG.getMachineFunction().getFunction();
1957 CallingConv::ID CallerCC = CallerF->getCallingConv();
1958 bool CCMatch = CallerCC == CalleeCC;
1960 // Look for obvious safe cases to perform tail call optimization that do not
1961 // require ABI changes. This is what gcc calls sibcall.
1963 // Do not sibcall optimize vararg calls unless the call site is not passing
1965 if (isVarArg && !Outs.empty())
1968 // Exception-handling functions need a special set of instructions to indicate
1969 // a return to the hardware. Tail-calling another function would probably
1971 if (CallerF->hasFnAttribute("interrupt"))
1974 // Also avoid sibcall optimization if either caller or callee uses struct
1975 // return semantics.
1976 if (isCalleeStructRet || isCallerStructRet)
1979 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1980 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1981 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1982 // support in the assembler and linker to be used. This would need to be
1983 // fixed to fully support tail calls in Thumb1.
1985 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1986 // LR. This means if we need to reload LR, it takes an extra instructions,
1987 // which outweighs the value of the tail call; but here we don't know yet
1988 // whether LR is going to be used. Probably the right approach is to
1989 // generate the tail call here and turn it back into CALL/RET in
1990 // emitEpilogue if LR is used.
1992 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1993 // but we need to make sure there are enough registers; the only valid
1994 // registers are the 4 used for parameters. We don't currently do this
1996 if (Subtarget->isThumb1Only())
1999 // If the calling conventions do not match, then we'd better make sure the
2000 // results are returned in the same way as what the caller expects.
2002 SmallVector<CCValAssign, 16> RVLocs1;
2003 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2004 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2005 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2007 SmallVector<CCValAssign, 16> RVLocs2;
2008 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2009 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2010 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2012 if (RVLocs1.size() != RVLocs2.size())
2014 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2015 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2017 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2019 if (RVLocs1[i].isRegLoc()) {
2020 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2023 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2029 // If Caller's vararg or byval argument has been split between registers and
2030 // stack, do not perform tail call, since part of the argument is in caller's
2032 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2033 getInfo<ARMFunctionInfo>();
2034 if (AFI_Caller->getArgRegsSaveSize())
2037 // If the callee takes no arguments then go on to check the results of the
2039 if (!Outs.empty()) {
2040 // Check if stack adjustment is needed. For now, do not do this if any
2041 // argument is passed on the stack.
2042 SmallVector<CCValAssign, 16> ArgLocs;
2043 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2044 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2045 CCInfo.AnalyzeCallOperands(Outs,
2046 CCAssignFnForNode(CalleeCC, false, isVarArg));
2047 if (CCInfo.getNextStackOffset()) {
2048 MachineFunction &MF = DAG.getMachineFunction();
2050 // Check if the arguments are already laid out in the right way as
2051 // the caller's fixed stack objects.
2052 MachineFrameInfo *MFI = MF.getFrameInfo();
2053 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2054 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2055 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2057 ++i, ++realArgIdx) {
2058 CCValAssign &VA = ArgLocs[i];
2059 EVT RegVT = VA.getLocVT();
2060 SDValue Arg = OutVals[realArgIdx];
2061 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2062 if (VA.getLocInfo() == CCValAssign::Indirect)
2064 if (VA.needsCustom()) {
2065 // f64 and vector types are split into multiple registers or
2066 // register/stack-slot combinations. The types will not match
2067 // the registers; give up on memory f64 refs until we figure
2068 // out what to do about this.
2071 if (!ArgLocs[++i].isRegLoc())
2073 if (RegVT == MVT::v2f64) {
2074 if (!ArgLocs[++i].isRegLoc())
2076 if (!ArgLocs[++i].isRegLoc())
2079 } else if (!VA.isRegLoc()) {
2080 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2092 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2093 MachineFunction &MF, bool isVarArg,
2094 const SmallVectorImpl<ISD::OutputArg> &Outs,
2095 LLVMContext &Context) const {
2096 SmallVector<CCValAssign, 16> RVLocs;
2097 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2098 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2102 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2103 SDLoc DL, SelectionDAG &DAG) {
2104 const MachineFunction &MF = DAG.getMachineFunction();
2105 const Function *F = MF.getFunction();
2107 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2109 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2110 // version of the "preferred return address". These offsets affect the return
2111 // instruction if this is a return from PL1 without hypervisor extensions.
2112 // IRQ/FIQ: +4 "subs pc, lr, #4"
2113 // SWI: 0 "subs pc, lr, #0"
2114 // ABORT: +4 "subs pc, lr, #4"
2115 // UNDEF: +4/+2 "subs pc, lr, #0"
2116 // UNDEF varies depending on where the exception came from ARM or Thumb
2117 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2120 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2123 else if (IntKind == "SWI" || IntKind == "UNDEF")
2126 report_fatal_error("Unsupported interrupt attribute. If present, value "
2127 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2129 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2131 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2132 RetOps.data(), RetOps.size());
2136 ARMTargetLowering::LowerReturn(SDValue Chain,
2137 CallingConv::ID CallConv, bool isVarArg,
2138 const SmallVectorImpl<ISD::OutputArg> &Outs,
2139 const SmallVectorImpl<SDValue> &OutVals,
2140 SDLoc dl, SelectionDAG &DAG) const {
2142 // CCValAssign - represent the assignment of the return value to a location.
2143 SmallVector<CCValAssign, 16> RVLocs;
2145 // CCState - Info about the registers and stack slots.
2146 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2147 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2149 // Analyze outgoing return values.
2150 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2154 SmallVector<SDValue, 4> RetOps;
2155 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2157 // Copy the result values into the output registers.
2158 for (unsigned i = 0, realRVLocIdx = 0;
2160 ++i, ++realRVLocIdx) {
2161 CCValAssign &VA = RVLocs[i];
2162 assert(VA.isRegLoc() && "Can only return in registers!");
2164 SDValue Arg = OutVals[realRVLocIdx];
2166 switch (VA.getLocInfo()) {
2167 default: llvm_unreachable("Unknown loc info!");
2168 case CCValAssign::Full: break;
2169 case CCValAssign::BCvt:
2170 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2174 if (VA.needsCustom()) {
2175 if (VA.getLocVT() == MVT::v2f64) {
2176 // Extract the first half and return it in two registers.
2177 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2178 DAG.getConstant(0, MVT::i32));
2179 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2180 DAG.getVTList(MVT::i32, MVT::i32), Half);
2182 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2183 Flag = Chain.getValue(1);
2184 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2185 VA = RVLocs[++i]; // skip ahead to next loc
2186 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2187 HalfGPRs.getValue(1), Flag);
2188 Flag = Chain.getValue(1);
2189 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2190 VA = RVLocs[++i]; // skip ahead to next loc
2192 // Extract the 2nd half and fall through to handle it as an f64 value.
2193 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2194 DAG.getConstant(1, MVT::i32));
2196 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2198 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2199 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2200 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2201 Flag = Chain.getValue(1);
2202 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2203 VA = RVLocs[++i]; // skip ahead to next loc
2204 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2207 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2209 // Guarantee that all emitted copies are
2210 // stuck together, avoiding something bad.
2211 Flag = Chain.getValue(1);
2212 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2215 // Update chain and glue.
2218 RetOps.push_back(Flag);
2220 // CPUs which aren't M-class use a special sequence to return from
2221 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2222 // though we use "subs pc, lr, #N").
2224 // M-class CPUs actually use a normal return sequence with a special
2225 // (hardware-provided) value in LR, so the normal code path works.
2226 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2227 !Subtarget->isMClass()) {
2228 if (Subtarget->isThumb1Only())
2229 report_fatal_error("interrupt attribute is not supported in Thumb1");
2230 return LowerInterruptReturn(RetOps, dl, DAG);
2233 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2234 RetOps.data(), RetOps.size());
2237 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2238 if (N->getNumValues() != 1)
2240 if (!N->hasNUsesOfValue(1, 0))
2243 SDValue TCChain = Chain;
2244 SDNode *Copy = *N->use_begin();
2245 if (Copy->getOpcode() == ISD::CopyToReg) {
2246 // If the copy has a glue operand, we conservatively assume it isn't safe to
2247 // perform a tail call.
2248 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2250 TCChain = Copy->getOperand(0);
2251 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2252 SDNode *VMov = Copy;
2253 // f64 returned in a pair of GPRs.
2254 SmallPtrSet<SDNode*, 2> Copies;
2255 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2257 if (UI->getOpcode() != ISD::CopyToReg)
2261 if (Copies.size() > 2)
2264 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2266 SDValue UseChain = UI->getOperand(0);
2267 if (Copies.count(UseChain.getNode()))
2274 } else if (Copy->getOpcode() == ISD::BITCAST) {
2275 // f32 returned in a single GPR.
2276 if (!Copy->hasOneUse())
2278 Copy = *Copy->use_begin();
2279 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2281 TCChain = Copy->getOperand(0);
2286 bool HasRet = false;
2287 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2289 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2290 UI->getOpcode() != ARMISD::INTRET_FLAG)
2302 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2303 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2306 if (!CI->isTailCall())
2309 return !Subtarget->isThumb1Only();
2312 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2313 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2314 // one of the above mentioned nodes. It has to be wrapped because otherwise
2315 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2316 // be used to form addressing mode. These wrapped nodes will be selected
2318 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2319 EVT PtrVT = Op.getValueType();
2320 // FIXME there is no actual debug info here
2322 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2324 if (CP->isMachineConstantPoolEntry())
2325 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2326 CP->getAlignment());
2328 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2329 CP->getAlignment());
2330 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2333 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2334 return MachineJumpTableInfo::EK_Inline;
2337 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2338 SelectionDAG &DAG) const {
2339 MachineFunction &MF = DAG.getMachineFunction();
2340 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2341 unsigned ARMPCLabelIndex = 0;
2343 EVT PtrVT = getPointerTy();
2344 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2345 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2347 if (RelocM == Reloc::Static) {
2348 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2350 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2351 ARMPCLabelIndex = AFI->createPICLabelUId();
2352 ARMConstantPoolValue *CPV =
2353 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2354 ARMCP::CPBlockAddress, PCAdj);
2355 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2357 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2358 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2359 MachinePointerInfo::getConstantPool(),
2360 false, false, false, 0);
2361 if (RelocM == Reloc::Static)
2363 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2364 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2367 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2369 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2370 SelectionDAG &DAG) const {
2372 EVT PtrVT = getPointerTy();
2373 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2374 MachineFunction &MF = DAG.getMachineFunction();
2375 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2376 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2377 ARMConstantPoolValue *CPV =
2378 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2379 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2380 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2381 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2382 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2383 MachinePointerInfo::getConstantPool(),
2384 false, false, false, 0);
2385 SDValue Chain = Argument.getValue(1);
2387 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2388 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2390 // call __tls_get_addr.
2393 Entry.Node = Argument;
2394 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2395 Args.push_back(Entry);
2396 // FIXME: is there useful debug info available here?
2397 TargetLowering::CallLoweringInfo CLI(Chain,
2398 (Type *) Type::getInt32Ty(*DAG.getContext()),
2399 false, false, false, false,
2400 0, CallingConv::C, /*isTailCall=*/false,
2401 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2402 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2403 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2404 return CallResult.first;
2407 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2408 // "local exec" model.
2410 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2412 TLSModel::Model model) const {
2413 const GlobalValue *GV = GA->getGlobal();
2416 SDValue Chain = DAG.getEntryNode();
2417 EVT PtrVT = getPointerTy();
2418 // Get the Thread Pointer
2419 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2421 if (model == TLSModel::InitialExec) {
2422 MachineFunction &MF = DAG.getMachineFunction();
2423 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2424 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2425 // Initial exec model.
2426 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2427 ARMConstantPoolValue *CPV =
2428 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2429 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2431 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2432 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2433 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2434 MachinePointerInfo::getConstantPool(),
2435 false, false, false, 0);
2436 Chain = Offset.getValue(1);
2438 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2439 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2441 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2442 MachinePointerInfo::getConstantPool(),
2443 false, false, false, 0);
2446 assert(model == TLSModel::LocalExec);
2447 ARMConstantPoolValue *CPV =
2448 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2449 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2450 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2451 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2452 MachinePointerInfo::getConstantPool(),
2453 false, false, false, 0);
2456 // The address of the thread local variable is the add of the thread
2457 // pointer with the offset of the variable.
2458 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2462 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2463 // TODO: implement the "local dynamic" model
2464 assert(Subtarget->isTargetELF() &&
2465 "TLS not implemented for non-ELF targets");
2466 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2468 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2471 case TLSModel::GeneralDynamic:
2472 case TLSModel::LocalDynamic:
2473 return LowerToTLSGeneralDynamicModel(GA, DAG);
2474 case TLSModel::InitialExec:
2475 case TLSModel::LocalExec:
2476 return LowerToTLSExecModels(GA, DAG, model);
2478 llvm_unreachable("bogus TLS model");
2481 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2482 SelectionDAG &DAG) const {
2483 EVT PtrVT = getPointerTy();
2485 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2486 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2487 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2488 ARMConstantPoolValue *CPV =
2489 ARMConstantPoolConstant::Create(GV,
2490 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2491 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2492 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2493 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2495 MachinePointerInfo::getConstantPool(),
2496 false, false, false, 0);
2497 SDValue Chain = Result.getValue(1);
2498 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2499 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2501 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2502 MachinePointerInfo::getGOT(),
2503 false, false, false, 0);
2507 // If we have T2 ops, we can materialize the address directly via movt/movw
2508 // pair. This is always cheaper.
2509 if (Subtarget->useMovt()) {
2511 // FIXME: Once remat is capable of dealing with instructions with register
2512 // operands, expand this into two nodes.
2513 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2514 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2516 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2517 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2518 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2519 MachinePointerInfo::getConstantPool(),
2520 false, false, false, 0);
2524 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2525 SelectionDAG &DAG) const {
2526 EVT PtrVT = getPointerTy();
2528 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2529 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2531 if (Subtarget->useMovt())
2534 // FIXME: Once remat is capable of dealing with instructions with register
2535 // operands, expand this into multiple nodes
2537 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2539 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2540 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2542 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2543 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2544 MachinePointerInfo::getGOT(), false, false, false, 0);
2548 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2549 SelectionDAG &DAG) const {
2550 assert(Subtarget->isTargetELF() &&
2551 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2552 MachineFunction &MF = DAG.getMachineFunction();
2553 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2554 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2555 EVT PtrVT = getPointerTy();
2557 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2558 ARMConstantPoolValue *CPV =
2559 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2560 ARMPCLabelIndex, PCAdj);
2561 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2562 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2563 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2564 MachinePointerInfo::getConstantPool(),
2565 false, false, false, 0);
2566 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2567 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2571 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2573 SDValue Val = DAG.getConstant(0, MVT::i32);
2574 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2575 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2576 Op.getOperand(1), Val);
2580 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2582 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2583 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2587 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2588 const ARMSubtarget *Subtarget) const {
2589 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2592 default: return SDValue(); // Don't custom lower most intrinsics.
2593 case Intrinsic::arm_thread_pointer: {
2594 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2595 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2597 case Intrinsic::eh_sjlj_lsda: {
2598 MachineFunction &MF = DAG.getMachineFunction();
2599 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2600 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2601 EVT PtrVT = getPointerTy();
2602 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2604 unsigned PCAdj = (RelocM != Reloc::PIC_)
2605 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2606 ARMConstantPoolValue *CPV =
2607 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2608 ARMCP::CPLSDA, PCAdj);
2609 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2610 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2612 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2613 MachinePointerInfo::getConstantPool(),
2614 false, false, false, 0);
2616 if (RelocM == Reloc::PIC_) {
2617 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2618 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2622 case Intrinsic::arm_neon_vmulls:
2623 case Intrinsic::arm_neon_vmullu: {
2624 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2625 ? ARMISD::VMULLs : ARMISD::VMULLu;
2626 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2627 Op.getOperand(1), Op.getOperand(2));
2632 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2633 const ARMSubtarget *Subtarget) {
2634 // FIXME: handle "fence singlethread" more efficiently.
2636 if (!Subtarget->hasDataBarrier()) {
2637 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2638 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2640 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2641 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2642 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2643 DAG.getConstant(0, MVT::i32));
2646 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2647 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2648 unsigned Domain = ARM_MB::ISH;
2649 if (Subtarget->isMClass()) {
2650 // Only a full system barrier exists in the M-class architectures.
2651 Domain = ARM_MB::SY;
2652 } else if (Subtarget->isSwift() && Ord == Release) {
2653 // Swift happens to implement ISHST barriers in a way that's compatible with
2654 // Release semantics but weaker than ISH so we'd be fools not to use
2655 // it. Beware: other processors probably don't!
2656 Domain = ARM_MB::ISHST;
2659 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2660 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2661 DAG.getConstant(Domain, MVT::i32));
2664 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2665 const ARMSubtarget *Subtarget) {
2666 // ARM pre v5TE and Thumb1 does not have preload instructions.
2667 if (!(Subtarget->isThumb2() ||
2668 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2669 // Just preserve the chain.
2670 return Op.getOperand(0);
2673 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2675 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2676 // ARMv7 with MP extension has PLDW.
2677 return Op.getOperand(0);
2679 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2680 if (Subtarget->isThumb()) {
2682 isRead = ~isRead & 1;
2683 isData = ~isData & 1;
2686 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2687 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2688 DAG.getConstant(isData, MVT::i32));
2691 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2692 MachineFunction &MF = DAG.getMachineFunction();
2693 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2695 // vastart just stores the address of the VarArgsFrameIndex slot into the
2696 // memory location argument.
2698 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2699 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2700 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2701 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2702 MachinePointerInfo(SV), false, false, 0);
2706 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2707 SDValue &Root, SelectionDAG &DAG,
2709 MachineFunction &MF = DAG.getMachineFunction();
2710 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2712 const TargetRegisterClass *RC;
2713 if (AFI->isThumb1OnlyFunction())
2714 RC = &ARM::tGPRRegClass;
2716 RC = &ARM::GPRRegClass;
2718 // Transform the arguments stored in physical registers into virtual ones.
2719 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2720 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2723 if (NextVA.isMemLoc()) {
2724 MachineFrameInfo *MFI = MF.getFrameInfo();
2725 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2727 // Create load node to retrieve arguments from the stack.
2728 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2729 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2730 MachinePointerInfo::getFixedStack(FI),
2731 false, false, false, 0);
2733 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2734 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2737 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2741 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2742 unsigned InRegsParamRecordIdx,
2744 unsigned &ArgRegsSize,
2745 unsigned &ArgRegsSaveSize)
2748 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2749 unsigned RBegin, REnd;
2750 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2751 NumGPRs = REnd - RBegin;
2753 unsigned int firstUnalloced;
2754 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2755 sizeof(GPRArgRegs) /
2756 sizeof(GPRArgRegs[0]));
2757 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2760 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2761 ArgRegsSize = NumGPRs * 4;
2763 // If parameter is split between stack and GPRs...
2764 if (NumGPRs && Align == 8 &&
2765 (ArgRegsSize < ArgSize ||
2766 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2767 // Add padding for part of param recovered from GPRs, so
2768 // its last byte must be at address K*8 - 1.
2769 // We need to do it, since remained (stack) part of parameter has
2770 // stack alignment, and we need to "attach" "GPRs head" without gaps
2773 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2774 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2776 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2778 ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2779 (ArgRegsSize + AFI->getArgRegsSaveSize());
2780 ArgRegsSaveSize = ArgRegsSize + Padding;
2782 // We don't need to extend regs save size for byval parameters if they
2783 // are passed via GPRs only.
2784 ArgRegsSaveSize = ArgRegsSize;
2787 // The remaining GPRs hold either the beginning of variable-argument
2788 // data, or the beginning of an aggregate passed by value (usually
2789 // byval). Either way, we allocate stack slots adjacent to the data
2790 // provided by our caller, and store the unallocated registers there.
2791 // If this is a variadic function, the va_list pointer will begin with
2792 // these values; otherwise, this reassembles a (byval) structure that
2793 // was split between registers and memory.
2794 // Return: The frame index registers were stored into.
2796 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2797 SDLoc dl, SDValue &Chain,
2798 const Value *OrigArg,
2799 unsigned InRegsParamRecordIdx,
2800 unsigned OffsetFromOrigArg,
2803 bool ForceMutable) const {
2805 // Currently, two use-cases possible:
2806 // Case #1. Non var-args function, and we meet first byval parameter.
2807 // Setup first unallocated register as first byval register;
2808 // eat all remained registers
2809 // (these two actions are performed by HandleByVal method).
2810 // Then, here, we initialize stack frame with
2811 // "store-reg" instructions.
2812 // Case #2. Var-args function, that doesn't contain byval parameters.
2813 // The same: eat all remained unallocated registers,
2814 // initialize stack frame.
2816 MachineFunction &MF = DAG.getMachineFunction();
2817 MachineFrameInfo *MFI = MF.getFrameInfo();
2818 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2819 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2820 unsigned RBegin, REnd;
2821 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2822 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2823 firstRegToSaveIndex = RBegin - ARM::R0;
2824 lastRegToSaveIndex = REnd - ARM::R0;
2826 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2827 (GPRArgRegs, array_lengthof(GPRArgRegs));
2828 lastRegToSaveIndex = 4;
2831 unsigned ArgRegsSize, ArgRegsSaveSize;
2832 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2833 ArgRegsSize, ArgRegsSaveSize);
2835 // Store any by-val regs to their spots on the stack so that they may be
2836 // loaded by deferencing the result of formal parameter pointer or va_next.
2837 // Note: once stack area for byval/varargs registers
2838 // was initialized, it can't be initialized again.
2839 if (ArgRegsSaveSize) {
2841 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2844 assert(AFI->getStoredByValParamsPadding() == 0 &&
2845 "The only parameter may be padded.");
2846 AFI->setStoredByValParamsPadding(Padding);
2849 int FrameIndex = MFI->CreateFixedObject(
2851 Padding + ArgOffset,
2853 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2855 SmallVector<SDValue, 4> MemOps;
2856 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2857 ++firstRegToSaveIndex, ++i) {
2858 const TargetRegisterClass *RC;
2859 if (AFI->isThumb1OnlyFunction())
2860 RC = &ARM::tGPRRegClass;
2862 RC = &ARM::GPRRegClass;
2864 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2865 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2867 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2868 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2870 MemOps.push_back(Store);
2871 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2872 DAG.getConstant(4, getPointerTy()));
2875 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2877 if (!MemOps.empty())
2878 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2879 &MemOps[0], MemOps.size());
2882 // This will point to the next argument passed via stack.
2883 return MFI->CreateFixedObject(
2884 4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2887 // Setup stack frame, the va_list pointer will start from.
2889 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2890 SDLoc dl, SDValue &Chain,
2892 bool ForceMutable) const {
2893 MachineFunction &MF = DAG.getMachineFunction();
2894 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2896 // Try to store any remaining integer argument regs
2897 // to their spots on the stack so that they may be loaded by deferencing
2898 // the result of va_next.
2899 // If there is no regs to be stored, just point address after last
2900 // argument passed via stack.
2902 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2903 0, ArgOffset, 0, ForceMutable);
2905 AFI->setVarArgsFrameIndex(FrameIndex);
2909 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2910 CallingConv::ID CallConv, bool isVarArg,
2911 const SmallVectorImpl<ISD::InputArg>
2913 SDLoc dl, SelectionDAG &DAG,
2914 SmallVectorImpl<SDValue> &InVals)
2916 MachineFunction &MF = DAG.getMachineFunction();
2917 MachineFrameInfo *MFI = MF.getFrameInfo();
2919 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2921 // Assign locations to all of the incoming arguments.
2922 SmallVector<CCValAssign, 16> ArgLocs;
2923 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2924 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2925 CCInfo.AnalyzeFormalArguments(Ins,
2926 CCAssignFnForNode(CallConv, /* Return*/ false,
2929 SmallVector<SDValue, 16> ArgValues;
2930 int lastInsIndex = -1;
2932 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2933 unsigned CurArgIdx = 0;
2935 // Initially ArgRegsSaveSize is zero.
2936 // Then we increase this value each time we meet byval parameter.
2937 // We also increase this value in case of varargs function.
2938 AFI->setArgRegsSaveSize(0);
2940 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2941 CCValAssign &VA = ArgLocs[i];
2942 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2943 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2944 // Arguments stored in registers.
2945 if (VA.isRegLoc()) {
2946 EVT RegVT = VA.getLocVT();
2948 if (VA.needsCustom()) {
2949 // f64 and vector types are split up into multiple registers or
2950 // combinations of registers and stack slots.
2951 if (VA.getLocVT() == MVT::v2f64) {
2952 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2954 VA = ArgLocs[++i]; // skip ahead to next loc
2956 if (VA.isMemLoc()) {
2957 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2958 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2959 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2960 MachinePointerInfo::getFixedStack(FI),
2961 false, false, false, 0);
2963 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2966 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2967 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2968 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2969 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2970 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2972 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2975 const TargetRegisterClass *RC;
2977 if (RegVT == MVT::f32)
2978 RC = &ARM::SPRRegClass;
2979 else if (RegVT == MVT::f64)
2980 RC = &ARM::DPRRegClass;
2981 else if (RegVT == MVT::v2f64)
2982 RC = &ARM::QPRRegClass;
2983 else if (RegVT == MVT::i32)
2984 RC = AFI->isThumb1OnlyFunction() ?
2985 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2986 (const TargetRegisterClass*)&ARM::GPRRegClass;
2988 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2990 // Transform the arguments in physical registers into virtual ones.
2991 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2992 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2995 // If this is an 8 or 16-bit value, it is really passed promoted
2996 // to 32 bits. Insert an assert[sz]ext to capture this, then
2997 // truncate to the right size.
2998 switch (VA.getLocInfo()) {
2999 default: llvm_unreachable("Unknown loc info!");
3000 case CCValAssign::Full: break;
3001 case CCValAssign::BCvt:
3002 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3004 case CCValAssign::SExt:
3005 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3006 DAG.getValueType(VA.getValVT()));
3007 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3009 case CCValAssign::ZExt:
3010 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3011 DAG.getValueType(VA.getValVT()));
3012 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3016 InVals.push_back(ArgValue);
3018 } else { // VA.isRegLoc()
3021 assert(VA.isMemLoc());
3022 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3024 int index = ArgLocs[i].getValNo();
3026 // Some Ins[] entries become multiple ArgLoc[] entries.
3027 // Process them only once.
3028 if (index != lastInsIndex)
3030 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3031 // FIXME: For now, all byval parameter objects are marked mutable.
3032 // This can be changed with more analysis.
3033 // In case of tail call optimization mark all arguments mutable.
3034 // Since they could be overwritten by lowering of arguments in case of
3036 if (Flags.isByVal()) {
3037 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3038 int FrameIndex = StoreByValRegs(
3039 CCInfo, DAG, dl, Chain, CurOrigArg,
3041 Ins[VA.getValNo()].PartOffset,
3042 VA.getLocMemOffset(),
3043 Flags.getByValSize(),
3044 true /*force mutable frames*/);
3045 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3046 CCInfo.nextInRegsParam();
3048 unsigned FIOffset = VA.getLocMemOffset() +
3049 AFI->getStoredByValParamsPadding();
3050 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3053 // Create load nodes to retrieve arguments from the stack.
3054 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3055 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3056 MachinePointerInfo::getFixedStack(FI),
3057 false, false, false, 0));
3059 lastInsIndex = index;
3066 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3067 CCInfo.getNextStackOffset());
3072 /// isFloatingPointZero - Return true if this is +0.0.
3073 static bool isFloatingPointZero(SDValue Op) {
3074 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3075 return CFP->getValueAPF().isPosZero();
3076 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3077 // Maybe this has already been legalized into the constant pool?
3078 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3079 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3080 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3081 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3082 return CFP->getValueAPF().isPosZero();
3088 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3089 /// the given operands.
3091 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3092 SDValue &ARMcc, SelectionDAG &DAG,
3094 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3095 unsigned C = RHSC->getZExtValue();
3096 if (!isLegalICmpImmediate(C)) {
3097 // Constant does not fit, try adjusting it by one?
3102 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3103 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3104 RHS = DAG.getConstant(C-1, MVT::i32);
3109 if (C != 0 && isLegalICmpImmediate(C-1)) {
3110 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3111 RHS = DAG.getConstant(C-1, MVT::i32);
3116 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3117 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3118 RHS = DAG.getConstant(C+1, MVT::i32);
3123 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3124 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3125 RHS = DAG.getConstant(C+1, MVT::i32);
3132 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3133 ARMISD::NodeType CompareType;
3136 CompareType = ARMISD::CMP;
3141 CompareType = ARMISD::CMPZ;
3144 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3145 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3148 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3150 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3153 if (!isFloatingPointZero(RHS))
3154 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3156 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3157 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3160 /// duplicateCmp - Glue values can have only one use, so this function
3161 /// duplicates a comparison node.
3163 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3164 unsigned Opc = Cmp.getOpcode();
3166 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3167 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3169 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3170 Cmp = Cmp.getOperand(0);
3171 Opc = Cmp.getOpcode();
3172 if (Opc == ARMISD::CMPFP)
3173 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3175 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3176 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3178 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3181 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3182 SDValue Cond = Op.getOperand(0);
3183 SDValue SelectTrue = Op.getOperand(1);
3184 SDValue SelectFalse = Op.getOperand(2);
3189 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3190 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3192 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3193 const ConstantSDNode *CMOVTrue =
3194 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3195 const ConstantSDNode *CMOVFalse =
3196 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3198 if (CMOVTrue && CMOVFalse) {
3199 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3200 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3204 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3206 False = SelectFalse;
3207 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3212 if (True.getNode() && False.getNode()) {
3213 EVT VT = Op.getValueType();
3214 SDValue ARMcc = Cond.getOperand(2);
3215 SDValue CCR = Cond.getOperand(3);
3216 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3217 assert(True.getValueType() == VT);
3218 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3223 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3224 // undefined bits before doing a full-word comparison with zero.
3225 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3226 DAG.getConstant(1, Cond.getValueType()));
3228 return DAG.getSelectCC(dl, Cond,
3229 DAG.getConstant(0, Cond.getValueType()),
3230 SelectTrue, SelectFalse, ISD::SETNE);
3233 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3234 if (CC == ISD::SETNE)
3236 return ISD::getSetCCSwappedOperands(CC);
3239 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3240 bool &swpCmpOps, bool &swpVselOps) {
3241 // Start by selecting the GE condition code for opcodes that return true for
3243 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3245 CondCode = ARMCC::GE;
3247 // and GT for opcodes that return false for 'equality'.
3248 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3250 CondCode = ARMCC::GT;
3252 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3253 // to swap the compare operands.
3254 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3258 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3259 // If we have an unordered opcode, we need to swap the operands to the VSEL
3260 // instruction (effectively negating the condition).
3262 // This also has the effect of swapping which one of 'less' or 'greater'
3263 // returns true, so we also swap the compare operands. It also switches
3264 // whether we return true for 'equality', so we compensate by picking the
3265 // opposite condition code to our original choice.
3266 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3267 CC == ISD::SETUGT) {
3268 swpCmpOps = !swpCmpOps;
3269 swpVselOps = !swpVselOps;
3270 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3273 // 'ordered' is 'anything but unordered', so use the VS condition code and
3274 // swap the VSEL operands.
3275 if (CC == ISD::SETO) {
3276 CondCode = ARMCC::VS;
3280 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3281 // code and swap the VSEL operands.
3282 if (CC == ISD::SETUNE) {
3283 CondCode = ARMCC::EQ;
3288 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3289 EVT VT = Op.getValueType();
3290 SDValue LHS = Op.getOperand(0);
3291 SDValue RHS = Op.getOperand(1);
3292 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3293 SDValue TrueVal = Op.getOperand(2);
3294 SDValue FalseVal = Op.getOperand(3);
3297 if (LHS.getValueType() == MVT::i32) {
3298 // Try to generate VSEL on ARMv8.
3299 // The VSEL instruction can't use all the usual ARM condition
3300 // codes: it only has two bits to select the condition code, so it's
3301 // constrained to use only GE, GT, VS and EQ.
3303 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3304 // swap the operands of the previous compare instruction (effectively
3305 // inverting the compare condition, swapping 'less' and 'greater') and
3306 // sometimes need to swap the operands to the VSEL (which inverts the
3307 // condition in the sense of firing whenever the previous condition didn't)
3308 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3309 TrueVal.getValueType() == MVT::f64)) {
3310 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3311 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3312 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3313 CC = getInverseCCForVSEL(CC);
3314 std::swap(TrueVal, FalseVal);
3319 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3320 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3321 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3325 ARMCC::CondCodes CondCode, CondCode2;
3326 FPCCToARMCC(CC, CondCode, CondCode2);
3328 // Try to generate VSEL on ARMv8.
3329 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3330 TrueVal.getValueType() == MVT::f64)) {
3331 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3332 // same operands, as follows:
3333 // c = fcmp [ogt, olt, ugt, ult] a, b
3335 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3336 // handled differently than the original code sequence.
3337 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3339 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3340 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3341 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3342 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3345 bool swpCmpOps = false;
3346 bool swpVselOps = false;
3347 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3349 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3350 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3352 std::swap(LHS, RHS);
3354 std::swap(TrueVal, FalseVal);
3358 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3359 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3360 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3361 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3363 if (CondCode2 != ARMCC::AL) {
3364 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3365 // FIXME: Needs another CMP because flag can have but one use.
3366 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3367 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3368 Result, TrueVal, ARMcc2, CCR, Cmp2);
3373 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3374 /// to morph to an integer compare sequence.
3375 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3376 const ARMSubtarget *Subtarget) {
3377 SDNode *N = Op.getNode();
3378 if (!N->hasOneUse())
3379 // Otherwise it requires moving the value from fp to integer registers.
3381 if (!N->getNumValues())
3383 EVT VT = Op.getValueType();
3384 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3385 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3386 // vmrs are very slow, e.g. cortex-a8.
3389 if (isFloatingPointZero(Op)) {
3393 return ISD::isNormalLoad(N);
3396 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3397 if (isFloatingPointZero(Op))
3398 return DAG.getConstant(0, MVT::i32);
3400 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3401 return DAG.getLoad(MVT::i32, SDLoc(Op),
3402 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3403 Ld->isVolatile(), Ld->isNonTemporal(),
3404 Ld->isInvariant(), Ld->getAlignment());
3406 llvm_unreachable("Unknown VFP cmp argument!");
3409 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3410 SDValue &RetVal1, SDValue &RetVal2) {
3411 if (isFloatingPointZero(Op)) {
3412 RetVal1 = DAG.getConstant(0, MVT::i32);
3413 RetVal2 = DAG.getConstant(0, MVT::i32);
3417 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3418 SDValue Ptr = Ld->getBasePtr();
3419 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3420 Ld->getChain(), Ptr,
3421 Ld->getPointerInfo(),
3422 Ld->isVolatile(), Ld->isNonTemporal(),
3423 Ld->isInvariant(), Ld->getAlignment());
3425 EVT PtrType = Ptr.getValueType();
3426 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3427 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3428 PtrType, Ptr, DAG.getConstant(4, PtrType));
3429 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3430 Ld->getChain(), NewPtr,
3431 Ld->getPointerInfo().getWithOffset(4),
3432 Ld->isVolatile(), Ld->isNonTemporal(),
3433 Ld->isInvariant(), NewAlign);
3437 llvm_unreachable("Unknown VFP cmp argument!");
3440 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3441 /// f32 and even f64 comparisons to integer ones.
3443 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3444 SDValue Chain = Op.getOperand(0);
3445 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3446 SDValue LHS = Op.getOperand(2);
3447 SDValue RHS = Op.getOperand(3);
3448 SDValue Dest = Op.getOperand(4);
3451 bool LHSSeenZero = false;
3452 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3453 bool RHSSeenZero = false;
3454 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3455 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3456 // If unsafe fp math optimization is enabled and there are no other uses of
3457 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3458 // to an integer comparison.
3459 if (CC == ISD::SETOEQ)
3461 else if (CC == ISD::SETUNE)
3464 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3466 if (LHS.getValueType() == MVT::f32) {
3467 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3468 bitcastf32Toi32(LHS, DAG), Mask);
3469 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3470 bitcastf32Toi32(RHS, DAG), Mask);
3471 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3472 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3473 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3474 Chain, Dest, ARMcc, CCR, Cmp);
3479 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3480 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3481 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3482 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3483 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3484 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3485 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3486 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3487 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3493 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3494 SDValue Chain = Op.getOperand(0);
3495 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3496 SDValue LHS = Op.getOperand(2);
3497 SDValue RHS = Op.getOperand(3);
3498 SDValue Dest = Op.getOperand(4);
3501 if (LHS.getValueType() == MVT::i32) {
3503 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3504 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3505 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3506 Chain, Dest, ARMcc, CCR, Cmp);
3509 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3511 if (getTargetMachine().Options.UnsafeFPMath &&
3512 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3513 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3514 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3515 if (Result.getNode())
3519 ARMCC::CondCodes CondCode, CondCode2;
3520 FPCCToARMCC(CC, CondCode, CondCode2);
3522 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3523 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3524 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3525 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3526 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3527 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3528 if (CondCode2 != ARMCC::AL) {
3529 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3530 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3531 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3536 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3537 SDValue Chain = Op.getOperand(0);
3538 SDValue Table = Op.getOperand(1);
3539 SDValue Index = Op.getOperand(2);
3542 EVT PTy = getPointerTy();
3543 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3544 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3545 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3546 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3547 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3548 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3549 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3550 if (Subtarget->isThumb2()) {
3551 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3552 // which does another jump to the destination. This also makes it easier
3553 // to translate it to TBB / TBH later.
3554 // FIXME: This might not work if the function is extremely large.
3555 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3556 Addr, Op.getOperand(2), JTI, UId);
3558 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3559 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3560 MachinePointerInfo::getJumpTable(),
3561 false, false, false, 0);
3562 Chain = Addr.getValue(1);
3563 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3564 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3566 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3567 MachinePointerInfo::getJumpTable(),
3568 false, false, false, 0);
3569 Chain = Addr.getValue(1);
3570 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3574 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3575 EVT VT = Op.getValueType();
3578 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3579 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3581 return DAG.UnrollVectorOp(Op.getNode());
3584 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3585 "Invalid type for custom lowering!");
3586 if (VT != MVT::v4i16)
3587 return DAG.UnrollVectorOp(Op.getNode());
3589 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3590 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3593 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3594 EVT VT = Op.getValueType();
3596 return LowerVectorFP_TO_INT(Op, DAG);
3601 switch (Op.getOpcode()) {
3602 default: llvm_unreachable("Invalid opcode!");
3603 case ISD::FP_TO_SINT:
3604 Opc = ARMISD::FTOSI;
3606 case ISD::FP_TO_UINT:
3607 Opc = ARMISD::FTOUI;
3610 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3611 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3614 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3615 EVT VT = Op.getValueType();
3618 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3619 if (VT.getVectorElementType() == MVT::f32)
3621 return DAG.UnrollVectorOp(Op.getNode());
3624 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3625 "Invalid type for custom lowering!");
3626 if (VT != MVT::v4f32)
3627 return DAG.UnrollVectorOp(Op.getNode());
3631 switch (Op.getOpcode()) {
3632 default: llvm_unreachable("Invalid opcode!");
3633 case ISD::SINT_TO_FP:
3634 CastOpc = ISD::SIGN_EXTEND;
3635 Opc = ISD::SINT_TO_FP;
3637 case ISD::UINT_TO_FP:
3638 CastOpc = ISD::ZERO_EXTEND;
3639 Opc = ISD::UINT_TO_FP;
3643 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3644 return DAG.getNode(Opc, dl, VT, Op);
3647 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3648 EVT VT = Op.getValueType();
3650 return LowerVectorINT_TO_FP(Op, DAG);
3655 switch (Op.getOpcode()) {
3656 default: llvm_unreachable("Invalid opcode!");
3657 case ISD::SINT_TO_FP:
3658 Opc = ARMISD::SITOF;
3660 case ISD::UINT_TO_FP:
3661 Opc = ARMISD::UITOF;
3665 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3666 return DAG.getNode(Opc, dl, VT, Op);
3669 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3670 // Implement fcopysign with a fabs and a conditional fneg.
3671 SDValue Tmp0 = Op.getOperand(0);
3672 SDValue Tmp1 = Op.getOperand(1);
3674 EVT VT = Op.getValueType();
3675 EVT SrcVT = Tmp1.getValueType();
3676 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3677 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3678 bool UseNEON = !InGPR && Subtarget->hasNEON();
3681 // Use VBSL to copy the sign bit.
3682 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3683 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3684 DAG.getTargetConstant(EncodedVal, MVT::i32));
3685 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3687 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3688 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3689 DAG.getConstant(32, MVT::i32));
3690 else /*if (VT == MVT::f32)*/
3691 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3692 if (SrcVT == MVT::f32) {
3693 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3695 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3696 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3697 DAG.getConstant(32, MVT::i32));
3698 } else if (VT == MVT::f32)
3699 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3700 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3701 DAG.getConstant(32, MVT::i32));
3702 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3703 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3705 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3707 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3708 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3709 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3711 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3712 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3713 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3714 if (VT == MVT::f32) {
3715 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3716 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3717 DAG.getConstant(0, MVT::i32));
3719 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3725 // Bitcast operand 1 to i32.
3726 if (SrcVT == MVT::f64)
3727 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3728 &Tmp1, 1).getValue(1);
3729 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3731 // Or in the signbit with integer operations.
3732 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3733 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3734 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3735 if (VT == MVT::f32) {
3736 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3737 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3738 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3739 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3742 // f64: Or the high part with signbit and then combine two parts.
3743 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3745 SDValue Lo = Tmp0.getValue(0);
3746 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3747 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3748 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3751 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3752 MachineFunction &MF = DAG.getMachineFunction();
3753 MachineFrameInfo *MFI = MF.getFrameInfo();
3754 MFI->setReturnAddressIsTaken(true);
3756 EVT VT = Op.getValueType();
3758 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3760 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3761 SDValue Offset = DAG.getConstant(4, MVT::i32);
3762 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3763 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3764 MachinePointerInfo(), false, false, false, 0);
3767 // Return LR, which contains the return address. Mark it an implicit live-in.
3768 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3769 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3772 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3773 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3774 MFI->setFrameAddressIsTaken(true);
3776 EVT VT = Op.getValueType();
3777 SDLoc dl(Op); // FIXME probably not meaningful
3778 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3779 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3780 ? ARM::R7 : ARM::R11;
3781 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3783 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3784 MachinePointerInfo(),
3785 false, false, false, 0);
3789 /// ExpandBITCAST - If the target supports VFP, this function is called to
3790 /// expand a bit convert where either the source or destination type is i64 to
3791 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3792 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3793 /// vectors), since the legalizer won't know what to do with that.
3794 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3795 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3797 SDValue Op = N->getOperand(0);
3799 // This function is only supposed to be called for i64 types, either as the
3800 // source or destination of the bit convert.
3801 EVT SrcVT = Op.getValueType();
3802 EVT DstVT = N->getValueType(0);
3803 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3804 "ExpandBITCAST called for non-i64 type");
3806 // Turn i64->f64 into VMOVDRR.
3807 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3808 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3809 DAG.getConstant(0, MVT::i32));
3810 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3811 DAG.getConstant(1, MVT::i32));
3812 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3813 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3816 // Turn f64->i64 into VMOVRRD.
3817 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3818 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3819 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3820 // Merge the pieces into a single i64 value.
3821 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3827 /// getZeroVector - Returns a vector of specified type with all zero elements.
3828 /// Zero vectors are used to represent vector negation and in those cases
3829 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3830 /// not support i64 elements, so sometimes the zero vectors will need to be
3831 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3833 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3834 assert(VT.isVector() && "Expected a vector type");
3835 // The canonical modified immediate encoding of a zero vector is....0!
3836 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3837 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3838 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3839 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3842 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3843 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3844 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3845 SelectionDAG &DAG) const {
3846 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3847 EVT VT = Op.getValueType();
3848 unsigned VTBits = VT.getSizeInBits();
3850 SDValue ShOpLo = Op.getOperand(0);
3851 SDValue ShOpHi = Op.getOperand(1);
3852 SDValue ShAmt = Op.getOperand(2);
3854 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3856 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3858 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3859 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3860 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3861 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3862 DAG.getConstant(VTBits, MVT::i32));
3863 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3864 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3865 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3867 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3868 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3870 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3871 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3874 SDValue Ops[2] = { Lo, Hi };
3875 return DAG.getMergeValues(Ops, 2, dl);
3878 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3879 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3880 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3881 SelectionDAG &DAG) const {
3882 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3883 EVT VT = Op.getValueType();
3884 unsigned VTBits = VT.getSizeInBits();
3886 SDValue ShOpLo = Op.getOperand(0);
3887 SDValue ShOpHi = Op.getOperand(1);
3888 SDValue ShAmt = Op.getOperand(2);
3891 assert(Op.getOpcode() == ISD::SHL_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, RevShAmt);
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, ShAmt);
3898 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3900 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3901 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3902 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3904 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3905 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3908 SDValue Ops[2] = { Lo, Hi };
3909 return DAG.getMergeValues(Ops, 2, dl);
3912 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3913 SelectionDAG &DAG) const {
3914 // The rounding mode is in bits 23:22 of the FPSCR.
3915 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3916 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3917 // so that the shift + and get folded into a bitfield extract.
3919 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3920 DAG.getConstant(Intrinsic::arm_get_fpscr,
3922 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3923 DAG.getConstant(1U << 22, MVT::i32));
3924 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3925 DAG.getConstant(22, MVT::i32));
3926 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3927 DAG.getConstant(3, MVT::i32));
3930 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3931 const ARMSubtarget *ST) {
3932 EVT VT = N->getValueType(0);
3935 if (!ST->hasV6T2Ops())
3938 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3939 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3942 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3943 /// for each 16-bit element from operand, repeated. The basic idea is to
3944 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3946 /// Trace for v4i16:
3947 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3948 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3949 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3950 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3951 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3952 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3953 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3954 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3955 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3956 EVT VT = N->getValueType(0);
3959 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3960 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3961 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3962 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3963 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3964 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3967 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3968 /// bit-count for each 16-bit element from the operand. We need slightly
3969 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3970 /// 64/128-bit registers.
3972 /// Trace for v4i16:
3973 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3974 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3975 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3976 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3977 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3978 EVT VT = N->getValueType(0);
3981 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3982 if (VT.is64BitVector()) {
3983 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3984 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3985 DAG.getIntPtrConstant(0));
3987 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3988 BitCounts, DAG.getIntPtrConstant(0));
3989 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3993 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3994 /// bit-count for each 32-bit element from the operand. The idea here is
3995 /// to split the vector into 16-bit elements, leverage the 16-bit count
3996 /// routine, and then combine the results.
3998 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3999 /// input = [v0 v1 ] (vi: 32-bit elements)
4000 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4001 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4002 /// vrev: N0 = [k1 k0 k3 k2 ]
4004 /// N1 =+[k1 k0 k3 k2 ]
4006 /// N2 =+[k1 k3 k0 k2 ]
4008 /// Extended =+[k1 k3 k0 k2 ]
4010 /// Extracted=+[k1 k3 ]
4012 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4013 EVT VT = N->getValueType(0);
4016 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4018 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4019 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4020 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4021 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4022 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4024 if (VT.is64BitVector()) {
4025 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4026 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4027 DAG.getIntPtrConstant(0));
4029 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4030 DAG.getIntPtrConstant(0));
4031 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4035 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4036 const ARMSubtarget *ST) {
4037 EVT VT = N->getValueType(0);
4039 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4040 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4041 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4042 "Unexpected type for custom ctpop lowering");
4044 if (VT.getVectorElementType() == MVT::i32)
4045 return lowerCTPOP32BitElements(N, DAG);
4047 return lowerCTPOP16BitElements(N, DAG);
4050 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4051 const ARMSubtarget *ST) {
4052 EVT VT = N->getValueType(0);
4058 // Lower vector shifts on NEON to use VSHL.
4059 assert(ST->hasNEON() && "unexpected vector shift");
4061 // Left shifts translate directly to the vshiftu intrinsic.
4062 if (N->getOpcode() == ISD::SHL)
4063 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4064 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4065 N->getOperand(0), N->getOperand(1));
4067 assert((N->getOpcode() == ISD::SRA ||
4068 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4070 // NEON uses the same intrinsics for both left and right shifts. For
4071 // right shifts, the shift amounts are negative, so negate the vector of
4073 EVT ShiftVT = N->getOperand(1).getValueType();
4074 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4075 getZeroVector(ShiftVT, DAG, dl),
4077 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4078 Intrinsic::arm_neon_vshifts :
4079 Intrinsic::arm_neon_vshiftu);
4080 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4081 DAG.getConstant(vshiftInt, MVT::i32),
4082 N->getOperand(0), NegatedCount);
4085 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4086 const ARMSubtarget *ST) {
4087 EVT VT = N->getValueType(0);
4090 // We can get here for a node like i32 = ISD::SHL i32, i64
4094 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4095 "Unknown shift to lower!");
4097 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4098 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4099 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4102 // If we are in thumb mode, we don't have RRX.
4103 if (ST->isThumb1Only()) return SDValue();
4105 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4106 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4107 DAG.getConstant(0, MVT::i32));
4108 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4109 DAG.getConstant(1, MVT::i32));
4111 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4112 // captures the result into a carry flag.
4113 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4114 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4116 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4117 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4119 // Merge the pieces into a single i64 value.
4120 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4123 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4124 SDValue TmpOp0, TmpOp1;
4125 bool Invert = false;
4129 SDValue Op0 = Op.getOperand(0);
4130 SDValue Op1 = Op.getOperand(1);
4131 SDValue CC = Op.getOperand(2);
4132 EVT VT = Op.getValueType();
4133 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4136 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4137 switch (SetCCOpcode) {
4138 default: llvm_unreachable("Illegal FP comparison");
4140 case ISD::SETNE: Invert = true; // Fallthrough
4142 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4144 case ISD::SETLT: Swap = true; // Fallthrough
4146 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4148 case ISD::SETLE: Swap = true; // Fallthrough
4150 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4151 case ISD::SETUGE: Swap = true; // Fallthrough
4152 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4153 case ISD::SETUGT: Swap = true; // Fallthrough
4154 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4155 case ISD::SETUEQ: Invert = true; // Fallthrough
4157 // Expand this to (OLT | OGT).
4161 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4162 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4164 case ISD::SETUO: Invert = true; // Fallthrough
4166 // Expand this to (OLT | OGE).
4170 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4171 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4175 // Integer comparisons.
4176 switch (SetCCOpcode) {
4177 default: llvm_unreachable("Illegal integer comparison");
4178 case ISD::SETNE: Invert = true;
4179 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4180 case ISD::SETLT: Swap = true;
4181 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4182 case ISD::SETLE: Swap = true;
4183 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4184 case ISD::SETULT: Swap = true;
4185 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4186 case ISD::SETULE: Swap = true;
4187 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4190 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4191 if (Opc == ARMISD::VCEQ) {
4194 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4196 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4199 // Ignore bitconvert.
4200 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4201 AndOp = AndOp.getOperand(0);
4203 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4205 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4206 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4213 std::swap(Op0, Op1);
4215 // If one of the operands is a constant vector zero, attempt to fold the
4216 // comparison to a specialized compare-against-zero form.
4218 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4220 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4221 if (Opc == ARMISD::VCGE)
4222 Opc = ARMISD::VCLEZ;
4223 else if (Opc == ARMISD::VCGT)
4224 Opc = ARMISD::VCLTZ;
4229 if (SingleOp.getNode()) {
4232 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4234 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4236 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4238 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4240 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4242 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4245 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4249 Result = DAG.getNOT(dl, Result, VT);
4254 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4255 /// valid vector constant for a NEON instruction with a "modified immediate"
4256 /// operand (e.g., VMOV). If so, return the encoded value.
4257 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4258 unsigned SplatBitSize, SelectionDAG &DAG,
4259 EVT &VT, bool is128Bits, NEONModImmType type) {
4260 unsigned OpCmode, Imm;
4262 // SplatBitSize is set to the smallest size that splats the vector, so a
4263 // zero vector will always have SplatBitSize == 8. However, NEON modified
4264 // immediate instructions others than VMOV do not support the 8-bit encoding
4265 // of a zero vector, and the default encoding of zero is supposed to be the
4270 switch (SplatBitSize) {
4272 if (type != VMOVModImm)
4274 // Any 1-byte value is OK. Op=0, Cmode=1110.
4275 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4278 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4282 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4283 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4284 if ((SplatBits & ~0xff) == 0) {
4285 // Value = 0x00nn: Op=x, Cmode=100x.
4290 if ((SplatBits & ~0xff00) == 0) {
4291 // Value = 0xnn00: Op=x, Cmode=101x.
4293 Imm = SplatBits >> 8;
4299 // NEON's 32-bit VMOV supports splat values where:
4300 // * only one byte is nonzero, or
4301 // * the least significant byte is 0xff and the second byte is nonzero, or
4302 // * the least significant 2 bytes are 0xff and the third is nonzero.
4303 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4304 if ((SplatBits & ~0xff) == 0) {
4305 // Value = 0x000000nn: Op=x, Cmode=000x.
4310 if ((SplatBits & ~0xff00) == 0) {
4311 // Value = 0x0000nn00: Op=x, Cmode=001x.
4313 Imm = SplatBits >> 8;
4316 if ((SplatBits & ~0xff0000) == 0) {
4317 // Value = 0x00nn0000: Op=x, Cmode=010x.
4319 Imm = SplatBits >> 16;
4322 if ((SplatBits & ~0xff000000) == 0) {
4323 // Value = 0xnn000000: Op=x, Cmode=011x.
4325 Imm = SplatBits >> 24;
4329 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4330 if (type == OtherModImm) return SDValue();
4332 if ((SplatBits & ~0xffff) == 0 &&
4333 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4334 // Value = 0x0000nnff: Op=x, Cmode=1100.
4336 Imm = SplatBits >> 8;
4341 if ((SplatBits & ~0xffffff) == 0 &&
4342 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4343 // Value = 0x00nnffff: Op=x, Cmode=1101.
4345 Imm = SplatBits >> 16;
4346 SplatBits |= 0xffff;
4350 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4351 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4352 // VMOV.I32. A (very) minor optimization would be to replicate the value
4353 // and fall through here to test for a valid 64-bit splat. But, then the
4354 // caller would also need to check and handle the change in size.
4358 if (type != VMOVModImm)
4360 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4361 uint64_t BitMask = 0xff;
4363 unsigned ImmMask = 1;
4365 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4366 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4369 } else if ((SplatBits & BitMask) != 0) {
4375 // Op=1, Cmode=1110.
4378 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4383 llvm_unreachable("unexpected size for isNEONModifiedImm");
4386 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4387 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4390 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4391 const ARMSubtarget *ST) const {
4395 bool IsDouble = Op.getValueType() == MVT::f64;
4396 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4398 // Try splatting with a VMOV.f32...
4399 APFloat FPVal = CFP->getValueAPF();
4400 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4403 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4404 // We have code in place to select a valid ConstantFP already, no need to
4409 // It's a float and we are trying to use NEON operations where
4410 // possible. Lower it to a splat followed by an extract.
4412 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4413 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4415 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4416 DAG.getConstant(0, MVT::i32));
4419 // The rest of our options are NEON only, make sure that's allowed before
4421 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4425 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4427 // It wouldn't really be worth bothering for doubles except for one very
4428 // important value, which does happen to match: 0.0. So make sure we don't do
4430 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4433 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4434 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4436 if (NewVal != SDValue()) {
4438 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4441 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4443 // It's a float: cast and extract a vector element.
4444 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4446 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4447 DAG.getConstant(0, MVT::i32));
4450 // Finally, try a VMVN.i32
4451 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4453 if (NewVal != SDValue()) {
4455 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4458 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4460 // It's a float: cast and extract a vector element.
4461 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4463 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4464 DAG.getConstant(0, MVT::i32));
4470 // check if an VEXT instruction can handle the shuffle mask when the
4471 // vector sources of the shuffle are the same.
4472 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4473 unsigned NumElts = VT.getVectorNumElements();
4475 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4481 // If this is a VEXT shuffle, the immediate value is the index of the first
4482 // element. The other shuffle indices must be the successive elements after
4484 unsigned ExpectedElt = Imm;
4485 for (unsigned i = 1; i < NumElts; ++i) {
4486 // Increment the expected index. If it wraps around, just follow it
4487 // back to index zero and keep going.
4489 if (ExpectedElt == NumElts)
4492 if (M[i] < 0) continue; // ignore UNDEF indices
4493 if (ExpectedElt != static_cast<unsigned>(M[i]))
4501 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4502 bool &ReverseVEXT, unsigned &Imm) {
4503 unsigned NumElts = VT.getVectorNumElements();
4504 ReverseVEXT = false;
4506 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4512 // If this is a VEXT shuffle, the immediate value is the index of the first
4513 // element. The other shuffle indices must be the successive elements after
4515 unsigned ExpectedElt = Imm;
4516 for (unsigned i = 1; i < NumElts; ++i) {
4517 // Increment the expected index. If it wraps around, it may still be
4518 // a VEXT but the source vectors must be swapped.
4520 if (ExpectedElt == NumElts * 2) {
4525 if (M[i] < 0) continue; // ignore UNDEF indices
4526 if (ExpectedElt != static_cast<unsigned>(M[i]))
4530 // Adjust the index value if the source operands will be swapped.
4537 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4538 /// instruction with the specified blocksize. (The order of the elements
4539 /// within each block of the vector is reversed.)
4540 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4541 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4542 "Only possible block sizes for VREV are: 16, 32, 64");
4544 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4548 unsigned NumElts = VT.getVectorNumElements();
4549 unsigned BlockElts = M[0] + 1;
4550 // If the first shuffle index is UNDEF, be optimistic.
4552 BlockElts = BlockSize / EltSz;
4554 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4557 for (unsigned i = 0; i < NumElts; ++i) {
4558 if (M[i] < 0) continue; // ignore UNDEF indices
4559 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4566 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4567 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4568 // range, then 0 is placed into the resulting vector. So pretty much any mask
4569 // of 8 elements can work here.
4570 return VT == MVT::v8i8 && M.size() == 8;
4573 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4574 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4578 unsigned NumElts = VT.getVectorNumElements();
4579 WhichResult = (M[0] == 0 ? 0 : 1);
4580 for (unsigned i = 0; i < NumElts; i += 2) {
4581 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4582 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4588 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4589 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4590 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4591 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4592 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4596 unsigned NumElts = VT.getVectorNumElements();
4597 WhichResult = (M[0] == 0 ? 0 : 1);
4598 for (unsigned i = 0; i < NumElts; i += 2) {
4599 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4600 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4606 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4607 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4611 unsigned NumElts = VT.getVectorNumElements();
4612 WhichResult = (M[0] == 0 ? 0 : 1);
4613 for (unsigned i = 0; i != NumElts; ++i) {
4614 if (M[i] < 0) continue; // ignore UNDEF indices
4615 if ((unsigned) M[i] != 2 * i + WhichResult)
4619 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4620 if (VT.is64BitVector() && EltSz == 32)
4626 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4627 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4628 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4629 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4630 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4634 unsigned Half = VT.getVectorNumElements() / 2;
4635 WhichResult = (M[0] == 0 ? 0 : 1);
4636 for (unsigned j = 0; j != 2; ++j) {
4637 unsigned Idx = WhichResult;
4638 for (unsigned i = 0; i != Half; ++i) {
4639 int MIdx = M[i + j * Half];
4640 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4646 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4647 if (VT.is64BitVector() && EltSz == 32)
4653 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4654 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4658 unsigned NumElts = VT.getVectorNumElements();
4659 WhichResult = (M[0] == 0 ? 0 : 1);
4660 unsigned Idx = WhichResult * NumElts / 2;
4661 for (unsigned i = 0; i != NumElts; i += 2) {
4662 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4663 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4668 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4669 if (VT.is64BitVector() && EltSz == 32)
4675 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4676 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4677 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4678 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4679 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4683 unsigned NumElts = VT.getVectorNumElements();
4684 WhichResult = (M[0] == 0 ? 0 : 1);
4685 unsigned Idx = WhichResult * NumElts / 2;
4686 for (unsigned i = 0; i != NumElts; i += 2) {
4687 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4688 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4693 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4694 if (VT.is64BitVector() && EltSz == 32)
4700 /// \return true if this is a reverse operation on an vector.
4701 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4702 unsigned NumElts = VT.getVectorNumElements();
4703 // Make sure the mask has the right size.
4704 if (NumElts != M.size())
4707 // Look for <15, ..., 3, -1, 1, 0>.
4708 for (unsigned i = 0; i != NumElts; ++i)
4709 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4715 // If N is an integer constant that can be moved into a register in one
4716 // instruction, return an SDValue of such a constant (will become a MOV
4717 // instruction). Otherwise return null.
4718 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4719 const ARMSubtarget *ST, SDLoc dl) {
4721 if (!isa<ConstantSDNode>(N))
4723 Val = cast<ConstantSDNode>(N)->getZExtValue();
4725 if (ST->isThumb1Only()) {
4726 if (Val <= 255 || ~Val <= 255)
4727 return DAG.getConstant(Val, MVT::i32);
4729 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4730 return DAG.getConstant(Val, MVT::i32);
4735 // If this is a case we can't handle, return null and let the default
4736 // expansion code take care of it.
4737 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4738 const ARMSubtarget *ST) const {
4739 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4741 EVT VT = Op.getValueType();
4743 APInt SplatBits, SplatUndef;
4744 unsigned SplatBitSize;
4746 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4747 if (SplatBitSize <= 64) {
4748 // Check if an immediate VMOV works.
4750 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4751 SplatUndef.getZExtValue(), SplatBitSize,
4752 DAG, VmovVT, VT.is128BitVector(),
4754 if (Val.getNode()) {
4755 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4756 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4759 // Try an immediate VMVN.
4760 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4761 Val = isNEONModifiedImm(NegatedImm,
4762 SplatUndef.getZExtValue(), SplatBitSize,
4763 DAG, VmovVT, VT.is128BitVector(),
4765 if (Val.getNode()) {
4766 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4767 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4770 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4771 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4772 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4774 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4775 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4781 // Scan through the operands to see if only one value is used.
4783 // As an optimisation, even if more than one value is used it may be more
4784 // profitable to splat with one value then change some lanes.
4786 // Heuristically we decide to do this if the vector has a "dominant" value,
4787 // defined as splatted to more than half of the lanes.
4788 unsigned NumElts = VT.getVectorNumElements();
4789 bool isOnlyLowElement = true;
4790 bool usesOnlyOneValue = true;
4791 bool hasDominantValue = false;
4792 bool isConstant = true;
4794 // Map of the number of times a particular SDValue appears in the
4796 DenseMap<SDValue, unsigned> ValueCounts;
4798 for (unsigned i = 0; i < NumElts; ++i) {
4799 SDValue V = Op.getOperand(i);
4800 if (V.getOpcode() == ISD::UNDEF)
4803 isOnlyLowElement = false;
4804 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4807 ValueCounts.insert(std::make_pair(V, 0));
4808 unsigned &Count = ValueCounts[V];
4810 // Is this value dominant? (takes up more than half of the lanes)
4811 if (++Count > (NumElts / 2)) {
4812 hasDominantValue = true;
4816 if (ValueCounts.size() != 1)
4817 usesOnlyOneValue = false;
4818 if (!Value.getNode() && ValueCounts.size() > 0)
4819 Value = ValueCounts.begin()->first;
4821 if (ValueCounts.size() == 0)
4822 return DAG.getUNDEF(VT);
4824 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4825 // Keep going if we are hitting this case.
4826 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4827 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4829 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4831 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4832 // i32 and try again.
4833 if (hasDominantValue && EltSize <= 32) {
4837 // If we are VDUPing a value that comes directly from a vector, that will
4838 // cause an unnecessary move to and from a GPR, where instead we could
4839 // just use VDUPLANE. We can only do this if the lane being extracted
4840 // is at a constant index, as the VDUP from lane instructions only have
4841 // constant-index forms.
4842 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4843 isa<ConstantSDNode>(Value->getOperand(1))) {
4844 // We need to create a new undef vector to use for the VDUPLANE if the
4845 // size of the vector from which we get the value is different than the
4846 // size of the vector that we need to create. We will insert the element
4847 // such that the register coalescer will remove unnecessary copies.
4848 if (VT != Value->getOperand(0).getValueType()) {
4849 ConstantSDNode *constIndex;
4850 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4851 assert(constIndex && "The index is not a constant!");
4852 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4853 VT.getVectorNumElements();
4854 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4855 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4856 Value, DAG.getConstant(index, MVT::i32)),
4857 DAG.getConstant(index, MVT::i32));
4859 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4860 Value->getOperand(0), Value->getOperand(1));
4862 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4864 if (!usesOnlyOneValue) {
4865 // The dominant value was splatted as 'N', but we now have to insert
4866 // all differing elements.
4867 for (unsigned I = 0; I < NumElts; ++I) {
4868 if (Op.getOperand(I) == Value)
4870 SmallVector<SDValue, 3> Ops;
4872 Ops.push_back(Op.getOperand(I));
4873 Ops.push_back(DAG.getConstant(I, MVT::i32));
4874 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4879 if (VT.getVectorElementType().isFloatingPoint()) {
4880 SmallVector<SDValue, 8> Ops;
4881 for (unsigned i = 0; i < NumElts; ++i)
4882 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4884 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4885 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4886 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4888 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4890 if (usesOnlyOneValue) {
4891 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4892 if (isConstant && Val.getNode())
4893 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4897 // If all elements are constants and the case above didn't get hit, fall back
4898 // to the default expansion, which will generate a load from the constant
4903 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4905 SDValue shuffle = ReconstructShuffle(Op, DAG);
4906 if (shuffle != SDValue())
4910 // Vectors with 32- or 64-bit elements can be built by directly assigning
4911 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4912 // will be legalized.
4913 if (EltSize >= 32) {
4914 // Do the expansion with floating-point types, since that is what the VFP
4915 // registers are defined to use, and since i64 is not legal.
4916 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4917 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4918 SmallVector<SDValue, 8> Ops;
4919 for (unsigned i = 0; i < NumElts; ++i)
4920 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4921 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4922 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4925 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4926 // know the default expansion would otherwise fall back on something even
4927 // worse. For a vector with one or two non-undef values, that's
4928 // scalar_to_vector for the elements followed by a shuffle (provided the
4929 // shuffle is valid for the target) and materialization element by element
4930 // on the stack followed by a load for everything else.
4931 if (!isConstant && !usesOnlyOneValue) {
4932 SDValue Vec = DAG.getUNDEF(VT);
4933 for (unsigned i = 0 ; i < NumElts; ++i) {
4934 SDValue V = Op.getOperand(i);
4935 if (V.getOpcode() == ISD::UNDEF)
4937 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4938 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4946 // Gather data to see if the operation can be modelled as a
4947 // shuffle in combination with VEXTs.
4948 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4949 SelectionDAG &DAG) const {
4951 EVT VT = Op.getValueType();
4952 unsigned NumElts = VT.getVectorNumElements();
4954 SmallVector<SDValue, 2> SourceVecs;
4955 SmallVector<unsigned, 2> MinElts;
4956 SmallVector<unsigned, 2> MaxElts;
4958 for (unsigned i = 0; i < NumElts; ++i) {
4959 SDValue V = Op.getOperand(i);
4960 if (V.getOpcode() == ISD::UNDEF)
4962 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4963 // A shuffle can only come from building a vector from various
4964 // elements of other vectors.
4966 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4967 VT.getVectorElementType()) {
4968 // This code doesn't know how to handle shuffles where the vector
4969 // element types do not match (this happens because type legalization
4970 // promotes the return type of EXTRACT_VECTOR_ELT).
4971 // FIXME: It might be appropriate to extend this code to handle
4972 // mismatched types.
4976 // Record this extraction against the appropriate vector if possible...
4977 SDValue SourceVec = V.getOperand(0);
4978 // If the element number isn't a constant, we can't effectively
4979 // analyze what's going on.
4980 if (!isa<ConstantSDNode>(V.getOperand(1)))
4982 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4983 bool FoundSource = false;
4984 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4985 if (SourceVecs[j] == SourceVec) {
4986 if (MinElts[j] > EltNo)
4988 if (MaxElts[j] < EltNo)
4995 // Or record a new source if not...
4997 SourceVecs.push_back(SourceVec);
4998 MinElts.push_back(EltNo);
4999 MaxElts.push_back(EltNo);
5003 // Currently only do something sane when at most two source vectors
5005 if (SourceVecs.size() > 2)
5008 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5009 int VEXTOffsets[2] = {0, 0};
5011 // This loop extracts the usage patterns of the source vectors
5012 // and prepares appropriate SDValues for a shuffle if possible.
5013 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5014 if (SourceVecs[i].getValueType() == VT) {
5015 // No VEXT necessary
5016 ShuffleSrcs[i] = SourceVecs[i];
5019 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5020 // It probably isn't worth padding out a smaller vector just to
5021 // break it down again in a shuffle.
5025 // Since only 64-bit and 128-bit vectors are legal on ARM and
5026 // we've eliminated the other cases...
5027 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5028 "unexpected vector sizes in ReconstructShuffle");
5030 if (MaxElts[i] - MinElts[i] >= NumElts) {
5031 // Span too large for a VEXT to cope
5035 if (MinElts[i] >= NumElts) {
5036 // The extraction can just take the second half
5037 VEXTOffsets[i] = NumElts;
5038 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5040 DAG.getIntPtrConstant(NumElts));
5041 } else if (MaxElts[i] < NumElts) {
5042 // The extraction can just take the first half
5044 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5046 DAG.getIntPtrConstant(0));
5048 // An actual VEXT is needed
5049 VEXTOffsets[i] = MinElts[i];
5050 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5052 DAG.getIntPtrConstant(0));
5053 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5055 DAG.getIntPtrConstant(NumElts));
5056 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5057 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5061 SmallVector<int, 8> Mask;
5063 for (unsigned i = 0; i < NumElts; ++i) {
5064 SDValue Entry = Op.getOperand(i);
5065 if (Entry.getOpcode() == ISD::UNDEF) {
5070 SDValue ExtractVec = Entry.getOperand(0);
5071 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5072 .getOperand(1))->getSExtValue();
5073 if (ExtractVec == SourceVecs[0]) {
5074 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5076 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5080 // Final check before we try to produce nonsense...
5081 if (isShuffleMaskLegal(Mask, VT))
5082 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5088 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5089 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5090 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5091 /// are assumed to be legal.
5093 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5095 if (VT.getVectorNumElements() == 4 &&
5096 (VT.is128BitVector() || VT.is64BitVector())) {
5097 unsigned PFIndexes[4];
5098 for (unsigned i = 0; i != 4; ++i) {
5102 PFIndexes[i] = M[i];
5105 // Compute the index in the perfect shuffle table.
5106 unsigned PFTableIndex =
5107 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5108 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5109 unsigned Cost = (PFEntry >> 30);
5116 unsigned Imm, WhichResult;
5118 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5119 return (EltSize >= 32 ||
5120 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5121 isVREVMask(M, VT, 64) ||
5122 isVREVMask(M, VT, 32) ||
5123 isVREVMask(M, VT, 16) ||
5124 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5125 isVTBLMask(M, VT) ||
5126 isVTRNMask(M, VT, WhichResult) ||
5127 isVUZPMask(M, VT, WhichResult) ||
5128 isVZIPMask(M, VT, WhichResult) ||
5129 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5130 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5131 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5132 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5135 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5136 /// the specified operations to build the shuffle.
5137 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5138 SDValue RHS, SelectionDAG &DAG,
5140 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5141 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5142 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5145 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5154 OP_VUZPL, // VUZP, left result
5155 OP_VUZPR, // VUZP, right result
5156 OP_VZIPL, // VZIP, left result
5157 OP_VZIPR, // VZIP, right result
5158 OP_VTRNL, // VTRN, left result
5159 OP_VTRNR // VTRN, right result
5162 if (OpNum == OP_COPY) {
5163 if (LHSID == (1*9+2)*9+3) return LHS;
5164 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5168 SDValue OpLHS, OpRHS;
5169 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5170 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5171 EVT VT = OpLHS.getValueType();
5174 default: llvm_unreachable("Unknown shuffle opcode!");
5176 // VREV divides the vector in half and swaps within the half.
5177 if (VT.getVectorElementType() == MVT::i32 ||
5178 VT.getVectorElementType() == MVT::f32)
5179 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5180 // vrev <4 x i16> -> VREV32
5181 if (VT.getVectorElementType() == MVT::i16)
5182 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5183 // vrev <4 x i8> -> VREV16
5184 assert(VT.getVectorElementType() == MVT::i8);
5185 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5190 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5191 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5195 return DAG.getNode(ARMISD::VEXT, dl, VT,
5197 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5200 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5201 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5204 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5205 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5208 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5209 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5213 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5214 ArrayRef<int> ShuffleMask,
5215 SelectionDAG &DAG) {
5216 // Check to see if we can use the VTBL instruction.
5217 SDValue V1 = Op.getOperand(0);
5218 SDValue V2 = Op.getOperand(1);
5221 SmallVector<SDValue, 8> VTBLMask;
5222 for (ArrayRef<int>::iterator
5223 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5224 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5226 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5227 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5228 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5231 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5232 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5236 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5237 SelectionDAG &DAG) {
5239 SDValue OpLHS = Op.getOperand(0);
5240 EVT VT = OpLHS.getValueType();
5242 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5243 "Expect an v8i16/v16i8 type");
5244 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5245 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5246 // extract the first 8 bytes into the top double word and the last 8 bytes
5247 // into the bottom double word. The v8i16 case is similar.
5248 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5249 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5250 DAG.getConstant(ExtractNum, MVT::i32));
5253 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5254 SDValue V1 = Op.getOperand(0);
5255 SDValue V2 = Op.getOperand(1);
5257 EVT VT = Op.getValueType();
5258 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5260 // Convert shuffles that are directly supported on NEON to target-specific
5261 // DAG nodes, instead of keeping them as shuffles and matching them again
5262 // during code selection. This is more efficient and avoids the possibility
5263 // of inconsistencies between legalization and selection.
5264 // FIXME: floating-point vectors should be canonicalized to integer vectors
5265 // of the same time so that they get CSEd properly.
5266 ArrayRef<int> ShuffleMask = SVN->getMask();
5268 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5269 if (EltSize <= 32) {
5270 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5271 int Lane = SVN->getSplatIndex();
5272 // If this is undef splat, generate it via "just" vdup, if possible.
5273 if (Lane == -1) Lane = 0;
5275 // Test if V1 is a SCALAR_TO_VECTOR.
5276 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5277 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5279 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5280 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5282 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5283 !isa<ConstantSDNode>(V1.getOperand(0))) {
5284 bool IsScalarToVector = true;
5285 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5286 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5287 IsScalarToVector = false;
5290 if (IsScalarToVector)
5291 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5293 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5294 DAG.getConstant(Lane, MVT::i32));
5299 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5302 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5303 DAG.getConstant(Imm, MVT::i32));
5306 if (isVREVMask(ShuffleMask, VT, 64))
5307 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5308 if (isVREVMask(ShuffleMask, VT, 32))
5309 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5310 if (isVREVMask(ShuffleMask, VT, 16))
5311 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5313 if (V2->getOpcode() == ISD::UNDEF &&
5314 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5315 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5316 DAG.getConstant(Imm, MVT::i32));
5319 // Check for Neon shuffles that modify both input vectors in place.
5320 // If both results are used, i.e., if there are two shuffles with the same
5321 // source operands and with masks corresponding to both results of one of
5322 // these operations, DAG memoization will ensure that a single node is
5323 // used for both shuffles.
5324 unsigned WhichResult;
5325 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5326 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5327 V1, V2).getValue(WhichResult);
5328 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5329 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5330 V1, V2).getValue(WhichResult);
5331 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5332 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5333 V1, V2).getValue(WhichResult);
5335 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5336 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5337 V1, V1).getValue(WhichResult);
5338 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5339 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5340 V1, V1).getValue(WhichResult);
5341 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5342 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5343 V1, V1).getValue(WhichResult);
5346 // If the shuffle is not directly supported and it has 4 elements, use
5347 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5348 unsigned NumElts = VT.getVectorNumElements();
5350 unsigned PFIndexes[4];
5351 for (unsigned i = 0; i != 4; ++i) {
5352 if (ShuffleMask[i] < 0)
5355 PFIndexes[i] = ShuffleMask[i];
5358 // Compute the index in the perfect shuffle table.
5359 unsigned PFTableIndex =
5360 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5361 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5362 unsigned Cost = (PFEntry >> 30);
5365 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5368 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5369 if (EltSize >= 32) {
5370 // Do the expansion with floating-point types, since that is what the VFP
5371 // registers are defined to use, and since i64 is not legal.
5372 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5373 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5374 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5375 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5376 SmallVector<SDValue, 8> Ops;
5377 for (unsigned i = 0; i < NumElts; ++i) {
5378 if (ShuffleMask[i] < 0)
5379 Ops.push_back(DAG.getUNDEF(EltVT));
5381 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5382 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5383 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5386 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5387 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5390 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5391 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5393 if (VT == MVT::v8i8) {
5394 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5395 if (NewOp.getNode())
5402 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5403 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5404 SDValue Lane = Op.getOperand(2);
5405 if (!isa<ConstantSDNode>(Lane))
5411 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5412 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5413 SDValue Lane = Op.getOperand(1);
5414 if (!isa<ConstantSDNode>(Lane))
5417 SDValue Vec = Op.getOperand(0);
5418 if (Op.getValueType() == MVT::i32 &&
5419 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5421 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5427 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5428 // The only time a CONCAT_VECTORS operation can have legal types is when
5429 // two 64-bit vectors are concatenated to a 128-bit vector.
5430 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5431 "unexpected CONCAT_VECTORS");
5433 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5434 SDValue Op0 = Op.getOperand(0);
5435 SDValue Op1 = Op.getOperand(1);
5436 if (Op0.getOpcode() != ISD::UNDEF)
5437 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5438 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5439 DAG.getIntPtrConstant(0));
5440 if (Op1.getOpcode() != ISD::UNDEF)
5441 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5442 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5443 DAG.getIntPtrConstant(1));
5444 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5447 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5448 /// element has been zero/sign-extended, depending on the isSigned parameter,
5449 /// from an integer type half its size.
5450 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5452 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5453 EVT VT = N->getValueType(0);
5454 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5455 SDNode *BVN = N->getOperand(0).getNode();
5456 if (BVN->getValueType(0) != MVT::v4i32 ||
5457 BVN->getOpcode() != ISD::BUILD_VECTOR)
5459 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5460 unsigned HiElt = 1 - LoElt;
5461 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5462 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5463 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5464 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5465 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5468 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5469 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5472 if (Hi0->isNullValue() && Hi1->isNullValue())
5478 if (N->getOpcode() != ISD::BUILD_VECTOR)
5481 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5482 SDNode *Elt = N->getOperand(i).getNode();
5483 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5484 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5485 unsigned HalfSize = EltSize / 2;
5487 if (!isIntN(HalfSize, C->getSExtValue()))
5490 if (!isUIntN(HalfSize, C->getZExtValue()))
5501 /// isSignExtended - Check if a node is a vector value that is sign-extended
5502 /// or a constant BUILD_VECTOR with sign-extended elements.
5503 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5504 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5506 if (isExtendedBUILD_VECTOR(N, DAG, true))
5511 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5512 /// or a constant BUILD_VECTOR with zero-extended elements.
5513 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5514 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5516 if (isExtendedBUILD_VECTOR(N, DAG, false))
5521 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5522 if (OrigVT.getSizeInBits() >= 64)
5525 assert(OrigVT.isSimple() && "Expecting a simple value type");
5527 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5528 switch (OrigSimpleTy) {
5529 default: llvm_unreachable("Unexpected Vector Type");
5538 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5539 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5540 /// We insert the required extension here to get the vector to fill a D register.
5541 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5544 unsigned ExtOpcode) {
5545 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5546 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5547 // 64-bits we need to insert a new extension so that it will be 64-bits.
5548 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5549 if (OrigTy.getSizeInBits() >= 64)
5552 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5553 EVT NewVT = getExtensionTo64Bits(OrigTy);
5555 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5558 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5559 /// does not do any sign/zero extension. If the original vector is less
5560 /// than 64 bits, an appropriate extension will be added after the load to
5561 /// reach a total size of 64 bits. We have to add the extension separately
5562 /// because ARM does not have a sign/zero extending load for vectors.
5563 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5564 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5566 // The load already has the right type.
5567 if (ExtendedTy == LD->getMemoryVT())
5568 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5569 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5570 LD->isNonTemporal(), LD->isInvariant(),
5571 LD->getAlignment());
5573 // We need to create a zextload/sextload. We cannot just create a load
5574 // followed by a zext/zext node because LowerMUL is also run during normal
5575 // operation legalization where we can't create illegal types.
5576 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5577 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5578 LD->getMemoryVT(), LD->isVolatile(),
5579 LD->isNonTemporal(), LD->getAlignment());
5582 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5583 /// extending load, or BUILD_VECTOR with extended elements, return the
5584 /// unextended value. The unextended vector should be 64 bits so that it can
5585 /// be used as an operand to a VMULL instruction. If the original vector size
5586 /// before extension is less than 64 bits we add a an extension to resize
5587 /// the vector to 64 bits.
5588 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5589 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5590 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5591 N->getOperand(0)->getValueType(0),
5595 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5596 return SkipLoadExtensionForVMULL(LD, DAG);
5598 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5599 // have been legalized as a BITCAST from v4i32.
5600 if (N->getOpcode() == ISD::BITCAST) {
5601 SDNode *BVN = N->getOperand(0).getNode();
5602 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5603 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5604 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5605 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5606 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5608 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5609 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5610 EVT VT = N->getValueType(0);
5611 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5612 unsigned NumElts = VT.getVectorNumElements();
5613 MVT TruncVT = MVT::getIntegerVT(EltSize);
5614 SmallVector<SDValue, 8> Ops;
5615 for (unsigned i = 0; i != NumElts; ++i) {
5616 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5617 const APInt &CInt = C->getAPIntValue();
5618 // Element types smaller than 32 bits are not legal, so use i32 elements.
5619 // The values are implicitly truncated so sext vs. zext doesn't matter.
5620 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5622 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5623 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5626 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5627 unsigned Opcode = N->getOpcode();
5628 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5629 SDNode *N0 = N->getOperand(0).getNode();
5630 SDNode *N1 = N->getOperand(1).getNode();
5631 return N0->hasOneUse() && N1->hasOneUse() &&
5632 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5637 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5638 unsigned Opcode = N->getOpcode();
5639 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5640 SDNode *N0 = N->getOperand(0).getNode();
5641 SDNode *N1 = N->getOperand(1).getNode();
5642 return N0->hasOneUse() && N1->hasOneUse() &&
5643 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5648 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5649 // Multiplications are only custom-lowered for 128-bit vectors so that
5650 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5651 EVT VT = Op.getValueType();
5652 assert(VT.is128BitVector() && VT.isInteger() &&
5653 "unexpected type for custom-lowering ISD::MUL");
5654 SDNode *N0 = Op.getOperand(0).getNode();
5655 SDNode *N1 = Op.getOperand(1).getNode();
5656 unsigned NewOpc = 0;
5658 bool isN0SExt = isSignExtended(N0, DAG);
5659 bool isN1SExt = isSignExtended(N1, DAG);
5660 if (isN0SExt && isN1SExt)
5661 NewOpc = ARMISD::VMULLs;
5663 bool isN0ZExt = isZeroExtended(N0, DAG);
5664 bool isN1ZExt = isZeroExtended(N1, DAG);
5665 if (isN0ZExt && isN1ZExt)
5666 NewOpc = ARMISD::VMULLu;
5667 else if (isN1SExt || isN1ZExt) {
5668 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5669 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5670 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5671 NewOpc = ARMISD::VMULLs;
5673 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5674 NewOpc = ARMISD::VMULLu;
5676 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5678 NewOpc = ARMISD::VMULLu;
5684 if (VT == MVT::v2i64)
5685 // Fall through to expand this. It is not legal.
5688 // Other vector multiplications are legal.
5693 // Legalize to a VMULL instruction.
5696 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5698 Op0 = SkipExtensionForVMULL(N0, DAG);
5699 assert(Op0.getValueType().is64BitVector() &&
5700 Op1.getValueType().is64BitVector() &&
5701 "unexpected types for extended operands to VMULL");
5702 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5705 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5706 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5713 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5714 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5715 EVT Op1VT = Op1.getValueType();
5716 return DAG.getNode(N0->getOpcode(), DL, VT,
5717 DAG.getNode(NewOpc, DL, VT,
5718 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5719 DAG.getNode(NewOpc, DL, VT,
5720 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5724 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5726 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5727 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5728 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5729 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5730 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5731 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5732 // Get reciprocal estimate.
5733 // float4 recip = vrecpeq_f32(yf);
5734 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5735 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5736 // Because char has a smaller range than uchar, we can actually get away
5737 // without any newton steps. This requires that we use a weird bias
5738 // of 0xb000, however (again, this has been exhaustively tested).
5739 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5740 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5741 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5742 Y = DAG.getConstant(0xb000, MVT::i32);
5743 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5744 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5745 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5746 // Convert back to short.
5747 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5748 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5753 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5755 // Convert to float.
5756 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5757 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5758 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5759 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5760 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5761 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5763 // Use reciprocal estimate and one refinement step.
5764 // float4 recip = vrecpeq_f32(yf);
5765 // recip *= vrecpsq_f32(yf, recip);
5766 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5767 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5768 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5769 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5771 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5772 // Because short has a smaller range than ushort, we can actually get away
5773 // with only a single newton step. This requires that we use a weird bias
5774 // of 89, however (again, this has been exhaustively tested).
5775 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5776 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5777 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5778 N1 = DAG.getConstant(0x89, MVT::i32);
5779 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5780 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5781 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5782 // Convert back to integer and return.
5783 // return vmovn_s32(vcvt_s32_f32(result));
5784 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5785 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5789 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5790 EVT VT = Op.getValueType();
5791 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5792 "unexpected type for custom-lowering ISD::SDIV");
5795 SDValue N0 = Op.getOperand(0);
5796 SDValue N1 = Op.getOperand(1);
5799 if (VT == MVT::v8i8) {
5800 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5801 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5803 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5804 DAG.getIntPtrConstant(4));
5805 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5806 DAG.getIntPtrConstant(4));
5807 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5808 DAG.getIntPtrConstant(0));
5809 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5810 DAG.getIntPtrConstant(0));
5812 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5813 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5815 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5816 N0 = LowerCONCAT_VECTORS(N0, DAG);
5818 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5821 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5824 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5825 EVT VT = Op.getValueType();
5826 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5827 "unexpected type for custom-lowering ISD::UDIV");
5830 SDValue N0 = Op.getOperand(0);
5831 SDValue N1 = Op.getOperand(1);
5834 if (VT == MVT::v8i8) {
5835 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5836 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5838 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5839 DAG.getIntPtrConstant(4));
5840 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5841 DAG.getIntPtrConstant(4));
5842 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5843 DAG.getIntPtrConstant(0));
5844 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5845 DAG.getIntPtrConstant(0));
5847 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5848 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5850 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5851 N0 = LowerCONCAT_VECTORS(N0, DAG);
5853 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5854 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5859 // v4i16 sdiv ... Convert to float.
5860 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5861 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5862 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5863 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5864 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5865 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5867 // Use reciprocal estimate and two refinement steps.
5868 // float4 recip = vrecpeq_f32(yf);
5869 // recip *= vrecpsq_f32(yf, recip);
5870 // recip *= vrecpsq_f32(yf, recip);
5871 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5872 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5873 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5874 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5876 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5877 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5878 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5880 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5881 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5882 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5883 // and that it will never cause us to return an answer too large).
5884 // float4 result = as_float4(as_int4(xf*recip) + 2);
5885 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5886 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5887 N1 = DAG.getConstant(2, MVT::i32);
5888 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5889 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5890 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5891 // Convert back to integer and return.
5892 // return vmovn_u32(vcvt_s32_f32(result));
5893 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5894 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5898 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5899 EVT VT = Op.getNode()->getValueType(0);
5900 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5903 bool ExtraOp = false;
5904 switch (Op.getOpcode()) {
5905 default: llvm_unreachable("Invalid code");
5906 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5907 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5908 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5909 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5913 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5915 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5916 Op.getOperand(1), Op.getOperand(2));
5919 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5920 assert(Subtarget->isTargetDarwin());
5922 // For iOS, we want to call an alternative entry point: __sincos_stret,
5923 // return values are passed via sret.
5925 SDValue Arg = Op.getOperand(0);
5926 EVT ArgVT = Arg.getValueType();
5927 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5929 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5930 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5932 // Pair of floats / doubles used to pass the result.
5933 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5935 // Create stack object for sret.
5936 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5937 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5938 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5939 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5945 Entry.Ty = RetTy->getPointerTo();
5946 Entry.isSExt = false;
5947 Entry.isZExt = false;
5948 Entry.isSRet = true;
5949 Args.push_back(Entry);
5953 Entry.isSExt = false;
5954 Entry.isZExt = false;
5955 Args.push_back(Entry);
5957 const char *LibcallName = (ArgVT == MVT::f64)
5958 ? "__sincos_stret" : "__sincosf_stret";
5959 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5962 CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5963 false, false, false, false, 0,
5964 CallingConv::C, /*isTaillCall=*/false,
5965 /*doesNotRet=*/false, /*isReturnValueUsed*/false,
5966 Callee, Args, DAG, dl);
5967 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5969 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
5970 MachinePointerInfo(), false, false, false, 0);
5972 // Address of cos field.
5973 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
5974 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
5975 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
5976 MachinePointerInfo(), false, false, false, 0);
5978 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
5979 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
5980 LoadSin.getValue(0), LoadCos.getValue(0));
5983 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5984 // Monotonic load/store is legal for all targets
5985 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5988 // Aquire/Release load/store is not legal for targets without a
5989 // dmb or equivalent available.
5994 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5995 SelectionDAG &DAG) {
5997 assert (Node->getValueType(0) == MVT::i64 &&
5998 "Only know how to expand i64 atomics");
5999 AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6001 SmallVector<SDValue, 6> Ops;
6002 Ops.push_back(Node->getOperand(0)); // Chain
6003 Ops.push_back(Node->getOperand(1)); // Ptr
6004 for(unsigned i=2; i<Node->getNumOperands(); i++) {
6006 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6007 Node->getOperand(i), DAG.getIntPtrConstant(0)));
6009 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6010 Node->getOperand(i), DAG.getIntPtrConstant(1)));
6012 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6014 DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6015 cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
6016 AN->getSynchScope());
6017 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6018 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6019 Results.push_back(Result.getValue(2));
6022 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6023 SmallVectorImpl<SDValue> &Results,
6025 const ARMSubtarget *Subtarget) {
6027 SDValue Cycles32, OutChain;
6029 if (Subtarget->hasPerfMon()) {
6030 // Under Power Management extensions, the cycle-count is:
6031 // mrc p15, #0, <Rt>, c9, c13, #0
6032 SDValue Ops[] = { N->getOperand(0), // Chain
6033 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6034 DAG.getConstant(15, MVT::i32),
6035 DAG.getConstant(0, MVT::i32),
6036 DAG.getConstant(9, MVT::i32),
6037 DAG.getConstant(13, MVT::i32),
6038 DAG.getConstant(0, MVT::i32)
6041 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6042 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6043 array_lengthof(Ops));
6044 OutChain = Cycles32.getValue(1);
6046 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6047 // there are older ARM CPUs that have implementation-specific ways of
6048 // obtaining this information (FIXME!).
6049 Cycles32 = DAG.getConstant(0, MVT::i32);
6050 OutChain = DAG.getEntryNode();
6054 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6055 Cycles32, DAG.getConstant(0, MVT::i32));
6056 Results.push_back(Cycles64);
6057 Results.push_back(OutChain);
6060 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6061 switch (Op.getOpcode()) {
6062 default: llvm_unreachable("Don't know how to custom lower this!");
6063 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6064 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6065 case ISD::GlobalAddress:
6066 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6067 LowerGlobalAddressELF(Op, DAG);
6068 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6069 case ISD::SELECT: return LowerSELECT(Op, DAG);
6070 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6071 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6072 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6073 case ISD::VASTART: return LowerVASTART(Op, DAG);
6074 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6075 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6076 case ISD::SINT_TO_FP:
6077 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6078 case ISD::FP_TO_SINT:
6079 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6080 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6081 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6082 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6083 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6084 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6085 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6086 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6088 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6091 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6092 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6093 case ISD::SRL_PARTS:
6094 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6095 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6096 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6097 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6098 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6099 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6100 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6101 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6102 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6103 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6104 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6105 case ISD::MUL: return LowerMUL(Op, DAG);
6106 case ISD::SDIV: return LowerSDIV(Op, DAG);
6107 case ISD::UDIV: return LowerUDIV(Op, DAG);
6111 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6112 case ISD::ATOMIC_LOAD:
6113 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6114 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6116 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6120 /// ReplaceNodeResults - Replace the results of node with an illegal result
6121 /// type with new values built out of custom code.
6122 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6123 SmallVectorImpl<SDValue>&Results,
6124 SelectionDAG &DAG) const {
6126 switch (N->getOpcode()) {
6128 llvm_unreachable("Don't know how to custom expand this!");
6130 Res = ExpandBITCAST(N, DAG);
6134 Res = Expand64BitShift(N, DAG, Subtarget);
6136 case ISD::READCYCLECOUNTER:
6137 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6139 case ISD::ATOMIC_STORE:
6140 case ISD::ATOMIC_LOAD:
6141 case ISD::ATOMIC_LOAD_ADD:
6142 case ISD::ATOMIC_LOAD_AND:
6143 case ISD::ATOMIC_LOAD_NAND:
6144 case ISD::ATOMIC_LOAD_OR:
6145 case ISD::ATOMIC_LOAD_SUB:
6146 case ISD::ATOMIC_LOAD_XOR:
6147 case ISD::ATOMIC_SWAP:
6148 case ISD::ATOMIC_CMP_SWAP:
6149 case ISD::ATOMIC_LOAD_MIN:
6150 case ISD::ATOMIC_LOAD_UMIN:
6151 case ISD::ATOMIC_LOAD_MAX:
6152 case ISD::ATOMIC_LOAD_UMAX:
6153 ReplaceATOMIC_OP_64(N, Results, DAG);
6157 Results.push_back(Res);
6160 //===----------------------------------------------------------------------===//
6161 // ARM Scheduler Hooks
6162 //===----------------------------------------------------------------------===//
6165 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6166 MachineBasicBlock *BB,
6167 unsigned Size) const {
6168 unsigned dest = MI->getOperand(0).getReg();
6169 unsigned ptr = MI->getOperand(1).getReg();
6170 unsigned oldval = MI->getOperand(2).getReg();
6171 unsigned newval = MI->getOperand(3).getReg();
6172 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6173 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6174 DebugLoc dl = MI->getDebugLoc();
6175 bool isThumb2 = Subtarget->isThumb2();
6177 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6178 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6179 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6180 (const TargetRegisterClass*)&ARM::GPRRegClass);
6183 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6184 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6185 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6188 unsigned ldrOpc, strOpc;
6189 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6191 MachineFunction *MF = BB->getParent();
6192 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6193 MachineFunction::iterator It = BB;
6194 ++It; // insert the new blocks after the current block
6196 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6197 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6198 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6199 MF->insert(It, loop1MBB);
6200 MF->insert(It, loop2MBB);
6201 MF->insert(It, exitMBB);
6203 // Transfer the remainder of BB and its successor edges to exitMBB.
6204 exitMBB->splice(exitMBB->begin(), BB,
6205 llvm::next(MachineBasicBlock::iterator(MI)),
6207 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6211 // fallthrough --> loop1MBB
6212 BB->addSuccessor(loop1MBB);
6215 // ldrex dest, [ptr]
6219 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6220 if (ldrOpc == ARM::t2LDREX)
6222 AddDefaultPred(MIB);
6223 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6224 .addReg(dest).addReg(oldval));
6225 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6226 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6227 BB->addSuccessor(loop2MBB);
6228 BB->addSuccessor(exitMBB);
6231 // strex scratch, newval, [ptr]
6235 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6236 if (strOpc == ARM::t2STREX)
6238 AddDefaultPred(MIB);
6239 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6240 .addReg(scratch).addImm(0));
6241 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6242 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6243 BB->addSuccessor(loop1MBB);
6244 BB->addSuccessor(exitMBB);
6250 MI->eraseFromParent(); // The instruction is gone now.
6256 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6257 unsigned Size, unsigned BinOpcode) const {
6258 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6259 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6261 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6262 MachineFunction *MF = BB->getParent();
6263 MachineFunction::iterator It = BB;
6266 unsigned dest = MI->getOperand(0).getReg();
6267 unsigned ptr = MI->getOperand(1).getReg();
6268 unsigned incr = MI->getOperand(2).getReg();
6269 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6270 DebugLoc dl = MI->getDebugLoc();
6271 bool isThumb2 = Subtarget->isThumb2();
6273 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6275 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6276 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6277 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6280 unsigned ldrOpc, strOpc;
6281 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6283 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6284 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6285 MF->insert(It, loopMBB);
6286 MF->insert(It, exitMBB);
6288 // Transfer the remainder of BB and its successor edges to exitMBB.
6289 exitMBB->splice(exitMBB->begin(), BB,
6290 llvm::next(MachineBasicBlock::iterator(MI)),
6292 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6294 const TargetRegisterClass *TRC = isThumb2 ?
6295 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6296 (const TargetRegisterClass*)&ARM::GPRRegClass;
6297 unsigned scratch = MRI.createVirtualRegister(TRC);
6298 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6302 // fallthrough --> loopMBB
6303 BB->addSuccessor(loopMBB);
6307 // <binop> scratch2, dest, incr
6308 // strex scratch, scratch2, ptr
6311 // fallthrough --> exitMBB
6313 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6314 if (ldrOpc == ARM::t2LDREX)
6316 AddDefaultPred(MIB);
6318 // operand order needs to go the other way for NAND
6319 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6320 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6321 addReg(incr).addReg(dest)).addReg(0);
6323 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6324 addReg(dest).addReg(incr)).addReg(0);
6327 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6328 if (strOpc == ARM::t2STREX)
6330 AddDefaultPred(MIB);
6331 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6332 .addReg(scratch).addImm(0));
6333 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6334 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6336 BB->addSuccessor(loopMBB);
6337 BB->addSuccessor(exitMBB);
6343 MI->eraseFromParent(); // The instruction is gone now.
6349 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6350 MachineBasicBlock *BB,
6353 ARMCC::CondCodes Cond) const {
6354 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6356 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6357 MachineFunction *MF = BB->getParent();
6358 MachineFunction::iterator It = BB;
6361 unsigned dest = MI->getOperand(0).getReg();
6362 unsigned ptr = MI->getOperand(1).getReg();
6363 unsigned incr = MI->getOperand(2).getReg();
6364 unsigned oldval = dest;
6365 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6366 DebugLoc dl = MI->getDebugLoc();
6367 bool isThumb2 = Subtarget->isThumb2();
6369 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6371 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6372 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6373 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6376 unsigned ldrOpc, strOpc, extendOpc;
6377 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6379 default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6381 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6384 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6391 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6392 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6393 MF->insert(It, loopMBB);
6394 MF->insert(It, exitMBB);
6396 // Transfer the remainder of BB and its successor edges to exitMBB.
6397 exitMBB->splice(exitMBB->begin(), BB,
6398 llvm::next(MachineBasicBlock::iterator(MI)),
6400 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6402 const TargetRegisterClass *TRC = isThumb2 ?
6403 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6404 (const TargetRegisterClass*)&ARM::GPRRegClass;
6405 unsigned scratch = MRI.createVirtualRegister(TRC);
6406 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6410 // fallthrough --> loopMBB
6411 BB->addSuccessor(loopMBB);
6415 // (sign extend dest, if required)
6417 // cmov.cond scratch2, incr, dest
6418 // strex scratch, scratch2, ptr
6421 // fallthrough --> exitMBB
6423 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6424 if (ldrOpc == ARM::t2LDREX)
6426 AddDefaultPred(MIB);
6428 // Sign extend the value, if necessary.
6429 if (signExtend && extendOpc) {
6430 oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6431 : &ARM::GPRnopcRegClass);
6433 MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6434 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6439 // Build compare and cmov instructions.
6440 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6441 .addReg(oldval).addReg(incr));
6442 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6443 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6445 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6446 if (strOpc == ARM::t2STREX)
6448 AddDefaultPred(MIB);
6449 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6450 .addReg(scratch).addImm(0));
6451 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6452 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6454 BB->addSuccessor(loopMBB);
6455 BB->addSuccessor(exitMBB);
6461 MI->eraseFromParent(); // The instruction is gone now.
6467 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6468 unsigned Op1, unsigned Op2,
6469 bool NeedsCarry, bool IsCmpxchg,
6470 bool IsMinMax, ARMCC::CondCodes CC) const {
6471 // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6472 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6474 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6475 MachineFunction *MF = BB->getParent();
6476 MachineFunction::iterator It = BB;
6479 bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6480 unsigned offset = (isStore ? -2 : 0);
6481 unsigned destlo = MI->getOperand(0).getReg();
6482 unsigned desthi = MI->getOperand(1).getReg();
6483 unsigned ptr = MI->getOperand(offset+2).getReg();
6484 unsigned vallo = MI->getOperand(offset+3).getReg();
6485 unsigned valhi = MI->getOperand(offset+4).getReg();
6486 unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6487 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6488 DebugLoc dl = MI->getDebugLoc();
6489 bool isThumb2 = Subtarget->isThumb2();
6491 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6493 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6494 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6495 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6496 MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6497 MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6500 unsigned ldrOpc, strOpc;
6501 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6503 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6504 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6505 if (IsCmpxchg || IsMinMax)
6506 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6508 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6509 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6511 MF->insert(It, loopMBB);
6512 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6513 if (IsCmpxchg) MF->insert(It, cont2BB);
6514 MF->insert(It, exitMBB);
6516 // Transfer the remainder of BB and its successor edges to exitMBB.
6517 exitMBB->splice(exitMBB->begin(), BB,
6518 llvm::next(MachineBasicBlock::iterator(MI)),
6520 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6522 const TargetRegisterClass *TRC = isThumb2 ?
6523 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6524 (const TargetRegisterClass*)&ARM::GPRRegClass;
6525 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6529 // fallthrough --> loopMBB
6530 BB->addSuccessor(loopMBB);
6533 // ldrexd r2, r3, ptr
6534 // <binopa> r0, r2, incr
6535 // <binopb> r1, r3, incr
6536 // strexd storesuccess, r0, r1, ptr
6537 // cmp storesuccess, #0
6539 // fallthrough --> exitMBB
6545 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6546 .addReg(destlo, RegState::Define)
6547 .addReg(desthi, RegState::Define)
6550 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6551 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6552 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6553 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6554 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6555 .addReg(GPRPair0, 0, ARM::gsub_0);
6556 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6557 .addReg(GPRPair0, 0, ARM::gsub_1);
6561 unsigned StoreLo, StoreHi;
6564 for (unsigned i = 0; i < 2; i++) {
6565 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6567 .addReg(i == 0 ? destlo : desthi)
6568 .addReg(i == 0 ? vallo : valhi));
6569 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6570 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6571 BB->addSuccessor(exitMBB);
6572 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6573 BB = (i == 0 ? contBB : cont2BB);
6576 // Copy to physregs for strexd
6577 StoreLo = MI->getOperand(5).getReg();
6578 StoreHi = MI->getOperand(6).getReg();
6580 // Perform binary operation
6581 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6582 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6583 .addReg(destlo).addReg(vallo))
6584 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6585 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6586 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6587 .addReg(desthi).addReg(valhi))
6588 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6593 // Copy to physregs for strexd
6598 // Compare and branch to exit block.
6599 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6600 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6601 BB->addSuccessor(exitMBB);
6602 BB->addSuccessor(contBB);
6610 MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6611 MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6612 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6613 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6615 // Marshal a pair...
6616 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6617 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6618 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6619 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6620 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6623 .addImm(ARM::gsub_0);
6624 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6627 .addImm(ARM::gsub_1);
6630 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6631 .addReg(StorePair).addReg(ptr));
6634 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6635 .addReg(storesuccess).addImm(0));
6636 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6637 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6639 BB->addSuccessor(loopMBB);
6640 BB->addSuccessor(exitMBB);
6646 MI->eraseFromParent(); // The instruction is gone now.
6652 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6654 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6656 unsigned destlo = MI->getOperand(0).getReg();
6657 unsigned desthi = MI->getOperand(1).getReg();
6658 unsigned ptr = MI->getOperand(2).getReg();
6659 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6660 DebugLoc dl = MI->getDebugLoc();
6661 bool isThumb2 = Subtarget->isThumb2();
6663 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6665 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6666 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6667 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6669 unsigned ldrOpc, strOpc;
6670 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6672 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6675 MIB.addReg(destlo, RegState::Define)
6676 .addReg(desthi, RegState::Define)
6680 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6681 MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6683 // Copy GPRPair0 into dest. (This copy will normally be coalesced.)
6684 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6685 .addReg(GPRPair0, 0, ARM::gsub_0);
6686 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6687 .addReg(GPRPair0, 0, ARM::gsub_1);
6689 AddDefaultPred(MIB);
6691 MI->eraseFromParent(); // The instruction is gone now.
6696 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6697 /// registers the function context.
6698 void ARMTargetLowering::
6699 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6700 MachineBasicBlock *DispatchBB, int FI) const {
6701 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6702 DebugLoc dl = MI->getDebugLoc();
6703 MachineFunction *MF = MBB->getParent();
6704 MachineRegisterInfo *MRI = &MF->getRegInfo();
6705 MachineConstantPool *MCP = MF->getConstantPool();
6706 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6707 const Function *F = MF->getFunction();
6709 bool isThumb = Subtarget->isThumb();
6710 bool isThumb2 = Subtarget->isThumb2();
6712 unsigned PCLabelId = AFI->createPICLabelUId();
6713 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6714 ARMConstantPoolValue *CPV =
6715 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6716 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6718 const TargetRegisterClass *TRC = isThumb ?
6719 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6720 (const TargetRegisterClass*)&ARM::GPRRegClass;
6722 // Grab constant pool and fixed stack memory operands.
6723 MachineMemOperand *CPMMO =
6724 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6725 MachineMemOperand::MOLoad, 4, 4);
6727 MachineMemOperand *FIMMOSt =
6728 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6729 MachineMemOperand::MOStore, 4, 4);
6731 // Load the address of the dispatch MBB into the jump buffer.
6733 // Incoming value: jbuf
6734 // ldr.n r5, LCPI1_1
6737 // str r5, [$jbuf, #+4] ; &jbuf[1]
6738 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6739 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6740 .addConstantPoolIndex(CPI)
6741 .addMemOperand(CPMMO));
6742 // Set the low bit because of thumb mode.
6743 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6745 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6746 .addReg(NewVReg1, RegState::Kill)
6748 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6749 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6750 .addReg(NewVReg2, RegState::Kill)
6752 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6753 .addReg(NewVReg3, RegState::Kill)
6755 .addImm(36) // &jbuf[1] :: pc
6756 .addMemOperand(FIMMOSt));
6757 } else if (isThumb) {
6758 // Incoming value: jbuf
6759 // ldr.n r1, LCPI1_4
6763 // add r2, $jbuf, #+4 ; &jbuf[1]
6765 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6766 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6767 .addConstantPoolIndex(CPI)
6768 .addMemOperand(CPMMO));
6769 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6770 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6771 .addReg(NewVReg1, RegState::Kill)
6773 // Set the low bit because of thumb mode.
6774 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6775 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6776 .addReg(ARM::CPSR, RegState::Define)
6778 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6779 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6780 .addReg(ARM::CPSR, RegState::Define)
6781 .addReg(NewVReg2, RegState::Kill)
6782 .addReg(NewVReg3, RegState::Kill));
6783 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6784 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6786 .addImm(36)); // &jbuf[1] :: pc
6787 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6788 .addReg(NewVReg4, RegState::Kill)
6789 .addReg(NewVReg5, RegState::Kill)
6791 .addMemOperand(FIMMOSt));
6793 // Incoming value: jbuf
6796 // str r1, [$jbuf, #+4] ; &jbuf[1]
6797 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6798 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6799 .addConstantPoolIndex(CPI)
6801 .addMemOperand(CPMMO));
6802 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6803 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6804 .addReg(NewVReg1, RegState::Kill)
6805 .addImm(PCLabelId));
6806 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6807 .addReg(NewVReg2, RegState::Kill)
6809 .addImm(36) // &jbuf[1] :: pc
6810 .addMemOperand(FIMMOSt));
6814 MachineBasicBlock *ARMTargetLowering::
6815 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6816 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6817 DebugLoc dl = MI->getDebugLoc();
6818 MachineFunction *MF = MBB->getParent();
6819 MachineRegisterInfo *MRI = &MF->getRegInfo();
6820 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6821 MachineFrameInfo *MFI = MF->getFrameInfo();
6822 int FI = MFI->getFunctionContextIndex();
6824 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6825 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6826 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6828 // Get a mapping of the call site numbers to all of the landing pads they're
6830 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6831 unsigned MaxCSNum = 0;
6832 MachineModuleInfo &MMI = MF->getMMI();
6833 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6835 if (!BB->isLandingPad()) continue;
6837 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6839 for (MachineBasicBlock::iterator
6840 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6841 if (!II->isEHLabel()) continue;
6843 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6844 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6846 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6847 for (SmallVectorImpl<unsigned>::iterator
6848 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6849 CSI != CSE; ++CSI) {
6850 CallSiteNumToLPad[*CSI].push_back(BB);
6851 MaxCSNum = std::max(MaxCSNum, *CSI);
6857 // Get an ordered list of the machine basic blocks for the jump table.
6858 std::vector<MachineBasicBlock*> LPadList;
6859 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6860 LPadList.reserve(CallSiteNumToLPad.size());
6861 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6862 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6863 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6864 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6865 LPadList.push_back(*II);
6866 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6870 assert(!LPadList.empty() &&
6871 "No landing pad destinations for the dispatch jump table!");
6873 // Create the jump table and associated information.
6874 MachineJumpTableInfo *JTI =
6875 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6876 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6877 unsigned UId = AFI->createJumpTableUId();
6878 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6880 // Create the MBBs for the dispatch code.
6882 // Shove the dispatch's address into the return slot in the function context.
6883 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6884 DispatchBB->setIsLandingPad();
6886 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6887 unsigned trap_opcode;
6888 if (Subtarget->isThumb())
6889 trap_opcode = ARM::tTRAP;
6891 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6893 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6894 DispatchBB->addSuccessor(TrapBB);
6896 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6897 DispatchBB->addSuccessor(DispContBB);
6900 MF->insert(MF->end(), DispatchBB);
6901 MF->insert(MF->end(), DispContBB);
6902 MF->insert(MF->end(), TrapBB);
6904 // Insert code into the entry block that creates and registers the function
6906 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6908 MachineMemOperand *FIMMOLd =
6909 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6910 MachineMemOperand::MOLoad |
6911 MachineMemOperand::MOVolatile, 4, 4);
6913 MachineInstrBuilder MIB;
6914 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6916 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6917 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6919 // Add a register mask with no preserved registers. This results in all
6920 // registers being marked as clobbered.
6921 MIB.addRegMask(RI.getNoPreservedMask());
6923 unsigned NumLPads = LPadList.size();
6924 if (Subtarget->isThumb2()) {
6925 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6926 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6929 .addMemOperand(FIMMOLd));
6931 if (NumLPads < 256) {
6932 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6934 .addImm(LPadList.size()));
6936 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6937 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6938 .addImm(NumLPads & 0xFFFF));
6940 unsigned VReg2 = VReg1;
6941 if ((NumLPads & 0xFFFF0000) != 0) {
6942 VReg2 = MRI->createVirtualRegister(TRC);
6943 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6945 .addImm(NumLPads >> 16));
6948 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6953 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6958 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6959 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6960 .addJumpTableIndex(MJTI)
6963 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6966 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6967 .addReg(NewVReg3, RegState::Kill)
6969 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6971 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6972 .addReg(NewVReg4, RegState::Kill)
6974 .addJumpTableIndex(MJTI)
6976 } else if (Subtarget->isThumb()) {
6977 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6978 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6981 .addMemOperand(FIMMOLd));
6983 if (NumLPads < 256) {
6984 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6988 MachineConstantPool *ConstantPool = MF->getConstantPool();
6989 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6990 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6992 // MachineConstantPool wants an explicit alignment.
6993 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6995 Align = getDataLayout()->getTypeAllocSize(C->getType());
6996 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6998 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6999 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7000 .addReg(VReg1, RegState::Define)
7001 .addConstantPoolIndex(Idx));
7002 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7007 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7012 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7013 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7014 .addReg(ARM::CPSR, RegState::Define)
7018 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7019 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7020 .addJumpTableIndex(MJTI)
7023 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7024 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7025 .addReg(ARM::CPSR, RegState::Define)
7026 .addReg(NewVReg2, RegState::Kill)
7029 MachineMemOperand *JTMMOLd =
7030 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7031 MachineMemOperand::MOLoad, 4, 4);
7033 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7034 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7035 .addReg(NewVReg4, RegState::Kill)
7037 .addMemOperand(JTMMOLd));
7039 unsigned NewVReg6 = NewVReg5;
7040 if (RelocM == Reloc::PIC_) {
7041 NewVReg6 = MRI->createVirtualRegister(TRC);
7042 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7043 .addReg(ARM::CPSR, RegState::Define)
7044 .addReg(NewVReg5, RegState::Kill)
7048 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7049 .addReg(NewVReg6, RegState::Kill)
7050 .addJumpTableIndex(MJTI)
7053 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7054 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7057 .addMemOperand(FIMMOLd));
7059 if (NumLPads < 256) {
7060 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7063 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7064 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7065 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7066 .addImm(NumLPads & 0xFFFF));
7068 unsigned VReg2 = VReg1;
7069 if ((NumLPads & 0xFFFF0000) != 0) {
7070 VReg2 = MRI->createVirtualRegister(TRC);
7071 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7073 .addImm(NumLPads >> 16));
7076 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7080 MachineConstantPool *ConstantPool = MF->getConstantPool();
7081 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7082 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7084 // MachineConstantPool wants an explicit alignment.
7085 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7087 Align = getDataLayout()->getTypeAllocSize(C->getType());
7088 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7090 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7091 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7092 .addReg(VReg1, RegState::Define)
7093 .addConstantPoolIndex(Idx)
7095 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7097 .addReg(VReg1, RegState::Kill));
7100 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7105 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7107 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7109 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7110 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7111 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7112 .addJumpTableIndex(MJTI)
7115 MachineMemOperand *JTMMOLd =
7116 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7117 MachineMemOperand::MOLoad, 4, 4);
7118 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7120 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7121 .addReg(NewVReg3, RegState::Kill)
7124 .addMemOperand(JTMMOLd));
7126 if (RelocM == Reloc::PIC_) {
7127 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7128 .addReg(NewVReg5, RegState::Kill)
7130 .addJumpTableIndex(MJTI)
7133 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7134 .addReg(NewVReg5, RegState::Kill)
7135 .addJumpTableIndex(MJTI)
7140 // Add the jump table entries as successors to the MBB.
7141 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7142 for (std::vector<MachineBasicBlock*>::iterator
7143 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7144 MachineBasicBlock *CurMBB = *I;
7145 if (SeenMBBs.insert(CurMBB))
7146 DispContBB->addSuccessor(CurMBB);
7149 // N.B. the order the invoke BBs are processed in doesn't matter here.
7150 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7151 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7152 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7153 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7154 MachineBasicBlock *BB = *I;
7156 // Remove the landing pad successor from the invoke block and replace it
7157 // with the new dispatch block.
7158 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7160 while (!Successors.empty()) {
7161 MachineBasicBlock *SMBB = Successors.pop_back_val();
7162 if (SMBB->isLandingPad()) {
7163 BB->removeSuccessor(SMBB);
7164 MBBLPads.push_back(SMBB);
7168 BB->addSuccessor(DispatchBB);
7170 // Find the invoke call and mark all of the callee-saved registers as
7171 // 'implicit defined' so that they're spilled. This prevents code from
7172 // moving instructions to before the EH block, where they will never be
7174 for (MachineBasicBlock::reverse_iterator
7175 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7176 if (!II->isCall()) continue;
7178 DenseMap<unsigned, bool> DefRegs;
7179 for (MachineInstr::mop_iterator
7180 OI = II->operands_begin(), OE = II->operands_end();
7182 if (!OI->isReg()) continue;
7183 DefRegs[OI->getReg()] = true;
7186 MachineInstrBuilder MIB(*MF, &*II);
7188 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7189 unsigned Reg = SavedRegs[i];
7190 if (Subtarget->isThumb2() &&
7191 !ARM::tGPRRegClass.contains(Reg) &&
7192 !ARM::hGPRRegClass.contains(Reg))
7194 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7196 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7199 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7206 // Mark all former landing pads as non-landing pads. The dispatch is the only
7208 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7209 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7210 (*I)->setIsLandingPad(false);
7212 // The instruction is gone now.
7213 MI->eraseFromParent();
7219 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7220 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7221 E = MBB->succ_end(); I != E; ++I)
7224 llvm_unreachable("Expecting a BB with two successors!");
7227 /// Return the load opcode for a given load size. If load size >= 8,
7228 /// neon opcode will be returned.
7229 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7231 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7232 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7234 return LdSize == 4 ? ARM::tLDRi
7235 : LdSize == 2 ? ARM::tLDRHi
7236 : LdSize == 1 ? ARM::tLDRBi : 0;
7238 return LdSize == 4 ? ARM::t2LDR_POST
7239 : LdSize == 2 ? ARM::t2LDRH_POST
7240 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7241 return LdSize == 4 ? ARM::LDR_POST_IMM
7242 : LdSize == 2 ? ARM::LDRH_POST
7243 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7246 /// Return the store opcode for a given store size. If store size >= 8,
7247 /// neon opcode will be returned.
7248 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7250 return StSize == 16 ? ARM::VST1q32wb_fixed
7251 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7253 return StSize == 4 ? ARM::tSTRi
7254 : StSize == 2 ? ARM::tSTRHi
7255 : StSize == 1 ? ARM::tSTRBi : 0;
7257 return StSize == 4 ? ARM::t2STR_POST
7258 : StSize == 2 ? ARM::t2STRH_POST
7259 : StSize == 1 ? ARM::t2STRB_POST : 0;
7260 return StSize == 4 ? ARM::STR_POST_IMM
7261 : StSize == 2 ? ARM::STRH_POST
7262 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7265 /// Emit a post-increment load operation with given size. The instructions
7266 /// will be added to BB at Pos.
7267 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7268 const TargetInstrInfo *TII, DebugLoc dl,
7269 unsigned LdSize, unsigned Data, unsigned AddrIn,
7270 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7271 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7272 assert(LdOpc != 0 && "Should have a load opcode");
7274 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7275 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7277 } else if (IsThumb1) {
7278 // load + update AddrIn
7279 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), 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(LdSize);
7285 AddDefaultPred(MIB);
7286 } else if (IsThumb2) {
7287 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7288 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7291 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7292 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7293 .addReg(0).addImm(LdSize));
7297 /// Emit a post-increment store operation with given size. The instructions
7298 /// will be added to BB at Pos.
7299 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7300 const TargetInstrInfo *TII, DebugLoc dl,
7301 unsigned StSize, unsigned Data, unsigned AddrIn,
7302 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7303 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7304 assert(StOpc != 0 && "Should have a store opcode");
7306 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7307 .addReg(AddrIn).addImm(0).addReg(Data));
7308 } else if (IsThumb1) {
7309 // store + update AddrIn
7310 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7311 .addReg(AddrIn).addImm(0));
7312 MachineInstrBuilder MIB =
7313 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7314 MIB = AddDefaultT1CC(MIB);
7315 MIB.addReg(AddrIn).addImm(StSize);
7316 AddDefaultPred(MIB);
7317 } else if (IsThumb2) {
7318 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7319 .addReg(Data).addReg(AddrIn).addImm(StSize));
7321 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7322 .addReg(Data).addReg(AddrIn).addReg(0)
7328 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7329 MachineBasicBlock *BB) const {
7330 // This pseudo instruction has 3 operands: dst, src, size
7331 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7332 // Otherwise, we will generate unrolled scalar copies.
7333 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7334 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7335 MachineFunction::iterator It = BB;
7338 unsigned dest = MI->getOperand(0).getReg();
7339 unsigned src = MI->getOperand(1).getReg();
7340 unsigned SizeVal = MI->getOperand(2).getImm();
7341 unsigned Align = MI->getOperand(3).getImm();
7342 DebugLoc dl = MI->getDebugLoc();
7344 MachineFunction *MF = BB->getParent();
7345 MachineRegisterInfo &MRI = MF->getRegInfo();
7346 unsigned UnitSize = 0;
7347 const TargetRegisterClass *TRC = 0;
7348 const TargetRegisterClass *VecTRC = 0;
7350 bool IsThumb1 = Subtarget->isThumb1Only();
7351 bool IsThumb2 = Subtarget->isThumb2();
7355 } else if (Align & 2) {
7358 // Check whether we can use NEON instructions.
7359 if (!MF->getFunction()->getAttributes().
7360 hasAttribute(AttributeSet::FunctionIndex,
7361 Attribute::NoImplicitFloat) &&
7362 Subtarget->hasNEON()) {
7363 if ((Align % 16 == 0) && SizeVal >= 16)
7365 else if ((Align % 8 == 0) && SizeVal >= 8)
7368 // Can't use NEON instructions.
7373 // Select the correct opcode and register class for unit size load/store
7374 bool IsNeon = UnitSize >= 8;
7375 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7376 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7378 VecTRC = UnitSize == 16
7379 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7381 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7384 unsigned BytesLeft = SizeVal % UnitSize;
7385 unsigned LoopSize = SizeVal - BytesLeft;
7387 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7388 // Use LDR and STR to copy.
7389 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7390 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7391 unsigned srcIn = src;
7392 unsigned destIn = dest;
7393 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7394 unsigned srcOut = MRI.createVirtualRegister(TRC);
7395 unsigned destOut = MRI.createVirtualRegister(TRC);
7396 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7397 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7398 IsThumb1, IsThumb2);
7399 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7400 IsThumb1, IsThumb2);
7405 // Handle the leftover bytes with LDRB and STRB.
7406 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7407 // [destOut] = STRB_POST(scratch, destIn, 1)
7408 for (unsigned i = 0; i < BytesLeft; i++) {
7409 unsigned srcOut = MRI.createVirtualRegister(TRC);
7410 unsigned destOut = MRI.createVirtualRegister(TRC);
7411 unsigned scratch = MRI.createVirtualRegister(TRC);
7412 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7413 IsThumb1, IsThumb2);
7414 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7415 IsThumb1, IsThumb2);
7419 MI->eraseFromParent(); // The instruction is gone now.
7423 // Expand the pseudo op to a loop.
7426 // movw varEnd, # --> with thumb2
7428 // ldrcp varEnd, idx --> without thumb2
7429 // fallthrough --> loopMBB
7431 // PHI varPhi, varEnd, varLoop
7432 // PHI srcPhi, src, srcLoop
7433 // PHI destPhi, dst, destLoop
7434 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7435 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7436 // subs varLoop, varPhi, #UnitSize
7438 // fallthrough --> exitMBB
7440 // epilogue to handle left-over bytes
7441 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7442 // [destOut] = STRB_POST(scratch, destLoop, 1)
7443 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7444 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7445 MF->insert(It, loopMBB);
7446 MF->insert(It, exitMBB);
7448 // Transfer the remainder of BB and its successor edges to exitMBB.
7449 exitMBB->splice(exitMBB->begin(), BB,
7450 llvm::next(MachineBasicBlock::iterator(MI)),
7452 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7454 // Load an immediate to varEnd.
7455 unsigned varEnd = MRI.createVirtualRegister(TRC);
7457 unsigned Vtmp = varEnd;
7458 if ((LoopSize & 0xFFFF0000) != 0)
7459 Vtmp = MRI.createVirtualRegister(TRC);
7460 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7461 .addImm(LoopSize & 0xFFFF));
7463 if ((LoopSize & 0xFFFF0000) != 0)
7464 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7465 .addReg(Vtmp).addImm(LoopSize >> 16));
7467 MachineConstantPool *ConstantPool = MF->getConstantPool();
7468 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7469 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7471 // MachineConstantPool wants an explicit alignment.
7472 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7474 Align = getDataLayout()->getTypeAllocSize(C->getType());
7475 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7478 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7479 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7481 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7482 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7484 BB->addSuccessor(loopMBB);
7486 // Generate the loop body:
7487 // varPhi = PHI(varLoop, varEnd)
7488 // srcPhi = PHI(srcLoop, src)
7489 // destPhi = PHI(destLoop, dst)
7490 MachineBasicBlock *entryBB = BB;
7492 unsigned varLoop = MRI.createVirtualRegister(TRC);
7493 unsigned varPhi = MRI.createVirtualRegister(TRC);
7494 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7495 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7496 unsigned destLoop = MRI.createVirtualRegister(TRC);
7497 unsigned destPhi = MRI.createVirtualRegister(TRC);
7499 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7500 .addReg(varLoop).addMBB(loopMBB)
7501 .addReg(varEnd).addMBB(entryBB);
7502 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7503 .addReg(srcLoop).addMBB(loopMBB)
7504 .addReg(src).addMBB(entryBB);
7505 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7506 .addReg(destLoop).addMBB(loopMBB)
7507 .addReg(dest).addMBB(entryBB);
7509 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7510 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7511 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7512 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7513 IsThumb1, IsThumb2);
7514 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7515 IsThumb1, IsThumb2);
7517 // Decrement loop variable by UnitSize.
7519 MachineInstrBuilder MIB =
7520 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7521 MIB = AddDefaultT1CC(MIB);
7522 MIB.addReg(varPhi).addImm(UnitSize);
7523 AddDefaultPred(MIB);
7525 MachineInstrBuilder MIB =
7526 BuildMI(*BB, BB->end(), dl,
7527 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7528 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7529 MIB->getOperand(5).setReg(ARM::CPSR);
7530 MIB->getOperand(5).setIsDef(true);
7532 BuildMI(*BB, BB->end(), dl,
7533 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7534 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7536 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7537 BB->addSuccessor(loopMBB);
7538 BB->addSuccessor(exitMBB);
7540 // Add epilogue to handle BytesLeft.
7542 MachineInstr *StartOfExit = exitMBB->begin();
7544 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7545 // [destOut] = STRB_POST(scratch, destLoop, 1)
7546 unsigned srcIn = srcLoop;
7547 unsigned destIn = destLoop;
7548 for (unsigned i = 0; i < BytesLeft; i++) {
7549 unsigned srcOut = MRI.createVirtualRegister(TRC);
7550 unsigned destOut = MRI.createVirtualRegister(TRC);
7551 unsigned scratch = MRI.createVirtualRegister(TRC);
7552 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7553 IsThumb1, IsThumb2);
7554 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7555 IsThumb1, IsThumb2);
7560 MI->eraseFromParent(); // The instruction is gone now.
7565 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7566 MachineBasicBlock *BB) const {
7567 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7568 DebugLoc dl = MI->getDebugLoc();
7569 bool isThumb2 = Subtarget->isThumb2();
7570 switch (MI->getOpcode()) {
7573 llvm_unreachable("Unexpected instr type to insert");
7575 // The Thumb2 pre-indexed stores have the same MI operands, they just
7576 // define them differently in the .td files from the isel patterns, so
7577 // they need pseudos.
7578 case ARM::t2STR_preidx:
7579 MI->setDesc(TII->get(ARM::t2STR_PRE));
7581 case ARM::t2STRB_preidx:
7582 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7584 case ARM::t2STRH_preidx:
7585 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7588 case ARM::STRi_preidx:
7589 case ARM::STRBi_preidx: {
7590 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7591 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7592 // Decode the offset.
7593 unsigned Offset = MI->getOperand(4).getImm();
7594 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7595 Offset = ARM_AM::getAM2Offset(Offset);
7599 MachineMemOperand *MMO = *MI->memoperands_begin();
7600 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7601 .addOperand(MI->getOperand(0)) // Rn_wb
7602 .addOperand(MI->getOperand(1)) // Rt
7603 .addOperand(MI->getOperand(2)) // Rn
7604 .addImm(Offset) // offset (skip GPR==zero_reg)
7605 .addOperand(MI->getOperand(5)) // pred
7606 .addOperand(MI->getOperand(6))
7607 .addMemOperand(MMO);
7608 MI->eraseFromParent();
7611 case ARM::STRr_preidx:
7612 case ARM::STRBr_preidx:
7613 case ARM::STRH_preidx: {
7615 switch (MI->getOpcode()) {
7616 default: llvm_unreachable("unexpected opcode!");
7617 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7618 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7619 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7621 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7622 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7623 MIB.addOperand(MI->getOperand(i));
7624 MI->eraseFromParent();
7627 case ARM::ATOMIC_LOAD_ADD_I8:
7628 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7629 case ARM::ATOMIC_LOAD_ADD_I16:
7630 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7631 case ARM::ATOMIC_LOAD_ADD_I32:
7632 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7634 case ARM::ATOMIC_LOAD_AND_I8:
7635 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7636 case ARM::ATOMIC_LOAD_AND_I16:
7637 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7638 case ARM::ATOMIC_LOAD_AND_I32:
7639 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7641 case ARM::ATOMIC_LOAD_OR_I8:
7642 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7643 case ARM::ATOMIC_LOAD_OR_I16:
7644 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7645 case ARM::ATOMIC_LOAD_OR_I32:
7646 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7648 case ARM::ATOMIC_LOAD_XOR_I8:
7649 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7650 case ARM::ATOMIC_LOAD_XOR_I16:
7651 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7652 case ARM::ATOMIC_LOAD_XOR_I32:
7653 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7655 case ARM::ATOMIC_LOAD_NAND_I8:
7656 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7657 case ARM::ATOMIC_LOAD_NAND_I16:
7658 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7659 case ARM::ATOMIC_LOAD_NAND_I32:
7660 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7662 case ARM::ATOMIC_LOAD_SUB_I8:
7663 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7664 case ARM::ATOMIC_LOAD_SUB_I16:
7665 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7666 case ARM::ATOMIC_LOAD_SUB_I32:
7667 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7669 case ARM::ATOMIC_LOAD_MIN_I8:
7670 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7671 case ARM::ATOMIC_LOAD_MIN_I16:
7672 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7673 case ARM::ATOMIC_LOAD_MIN_I32:
7674 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7676 case ARM::ATOMIC_LOAD_MAX_I8:
7677 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7678 case ARM::ATOMIC_LOAD_MAX_I16:
7679 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7680 case ARM::ATOMIC_LOAD_MAX_I32:
7681 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7683 case ARM::ATOMIC_LOAD_UMIN_I8:
7684 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7685 case ARM::ATOMIC_LOAD_UMIN_I16:
7686 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7687 case ARM::ATOMIC_LOAD_UMIN_I32:
7688 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7690 case ARM::ATOMIC_LOAD_UMAX_I8:
7691 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7692 case ARM::ATOMIC_LOAD_UMAX_I16:
7693 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7694 case ARM::ATOMIC_LOAD_UMAX_I32:
7695 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7697 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7698 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7699 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7701 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7702 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7703 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7705 case ARM::ATOMIC_LOAD_I64:
7706 return EmitAtomicLoad64(MI, BB);
7708 case ARM::ATOMIC_LOAD_ADD_I64:
7709 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7710 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7711 /*NeedsCarry*/ true);
7712 case ARM::ATOMIC_LOAD_SUB_I64:
7713 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7714 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7715 /*NeedsCarry*/ true);
7716 case ARM::ATOMIC_LOAD_OR_I64:
7717 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7718 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7719 case ARM::ATOMIC_LOAD_XOR_I64:
7720 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7721 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7722 case ARM::ATOMIC_LOAD_AND_I64:
7723 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7724 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7725 case ARM::ATOMIC_STORE_I64:
7726 case ARM::ATOMIC_SWAP_I64:
7727 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7728 case ARM::ATOMIC_CMP_SWAP_I64:
7729 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7730 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7731 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7732 case ARM::ATOMIC_LOAD_MIN_I64:
7733 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7734 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7735 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7736 /*IsMinMax*/ true, ARMCC::LT);
7737 case ARM::ATOMIC_LOAD_MAX_I64:
7738 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7739 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7740 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7741 /*IsMinMax*/ true, ARMCC::GE);
7742 case ARM::ATOMIC_LOAD_UMIN_I64:
7743 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7744 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7745 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7746 /*IsMinMax*/ true, ARMCC::LO);
7747 case ARM::ATOMIC_LOAD_UMAX_I64:
7748 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7749 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7750 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7751 /*IsMinMax*/ true, ARMCC::HS);
7753 case ARM::tMOVCCr_pseudo: {
7754 // To "insert" a SELECT_CC instruction, we actually have to insert the
7755 // diamond control-flow pattern. The incoming instruction knows the
7756 // destination vreg to set, the condition code register to branch on, the
7757 // true/false values to select between, and a branch opcode to use.
7758 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7759 MachineFunction::iterator It = BB;
7765 // cmpTY ccX, r1, r2
7767 // fallthrough --> copy0MBB
7768 MachineBasicBlock *thisMBB = BB;
7769 MachineFunction *F = BB->getParent();
7770 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7771 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7772 F->insert(It, copy0MBB);
7773 F->insert(It, sinkMBB);
7775 // Transfer the remainder of BB and its successor edges to sinkMBB.
7776 sinkMBB->splice(sinkMBB->begin(), BB,
7777 llvm::next(MachineBasicBlock::iterator(MI)),
7779 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7781 BB->addSuccessor(copy0MBB);
7782 BB->addSuccessor(sinkMBB);
7784 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7785 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7788 // %FalseValue = ...
7789 // # fallthrough to sinkMBB
7792 // Update machine-CFG edges
7793 BB->addSuccessor(sinkMBB);
7796 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7799 BuildMI(*BB, BB->begin(), dl,
7800 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7801 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7802 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7804 MI->eraseFromParent(); // The pseudo instruction is gone now.
7809 case ARM::BCCZi64: {
7810 // If there is an unconditional branch to the other successor, remove it.
7811 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7813 // Compare both parts that make up the double comparison separately for
7815 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7817 unsigned LHS1 = MI->getOperand(1).getReg();
7818 unsigned LHS2 = MI->getOperand(2).getReg();
7820 AddDefaultPred(BuildMI(BB, dl,
7821 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7822 .addReg(LHS1).addImm(0));
7823 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7824 .addReg(LHS2).addImm(0)
7825 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7827 unsigned RHS1 = MI->getOperand(3).getReg();
7828 unsigned RHS2 = MI->getOperand(4).getReg();
7829 AddDefaultPred(BuildMI(BB, dl,
7830 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7831 .addReg(LHS1).addReg(RHS1));
7832 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7833 .addReg(LHS2).addReg(RHS2)
7834 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7837 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7838 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7839 if (MI->getOperand(0).getImm() == ARMCC::NE)
7840 std::swap(destMBB, exitMBB);
7842 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7843 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7845 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7847 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7849 MI->eraseFromParent(); // The pseudo instruction is gone now.
7853 case ARM::Int_eh_sjlj_setjmp:
7854 case ARM::Int_eh_sjlj_setjmp_nofp:
7855 case ARM::tInt_eh_sjlj_setjmp:
7856 case ARM::t2Int_eh_sjlj_setjmp:
7857 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7858 EmitSjLjDispatchBlock(MI, BB);
7863 // To insert an ABS instruction, we have to insert the
7864 // diamond control-flow pattern. The incoming instruction knows the
7865 // source vreg to test against 0, the destination vreg to set,
7866 // the condition code register to branch on, the
7867 // true/false values to select between, and a branch opcode to use.
7872 // BCC (branch to SinkBB if V0 >= 0)
7873 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7874 // SinkBB: V1 = PHI(V2, V3)
7875 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7876 MachineFunction::iterator BBI = BB;
7878 MachineFunction *Fn = BB->getParent();
7879 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7880 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7881 Fn->insert(BBI, RSBBB);
7882 Fn->insert(BBI, SinkBB);
7884 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7885 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7886 bool isThumb2 = Subtarget->isThumb2();
7887 MachineRegisterInfo &MRI = Fn->getRegInfo();
7888 // In Thumb mode S must not be specified if source register is the SP or
7889 // PC and if destination register is the SP, so restrict register class
7890 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7891 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7892 (const TargetRegisterClass*)&ARM::GPRRegClass);
7894 // Transfer the remainder of BB and its successor edges to sinkMBB.
7895 SinkBB->splice(SinkBB->begin(), BB,
7896 llvm::next(MachineBasicBlock::iterator(MI)),
7898 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7900 BB->addSuccessor(RSBBB);
7901 BB->addSuccessor(SinkBB);
7903 // fall through to SinkMBB
7904 RSBBB->addSuccessor(SinkBB);
7906 // insert a cmp at the end of BB
7907 AddDefaultPred(BuildMI(BB, dl,
7908 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7909 .addReg(ABSSrcReg).addImm(0));
7911 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7913 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7914 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7916 // insert rsbri in RSBBB
7917 // Note: BCC and rsbri will be converted into predicated rsbmi
7918 // by if-conversion pass
7919 BuildMI(*RSBBB, RSBBB->begin(), dl,
7920 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7921 .addReg(ABSSrcReg, RegState::Kill)
7922 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7924 // insert PHI in SinkBB,
7925 // reuse ABSDstReg to not change uses of ABS instruction
7926 BuildMI(*SinkBB, SinkBB->begin(), dl,
7927 TII->get(ARM::PHI), ABSDstReg)
7928 .addReg(NewRsbDstReg).addMBB(RSBBB)
7929 .addReg(ABSSrcReg).addMBB(BB);
7931 // remove ABS instruction
7932 MI->eraseFromParent();
7934 // return last added BB
7937 case ARM::COPY_STRUCT_BYVAL_I32:
7939 return EmitStructByval(MI, BB);
7943 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7944 SDNode *Node) const {
7945 if (!MI->hasPostISelHook()) {
7946 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7947 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7951 const MCInstrDesc *MCID = &MI->getDesc();
7952 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7953 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7954 // operand is still set to noreg. If needed, set the optional operand's
7955 // register to CPSR, and remove the redundant implicit def.
7957 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7959 // Rename pseudo opcodes.
7960 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7962 const ARMBaseInstrInfo *TII =
7963 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7964 MCID = &TII->get(NewOpc);
7966 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7967 "converted opcode should be the same except for cc_out");
7971 // Add the optional cc_out operand
7972 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7974 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7976 // Any ARM instruction that sets the 's' bit should specify an optional
7977 // "cc_out" operand in the last operand position.
7978 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7979 assert(!NewOpc && "Optional cc_out operand required");
7982 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7983 // since we already have an optional CPSR def.
7984 bool definesCPSR = false;
7985 bool deadCPSR = false;
7986 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7988 const MachineOperand &MO = MI->getOperand(i);
7989 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7993 MI->RemoveOperand(i);
7998 assert(!NewOpc && "Optional cc_out operand required");
8001 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8003 assert(!MI->getOperand(ccOutIdx).getReg() &&
8004 "expect uninitialized optional cc_out operand");
8008 // If this instruction was defined with an optional CPSR def and its dag node
8009 // had a live implicit CPSR def, then activate the optional CPSR def.
8010 MachineOperand &MO = MI->getOperand(ccOutIdx);
8011 MO.setReg(ARM::CPSR);
8015 //===----------------------------------------------------------------------===//
8016 // ARM Optimization Hooks
8017 //===----------------------------------------------------------------------===//
8019 // Helper function that checks if N is a null or all ones constant.
8020 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8021 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8024 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8027 // Return true if N is conditionally 0 or all ones.
8028 // Detects these expressions where cc is an i1 value:
8030 // (select cc 0, y) [AllOnes=0]
8031 // (select cc y, 0) [AllOnes=0]
8032 // (zext cc) [AllOnes=0]
8033 // (sext cc) [AllOnes=0/1]
8034 // (select cc -1, y) [AllOnes=1]
8035 // (select cc y, -1) [AllOnes=1]
8037 // Invert is set when N is the null/all ones constant when CC is false.
8038 // OtherOp is set to the alternative value of N.
8039 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8040 SDValue &CC, bool &Invert,
8042 SelectionDAG &DAG) {
8043 switch (N->getOpcode()) {
8044 default: return false;
8046 CC = N->getOperand(0);
8047 SDValue N1 = N->getOperand(1);
8048 SDValue N2 = N->getOperand(2);
8049 if (isZeroOrAllOnes(N1, AllOnes)) {
8054 if (isZeroOrAllOnes(N2, AllOnes)) {
8061 case ISD::ZERO_EXTEND:
8062 // (zext cc) can never be the all ones value.
8066 case ISD::SIGN_EXTEND: {
8067 EVT VT = N->getValueType(0);
8068 CC = N->getOperand(0);
8069 if (CC.getValueType() != MVT::i1)
8073 // When looking for an AllOnes constant, N is an sext, and the 'other'
8075 OtherOp = DAG.getConstant(0, VT);
8076 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8077 // When looking for a 0 constant, N can be zext or sext.
8078 OtherOp = DAG.getConstant(1, VT);
8080 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8086 // Combine a constant select operand into its use:
8088 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8089 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8090 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8091 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8092 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8094 // The transform is rejected if the select doesn't have a constant operand that
8095 // is null, or all ones when AllOnes is set.
8097 // Also recognize sext/zext from i1:
8099 // (add (zext cc), x) -> (select cc (add x, 1), x)
8100 // (add (sext cc), x) -> (select cc (add x, -1), x)
8102 // These transformations eventually create predicated instructions.
8104 // @param N The node to transform.
8105 // @param Slct The N operand that is a select.
8106 // @param OtherOp The other N operand (x above).
8107 // @param DCI Context.
8108 // @param AllOnes Require the select constant to be all ones instead of null.
8109 // @returns The new node, or SDValue() on failure.
8111 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8112 TargetLowering::DAGCombinerInfo &DCI,
8113 bool AllOnes = false) {
8114 SelectionDAG &DAG = DCI.DAG;
8115 EVT VT = N->getValueType(0);
8116 SDValue NonConstantVal;
8119 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8120 NonConstantVal, DAG))
8123 // Slct is now know to be the desired identity constant when CC is true.
8124 SDValue TrueVal = OtherOp;
8125 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8126 OtherOp, NonConstantVal);
8127 // Unless SwapSelectOps says CC should be false.
8129 std::swap(TrueVal, FalseVal);
8131 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8132 CCOp, TrueVal, FalseVal);
8135 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8137 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8138 TargetLowering::DAGCombinerInfo &DCI) {
8139 SDValue N0 = N->getOperand(0);
8140 SDValue N1 = N->getOperand(1);
8141 if (N0.getNode()->hasOneUse()) {
8142 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8143 if (Result.getNode())
8146 if (N1.getNode()->hasOneUse()) {
8147 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8148 if (Result.getNode())
8154 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8155 // (only after legalization).
8156 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8157 TargetLowering::DAGCombinerInfo &DCI,
8158 const ARMSubtarget *Subtarget) {
8160 // Only perform optimization if after legalize, and if NEON is available. We
8161 // also expected both operands to be BUILD_VECTORs.
8162 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8163 || N0.getOpcode() != ISD::BUILD_VECTOR
8164 || N1.getOpcode() != ISD::BUILD_VECTOR)
8167 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8168 EVT VT = N->getValueType(0);
8169 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8172 // Check that the vector operands are of the right form.
8173 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8174 // operands, where N is the size of the formed vector.
8175 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8176 // index such that we have a pair wise add pattern.
8178 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8179 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8181 SDValue Vec = N0->getOperand(0)->getOperand(0);
8182 SDNode *V = Vec.getNode();
8183 unsigned nextIndex = 0;
8185 // For each operands to the ADD which are BUILD_VECTORs,
8186 // check to see if each of their operands are an EXTRACT_VECTOR with
8187 // the same vector and appropriate index.
8188 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8189 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8190 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8192 SDValue ExtVec0 = N0->getOperand(i);
8193 SDValue ExtVec1 = N1->getOperand(i);
8195 // First operand is the vector, verify its the same.
8196 if (V != ExtVec0->getOperand(0).getNode() ||
8197 V != ExtVec1->getOperand(0).getNode())
8200 // Second is the constant, verify its correct.
8201 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8202 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8204 // For the constant, we want to see all the even or all the odd.
8205 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8206 || C1->getZExtValue() != nextIndex+1)
8215 // Create VPADDL node.
8216 SelectionDAG &DAG = DCI.DAG;
8217 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8219 // Build operand list.
8220 SmallVector<SDValue, 8> Ops;
8221 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8222 TLI.getPointerTy()));
8224 // Input is the vector.
8227 // Get widened type and narrowed type.
8229 unsigned numElem = VT.getVectorNumElements();
8230 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8231 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8232 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8233 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8235 llvm_unreachable("Invalid vector element type for padd optimization.");
8238 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8239 widenType, &Ops[0], Ops.size());
8240 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8243 static SDValue findMUL_LOHI(SDValue V) {
8244 if (V->getOpcode() == ISD::UMUL_LOHI ||
8245 V->getOpcode() == ISD::SMUL_LOHI)
8250 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8251 TargetLowering::DAGCombinerInfo &DCI,
8252 const ARMSubtarget *Subtarget) {
8254 if (Subtarget->isThumb1Only()) return SDValue();
8256 // Only perform the checks after legalize when the pattern is available.
8257 if (DCI.isBeforeLegalize()) return SDValue();
8259 // Look for multiply add opportunities.
8260 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8261 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8262 // a glue link from the first add to the second add.
8263 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8264 // a S/UMLAL instruction.
8267 // \ / \ [no multiline comment]
8273 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8274 SDValue AddcOp0 = AddcNode->getOperand(0);
8275 SDValue AddcOp1 = AddcNode->getOperand(1);
8277 // Check if the two operands are from the same mul_lohi node.
8278 if (AddcOp0.getNode() == AddcOp1.getNode())
8281 assert(AddcNode->getNumValues() == 2 &&
8282 AddcNode->getValueType(0) == MVT::i32 &&
8283 "Expect ADDC with two result values. First: i32");
8285 // Check that we have a glued ADDC node.
8286 if (AddcNode->getValueType(1) != MVT::Glue)
8289 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8290 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8291 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8292 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8293 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8296 // Look for the glued ADDE.
8297 SDNode* AddeNode = AddcNode->getGluedUser();
8298 if (AddeNode == NULL)
8301 // Make sure it is really an ADDE.
8302 if (AddeNode->getOpcode() != ISD::ADDE)
8305 assert(AddeNode->getNumOperands() == 3 &&
8306 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8307 "ADDE node has the wrong inputs");
8309 // Check for the triangle shape.
8310 SDValue AddeOp0 = AddeNode->getOperand(0);
8311 SDValue AddeOp1 = AddeNode->getOperand(1);
8313 // Make sure that the ADDE operands are not coming from the same node.
8314 if (AddeOp0.getNode() == AddeOp1.getNode())
8317 // Find the MUL_LOHI node walking up ADDE's operands.
8318 bool IsLeftOperandMUL = false;
8319 SDValue MULOp = findMUL_LOHI(AddeOp0);
8320 if (MULOp == SDValue())
8321 MULOp = findMUL_LOHI(AddeOp1);
8323 IsLeftOperandMUL = true;
8324 if (MULOp == SDValue())
8327 // Figure out the right opcode.
8328 unsigned Opc = MULOp->getOpcode();
8329 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8331 // Figure out the high and low input values to the MLAL node.
8332 SDValue* HiMul = &MULOp;
8333 SDValue* HiAdd = NULL;
8334 SDValue* LoMul = NULL;
8335 SDValue* LowAdd = NULL;
8337 if (IsLeftOperandMUL)
8343 if (AddcOp0->getOpcode() == Opc) {
8347 if (AddcOp1->getOpcode() == Opc) {
8355 if (LoMul->getNode() != HiMul->getNode())
8358 // Create the merged node.
8359 SelectionDAG &DAG = DCI.DAG;
8361 // Build operand list.
8362 SmallVector<SDValue, 8> Ops;
8363 Ops.push_back(LoMul->getOperand(0));
8364 Ops.push_back(LoMul->getOperand(1));
8365 Ops.push_back(*LowAdd);
8366 Ops.push_back(*HiAdd);
8368 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8369 DAG.getVTList(MVT::i32, MVT::i32),
8370 &Ops[0], Ops.size());
8372 // Replace the ADDs' nodes uses by the MLA node's values.
8373 SDValue HiMLALResult(MLALNode.getNode(), 1);
8374 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8376 SDValue LoMLALResult(MLALNode.getNode(), 0);
8377 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8379 // Return original node to notify the driver to stop replacing.
8380 SDValue resNode(AddcNode, 0);
8384 /// PerformADDCCombine - Target-specific dag combine transform from
8385 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8386 static SDValue PerformADDCCombine(SDNode *N,
8387 TargetLowering::DAGCombinerInfo &DCI,
8388 const ARMSubtarget *Subtarget) {
8390 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8394 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8395 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8396 /// called with the default operands, and if that fails, with commuted
8398 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8399 TargetLowering::DAGCombinerInfo &DCI,
8400 const ARMSubtarget *Subtarget){
8402 // Attempt to create vpaddl for this add.
8403 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8404 if (Result.getNode())
8407 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8408 if (N0.getNode()->hasOneUse()) {
8409 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8410 if (Result.getNode()) return Result;
8415 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8417 static SDValue PerformADDCombine(SDNode *N,
8418 TargetLowering::DAGCombinerInfo &DCI,
8419 const ARMSubtarget *Subtarget) {
8420 SDValue N0 = N->getOperand(0);
8421 SDValue N1 = N->getOperand(1);
8423 // First try with the default operand order.
8424 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8425 if (Result.getNode())
8428 // If that didn't work, try again with the operands commuted.
8429 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8432 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8434 static SDValue PerformSUBCombine(SDNode *N,
8435 TargetLowering::DAGCombinerInfo &DCI) {
8436 SDValue N0 = N->getOperand(0);
8437 SDValue N1 = N->getOperand(1);
8439 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8440 if (N1.getNode()->hasOneUse()) {
8441 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8442 if (Result.getNode()) return Result;
8448 /// PerformVMULCombine
8449 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8450 /// special multiplier accumulator forwarding.
8456 // However, for (A + B) * (A + B),
8463 static SDValue PerformVMULCombine(SDNode *N,
8464 TargetLowering::DAGCombinerInfo &DCI,
8465 const ARMSubtarget *Subtarget) {
8466 if (!Subtarget->hasVMLxForwarding())
8469 SelectionDAG &DAG = DCI.DAG;
8470 SDValue N0 = N->getOperand(0);
8471 SDValue N1 = N->getOperand(1);
8472 unsigned Opcode = N0.getOpcode();
8473 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8474 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8475 Opcode = N1.getOpcode();
8476 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8477 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8485 EVT VT = N->getValueType(0);
8487 SDValue N00 = N0->getOperand(0);
8488 SDValue N01 = N0->getOperand(1);
8489 return DAG.getNode(Opcode, DL, VT,
8490 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8491 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8494 static SDValue PerformMULCombine(SDNode *N,
8495 TargetLowering::DAGCombinerInfo &DCI,
8496 const ARMSubtarget *Subtarget) {
8497 SelectionDAG &DAG = DCI.DAG;
8499 if (Subtarget->isThumb1Only())
8502 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8505 EVT VT = N->getValueType(0);
8506 if (VT.is64BitVector() || VT.is128BitVector())
8507 return PerformVMULCombine(N, DCI, Subtarget);
8511 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8515 int64_t MulAmt = C->getSExtValue();
8516 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8518 ShiftAmt = ShiftAmt & (32 - 1);
8519 SDValue V = N->getOperand(0);
8523 MulAmt >>= ShiftAmt;
8526 if (isPowerOf2_32(MulAmt - 1)) {
8527 // (mul x, 2^N + 1) => (add (shl x, N), x)
8528 Res = DAG.getNode(ISD::ADD, DL, VT,
8530 DAG.getNode(ISD::SHL, DL, VT,
8532 DAG.getConstant(Log2_32(MulAmt - 1),
8534 } else if (isPowerOf2_32(MulAmt + 1)) {
8535 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8536 Res = DAG.getNode(ISD::SUB, DL, VT,
8537 DAG.getNode(ISD::SHL, DL, VT,
8539 DAG.getConstant(Log2_32(MulAmt + 1),
8545 uint64_t MulAmtAbs = -MulAmt;
8546 if (isPowerOf2_32(MulAmtAbs + 1)) {
8547 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8548 Res = DAG.getNode(ISD::SUB, DL, VT,
8550 DAG.getNode(ISD::SHL, DL, VT,
8552 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8554 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8555 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8556 Res = DAG.getNode(ISD::ADD, DL, VT,
8558 DAG.getNode(ISD::SHL, DL, VT,
8560 DAG.getConstant(Log2_32(MulAmtAbs-1),
8562 Res = DAG.getNode(ISD::SUB, DL, VT,
8563 DAG.getConstant(0, MVT::i32),Res);
8570 Res = DAG.getNode(ISD::SHL, DL, VT,
8571 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8573 // Do not add new nodes to DAG combiner worklist.
8574 DCI.CombineTo(N, Res, false);
8578 static SDValue PerformANDCombine(SDNode *N,
8579 TargetLowering::DAGCombinerInfo &DCI,
8580 const ARMSubtarget *Subtarget) {
8582 // Attempt to use immediate-form VBIC
8583 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8585 EVT VT = N->getValueType(0);
8586 SelectionDAG &DAG = DCI.DAG;
8588 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8591 APInt SplatBits, SplatUndef;
8592 unsigned SplatBitSize;
8595 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8596 if (SplatBitSize <= 64) {
8598 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8599 SplatUndef.getZExtValue(), SplatBitSize,
8600 DAG, VbicVT, VT.is128BitVector(),
8602 if (Val.getNode()) {
8604 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8605 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8606 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8611 if (!Subtarget->isThumb1Only()) {
8612 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8613 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8614 if (Result.getNode())
8621 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8622 static SDValue PerformORCombine(SDNode *N,
8623 TargetLowering::DAGCombinerInfo &DCI,
8624 const ARMSubtarget *Subtarget) {
8625 // Attempt to use immediate-form VORR
8626 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8628 EVT VT = N->getValueType(0);
8629 SelectionDAG &DAG = DCI.DAG;
8631 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8634 APInt SplatBits, SplatUndef;
8635 unsigned SplatBitSize;
8637 if (BVN && Subtarget->hasNEON() &&
8638 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8639 if (SplatBitSize <= 64) {
8641 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8642 SplatUndef.getZExtValue(), SplatBitSize,
8643 DAG, VorrVT, VT.is128BitVector(),
8645 if (Val.getNode()) {
8647 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8648 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8649 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8654 if (!Subtarget->isThumb1Only()) {
8655 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8656 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8657 if (Result.getNode())
8661 // The code below optimizes (or (and X, Y), Z).
8662 // The AND operand needs to have a single user to make these optimizations
8664 SDValue N0 = N->getOperand(0);
8665 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8667 SDValue N1 = N->getOperand(1);
8669 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8670 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8671 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8673 unsigned SplatBitSize;
8676 APInt SplatBits0, SplatBits1;
8677 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8678 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8679 // Ensure that the second operand of both ands are constants
8680 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8681 HasAnyUndefs) && !HasAnyUndefs) {
8682 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8683 HasAnyUndefs) && !HasAnyUndefs) {
8684 // Ensure that the bit width of the constants are the same and that
8685 // the splat arguments are logical inverses as per the pattern we
8686 // are trying to simplify.
8687 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8688 SplatBits0 == ~SplatBits1) {
8689 // Canonicalize the vector type to make instruction selection
8691 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8692 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8696 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8702 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8705 // BFI is only available on V6T2+
8706 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8710 // 1) or (and A, mask), val => ARMbfi A, val, mask
8711 // iff (val & mask) == val
8713 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8714 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8715 // && mask == ~mask2
8716 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8717 // && ~mask == mask2
8718 // (i.e., copy a bitfield value into another bitfield of the same width)
8723 SDValue N00 = N0.getOperand(0);
8725 // The value and the mask need to be constants so we can verify this is
8726 // actually a bitfield set. If the mask is 0xffff, we can do better
8727 // via a movt instruction, so don't use BFI in that case.
8728 SDValue MaskOp = N0.getOperand(1);
8729 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8732 unsigned Mask = MaskC->getZExtValue();
8736 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8737 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8739 unsigned Val = N1C->getZExtValue();
8740 if ((Val & ~Mask) != Val)
8743 if (ARM::isBitFieldInvertedMask(Mask)) {
8744 Val >>= countTrailingZeros(~Mask);
8746 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8747 DAG.getConstant(Val, MVT::i32),
8748 DAG.getConstant(Mask, MVT::i32));
8750 // Do not add new nodes to DAG combiner worklist.
8751 DCI.CombineTo(N, Res, false);
8754 } else if (N1.getOpcode() == ISD::AND) {
8755 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8756 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8759 unsigned Mask2 = N11C->getZExtValue();
8761 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8763 if (ARM::isBitFieldInvertedMask(Mask) &&
8765 // The pack halfword instruction works better for masks that fit it,
8766 // so use that when it's available.
8767 if (Subtarget->hasT2ExtractPack() &&
8768 (Mask == 0xffff || Mask == 0xffff0000))
8771 unsigned amt = countTrailingZeros(Mask2);
8772 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8773 DAG.getConstant(amt, MVT::i32));
8774 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8775 DAG.getConstant(Mask, MVT::i32));
8776 // Do not add new nodes to DAG combiner worklist.
8777 DCI.CombineTo(N, Res, false);
8779 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8781 // The pack halfword instruction works better for masks that fit it,
8782 // so use that when it's available.
8783 if (Subtarget->hasT2ExtractPack() &&
8784 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8787 unsigned lsb = countTrailingZeros(Mask);
8788 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8789 DAG.getConstant(lsb, MVT::i32));
8790 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8791 DAG.getConstant(Mask2, MVT::i32));
8792 // Do not add new nodes to DAG combiner worklist.
8793 DCI.CombineTo(N, Res, false);
8798 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8799 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8800 ARM::isBitFieldInvertedMask(~Mask)) {
8801 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8802 // where lsb(mask) == #shamt and masked bits of B are known zero.
8803 SDValue ShAmt = N00.getOperand(1);
8804 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8805 unsigned LSB = countTrailingZeros(Mask);
8809 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8810 DAG.getConstant(~Mask, MVT::i32));
8812 // Do not add new nodes to DAG combiner worklist.
8813 DCI.CombineTo(N, Res, false);
8819 static SDValue PerformXORCombine(SDNode *N,
8820 TargetLowering::DAGCombinerInfo &DCI,
8821 const ARMSubtarget *Subtarget) {
8822 EVT VT = N->getValueType(0);
8823 SelectionDAG &DAG = DCI.DAG;
8825 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8828 if (!Subtarget->isThumb1Only()) {
8829 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8830 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8831 if (Result.getNode())
8838 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8839 /// the bits being cleared by the AND are not demanded by the BFI.
8840 static SDValue PerformBFICombine(SDNode *N,
8841 TargetLowering::DAGCombinerInfo &DCI) {
8842 SDValue N1 = N->getOperand(1);
8843 if (N1.getOpcode() == ISD::AND) {
8844 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8847 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8848 unsigned LSB = countTrailingZeros(~InvMask);
8849 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8850 unsigned Mask = (1 << Width)-1;
8851 unsigned Mask2 = N11C->getZExtValue();
8852 if ((Mask & (~Mask2)) == 0)
8853 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8854 N->getOperand(0), N1.getOperand(0),
8860 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8861 /// ARMISD::VMOVRRD.
8862 static SDValue PerformVMOVRRDCombine(SDNode *N,
8863 TargetLowering::DAGCombinerInfo &DCI) {
8864 // vmovrrd(vmovdrr x, y) -> x,y
8865 SDValue InDouble = N->getOperand(0);
8866 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8867 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8869 // vmovrrd(load f64) -> (load i32), (load i32)
8870 SDNode *InNode = InDouble.getNode();
8871 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8872 InNode->getValueType(0) == MVT::f64 &&
8873 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8874 !cast<LoadSDNode>(InNode)->isVolatile()) {
8875 // TODO: Should this be done for non-FrameIndex operands?
8876 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8878 SelectionDAG &DAG = DCI.DAG;
8880 SDValue BasePtr = LD->getBasePtr();
8881 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8882 LD->getPointerInfo(), LD->isVolatile(),
8883 LD->isNonTemporal(), LD->isInvariant(),
8884 LD->getAlignment());
8886 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8887 DAG.getConstant(4, MVT::i32));
8888 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8889 LD->getPointerInfo(), LD->isVolatile(),
8890 LD->isNonTemporal(), LD->isInvariant(),
8891 std::min(4U, LD->getAlignment() / 2));
8893 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8894 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8895 DCI.RemoveFromWorklist(LD);
8903 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8904 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8905 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8906 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8907 SDValue Op0 = N->getOperand(0);
8908 SDValue Op1 = N->getOperand(1);
8909 if (Op0.getOpcode() == ISD::BITCAST)
8910 Op0 = Op0.getOperand(0);
8911 if (Op1.getOpcode() == ISD::BITCAST)
8912 Op1 = Op1.getOperand(0);
8913 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8914 Op0.getNode() == Op1.getNode() &&
8915 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8916 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8917 N->getValueType(0), Op0.getOperand(0));
8921 /// PerformSTORECombine - Target-specific dag combine xforms for
8923 static SDValue PerformSTORECombine(SDNode *N,
8924 TargetLowering::DAGCombinerInfo &DCI) {
8925 StoreSDNode *St = cast<StoreSDNode>(N);
8926 if (St->isVolatile())
8929 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8930 // pack all of the elements in one place. Next, store to memory in fewer
8932 SDValue StVal = St->getValue();
8933 EVT VT = StVal.getValueType();
8934 if (St->isTruncatingStore() && VT.isVector()) {
8935 SelectionDAG &DAG = DCI.DAG;
8936 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8937 EVT StVT = St->getMemoryVT();
8938 unsigned NumElems = VT.getVectorNumElements();
8939 assert(StVT != VT && "Cannot truncate to the same type");
8940 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8941 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8943 // From, To sizes and ElemCount must be pow of two
8944 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8946 // We are going to use the original vector elt for storing.
8947 // Accumulated smaller vector elements must be a multiple of the store size.
8948 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8950 unsigned SizeRatio = FromEltSz / ToEltSz;
8951 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8953 // Create a type on which we perform the shuffle.
8954 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8955 NumElems*SizeRatio);
8956 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8959 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8960 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8961 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8963 // Can't shuffle using an illegal type.
8964 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8966 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8967 DAG.getUNDEF(WideVec.getValueType()),
8969 // At this point all of the data is stored at the bottom of the
8970 // register. We now need to save it to mem.
8972 // Find the largest store unit
8973 MVT StoreType = MVT::i8;
8974 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8975 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8976 MVT Tp = (MVT::SimpleValueType)tp;
8977 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8980 // Didn't find a legal store type.
8981 if (!TLI.isTypeLegal(StoreType))
8984 // Bitcast the original vector into a vector of store-size units
8985 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8986 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8987 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8988 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8989 SmallVector<SDValue, 8> Chains;
8990 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8991 TLI.getPointerTy());
8992 SDValue BasePtr = St->getBasePtr();
8994 // Perform one or more big stores into memory.
8995 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8996 for (unsigned I = 0; I < E; I++) {
8997 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8998 StoreType, ShuffWide,
8999 DAG.getIntPtrConstant(I));
9000 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9001 St->getPointerInfo(), St->isVolatile(),
9002 St->isNonTemporal(), St->getAlignment());
9003 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9005 Chains.push_back(Ch);
9007 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9011 if (!ISD::isNormalStore(St))
9014 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9015 // ARM stores of arguments in the same cache line.
9016 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9017 StVal.getNode()->hasOneUse()) {
9018 SelectionDAG &DAG = DCI.DAG;
9020 SDValue BasePtr = St->getBasePtr();
9021 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9022 StVal.getNode()->getOperand(0), BasePtr,
9023 St->getPointerInfo(), St->isVolatile(),
9024 St->isNonTemporal(), St->getAlignment());
9026 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9027 DAG.getConstant(4, MVT::i32));
9028 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9029 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9030 St->isNonTemporal(),
9031 std::min(4U, St->getAlignment() / 2));
9034 if (StVal.getValueType() != MVT::i64 ||
9035 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9038 // Bitcast an i64 store extracted from a vector to f64.
9039 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9040 SelectionDAG &DAG = DCI.DAG;
9042 SDValue IntVec = StVal.getOperand(0);
9043 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9044 IntVec.getValueType().getVectorNumElements());
9045 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9046 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9047 Vec, StVal.getOperand(1));
9049 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9050 // Make the DAGCombiner fold the bitcasts.
9051 DCI.AddToWorklist(Vec.getNode());
9052 DCI.AddToWorklist(ExtElt.getNode());
9053 DCI.AddToWorklist(V.getNode());
9054 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9055 St->getPointerInfo(), St->isVolatile(),
9056 St->isNonTemporal(), St->getAlignment(),
9060 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9061 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9062 /// i64 vector to have f64 elements, since the value can then be loaded
9063 /// directly into a VFP register.
9064 static bool hasNormalLoadOperand(SDNode *N) {
9065 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9066 for (unsigned i = 0; i < NumElts; ++i) {
9067 SDNode *Elt = N->getOperand(i).getNode();
9068 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9074 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9075 /// ISD::BUILD_VECTOR.
9076 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9077 TargetLowering::DAGCombinerInfo &DCI){
9078 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9079 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9080 // into a pair of GPRs, which is fine when the value is used as a scalar,
9081 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9082 SelectionDAG &DAG = DCI.DAG;
9083 if (N->getNumOperands() == 2) {
9084 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9089 // Load i64 elements as f64 values so that type legalization does not split
9090 // them up into i32 values.
9091 EVT VT = N->getValueType(0);
9092 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9095 SmallVector<SDValue, 8> Ops;
9096 unsigned NumElts = VT.getVectorNumElements();
9097 for (unsigned i = 0; i < NumElts; ++i) {
9098 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9100 // Make the DAGCombiner fold the bitcast.
9101 DCI.AddToWorklist(V.getNode());
9103 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9104 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9105 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9108 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9110 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9111 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9112 // At that time, we may have inserted bitcasts from integer to float.
9113 // If these bitcasts have survived DAGCombine, change the lowering of this
9114 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9115 // force to use floating point types.
9117 // Make sure we can change the type of the vector.
9118 // This is possible iff:
9119 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9120 // 1.1. Vector is used only once.
9121 // 1.2. Use is a bit convert to an integer type.
9122 // 2. The size of its operands are 32-bits (64-bits are not legal).
9123 EVT VT = N->getValueType(0);
9124 EVT EltVT = VT.getVectorElementType();
9126 // Check 1.1. and 2.
9127 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9130 // By construction, the input type must be float.
9131 assert(EltVT == MVT::f32 && "Unexpected type!");
9134 SDNode *Use = *N->use_begin();
9135 if (Use->getOpcode() != ISD::BITCAST ||
9136 Use->getValueType(0).isFloatingPoint())
9139 // Check profitability.
9140 // Model is, if more than half of the relevant operands are bitcast from
9141 // i32, turn the build_vector into a sequence of insert_vector_elt.
9142 // Relevant operands are everything that is not statically
9143 // (i.e., at compile time) bitcasted.
9144 unsigned NumOfBitCastedElts = 0;
9145 unsigned NumElts = VT.getVectorNumElements();
9146 unsigned NumOfRelevantElts = NumElts;
9147 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9148 SDValue Elt = N->getOperand(Idx);
9149 if (Elt->getOpcode() == ISD::BITCAST) {
9150 // Assume only bit cast to i32 will go away.
9151 if (Elt->getOperand(0).getValueType() == MVT::i32)
9152 ++NumOfBitCastedElts;
9153 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9154 // Constants are statically casted, thus do not count them as
9155 // relevant operands.
9156 --NumOfRelevantElts;
9159 // Check if more than half of the elements require a non-free bitcast.
9160 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9163 SelectionDAG &DAG = DCI.DAG;
9164 // Create the new vector type.
9165 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9166 // Check if the type is legal.
9167 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9168 if (!TLI.isTypeLegal(VecVT))
9172 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9173 // => BITCAST INSERT_VECTOR_ELT
9174 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9176 SDValue Vec = DAG.getUNDEF(VecVT);
9178 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9179 SDValue V = N->getOperand(Idx);
9180 if (V.getOpcode() == ISD::UNDEF)
9182 if (V.getOpcode() == ISD::BITCAST &&
9183 V->getOperand(0).getValueType() == MVT::i32)
9184 // Fold obvious case.
9185 V = V.getOperand(0);
9187 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9188 // Make the DAGCombiner fold the bitcasts.
9189 DCI.AddToWorklist(V.getNode());
9191 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9192 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9194 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9195 // Make the DAGCombiner fold the bitcasts.
9196 DCI.AddToWorklist(Vec.getNode());
9200 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9201 /// ISD::INSERT_VECTOR_ELT.
9202 static SDValue PerformInsertEltCombine(SDNode *N,
9203 TargetLowering::DAGCombinerInfo &DCI) {
9204 // Bitcast an i64 load inserted into a vector to f64.
9205 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9206 EVT VT = N->getValueType(0);
9207 SDNode *Elt = N->getOperand(1).getNode();
9208 if (VT.getVectorElementType() != MVT::i64 ||
9209 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9212 SelectionDAG &DAG = DCI.DAG;
9214 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9215 VT.getVectorNumElements());
9216 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9217 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9218 // Make the DAGCombiner fold the bitcasts.
9219 DCI.AddToWorklist(Vec.getNode());
9220 DCI.AddToWorklist(V.getNode());
9221 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9222 Vec, V, N->getOperand(2));
9223 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9226 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9227 /// ISD::VECTOR_SHUFFLE.
9228 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9229 // The LLVM shufflevector instruction does not require the shuffle mask
9230 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9231 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9232 // operands do not match the mask length, they are extended by concatenating
9233 // them with undef vectors. That is probably the right thing for other
9234 // targets, but for NEON it is better to concatenate two double-register
9235 // size vector operands into a single quad-register size vector. Do that
9236 // transformation here:
9237 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9238 // shuffle(concat(v1, v2), undef)
9239 SDValue Op0 = N->getOperand(0);
9240 SDValue Op1 = N->getOperand(1);
9241 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9242 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9243 Op0.getNumOperands() != 2 ||
9244 Op1.getNumOperands() != 2)
9246 SDValue Concat0Op1 = Op0.getOperand(1);
9247 SDValue Concat1Op1 = Op1.getOperand(1);
9248 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9249 Concat1Op1.getOpcode() != ISD::UNDEF)
9251 // Skip the transformation if any of the types are illegal.
9252 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9253 EVT VT = N->getValueType(0);
9254 if (!TLI.isTypeLegal(VT) ||
9255 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9256 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9259 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9260 Op0.getOperand(0), Op1.getOperand(0));
9261 // Translate the shuffle mask.
9262 SmallVector<int, 16> NewMask;
9263 unsigned NumElts = VT.getVectorNumElements();
9264 unsigned HalfElts = NumElts/2;
9265 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9266 for (unsigned n = 0; n < NumElts; ++n) {
9267 int MaskElt = SVN->getMaskElt(n);
9269 if (MaskElt < (int)HalfElts)
9271 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9272 NewElt = HalfElts + MaskElt - NumElts;
9273 NewMask.push_back(NewElt);
9275 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9276 DAG.getUNDEF(VT), NewMask.data());
9279 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9280 /// NEON load/store intrinsics to merge base address updates.
9281 static SDValue CombineBaseUpdate(SDNode *N,
9282 TargetLowering::DAGCombinerInfo &DCI) {
9283 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9286 SelectionDAG &DAG = DCI.DAG;
9287 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9288 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9289 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9290 SDValue Addr = N->getOperand(AddrOpIdx);
9292 // Search for a use of the address operand that is an increment.
9293 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9294 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9296 if (User->getOpcode() != ISD::ADD ||
9297 UI.getUse().getResNo() != Addr.getResNo())
9300 // Check that the add is independent of the load/store. Otherwise, folding
9301 // it would create a cycle.
9302 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9305 // Find the new opcode for the updating load/store.
9307 bool isLaneOp = false;
9308 unsigned NewOpc = 0;
9309 unsigned NumVecs = 0;
9311 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9313 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9314 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9316 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9318 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9320 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9322 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9323 NumVecs = 2; isLaneOp = true; break;
9324 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9325 NumVecs = 3; isLaneOp = true; break;
9326 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9327 NumVecs = 4; isLaneOp = true; break;
9328 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9329 NumVecs = 1; isLoad = false; break;
9330 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9331 NumVecs = 2; isLoad = false; break;
9332 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9333 NumVecs = 3; isLoad = false; break;
9334 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9335 NumVecs = 4; isLoad = false; break;
9336 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9337 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9338 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9339 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9340 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9341 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9345 switch (N->getOpcode()) {
9346 default: llvm_unreachable("unexpected opcode for Neon base update");
9347 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9348 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9349 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9353 // Find the size of memory referenced by the load/store.
9356 VecTy = N->getValueType(0);
9358 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9359 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9361 NumBytes /= VecTy.getVectorNumElements();
9363 // If the increment is a constant, it must match the memory ref size.
9364 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9365 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9366 uint64_t IncVal = CInc->getZExtValue();
9367 if (IncVal != NumBytes)
9369 } else if (NumBytes >= 3 * 16) {
9370 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9371 // separate instructions that make it harder to use a non-constant update.
9375 // Create the new updating load/store node.
9377 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9379 for (n = 0; n < NumResultVecs; ++n)
9381 Tys[n++] = MVT::i32;
9382 Tys[n] = MVT::Other;
9383 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9384 SmallVector<SDValue, 8> Ops;
9385 Ops.push_back(N->getOperand(0)); // incoming chain
9386 Ops.push_back(N->getOperand(AddrOpIdx));
9388 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9389 Ops.push_back(N->getOperand(i));
9391 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9392 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9393 Ops.data(), Ops.size(),
9394 MemInt->getMemoryVT(),
9395 MemInt->getMemOperand());
9398 std::vector<SDValue> NewResults;
9399 for (unsigned i = 0; i < NumResultVecs; ++i) {
9400 NewResults.push_back(SDValue(UpdN.getNode(), i));
9402 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9403 DCI.CombineTo(N, NewResults);
9404 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9411 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9412 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9413 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9415 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9416 SelectionDAG &DAG = DCI.DAG;
9417 EVT VT = N->getValueType(0);
9418 // vldN-dup instructions only support 64-bit vectors for N > 1.
9419 if (!VT.is64BitVector())
9422 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9423 SDNode *VLD = N->getOperand(0).getNode();
9424 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9426 unsigned NumVecs = 0;
9427 unsigned NewOpc = 0;
9428 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9429 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9431 NewOpc = ARMISD::VLD2DUP;
9432 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9434 NewOpc = ARMISD::VLD3DUP;
9435 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9437 NewOpc = ARMISD::VLD4DUP;
9442 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9443 // numbers match the load.
9444 unsigned VLDLaneNo =
9445 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9446 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9448 // Ignore uses of the chain result.
9449 if (UI.getUse().getResNo() == NumVecs)
9452 if (User->getOpcode() != ARMISD::VDUPLANE ||
9453 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9457 // Create the vldN-dup node.
9460 for (n = 0; n < NumVecs; ++n)
9462 Tys[n] = MVT::Other;
9463 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9464 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9465 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9466 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9467 Ops, 2, VLDMemInt->getMemoryVT(),
9468 VLDMemInt->getMemOperand());
9471 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9473 unsigned ResNo = UI.getUse().getResNo();
9474 // Ignore uses of the chain result.
9475 if (ResNo == NumVecs)
9478 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9481 // Now the vldN-lane intrinsic is dead except for its chain result.
9482 // Update uses of the chain.
9483 std::vector<SDValue> VLDDupResults;
9484 for (unsigned n = 0; n < NumVecs; ++n)
9485 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9486 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9487 DCI.CombineTo(VLD, VLDDupResults);
9492 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9493 /// ARMISD::VDUPLANE.
9494 static SDValue PerformVDUPLANECombine(SDNode *N,
9495 TargetLowering::DAGCombinerInfo &DCI) {
9496 SDValue Op = N->getOperand(0);
9498 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9499 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9500 if (CombineVLDDUP(N, DCI))
9501 return SDValue(N, 0);
9503 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9504 // redundant. Ignore bit_converts for now; element sizes are checked below.
9505 while (Op.getOpcode() == ISD::BITCAST)
9506 Op = Op.getOperand(0);
9507 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9510 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9511 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9512 // The canonical VMOV for a zero vector uses a 32-bit element size.
9513 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9515 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9517 EVT VT = N->getValueType(0);
9518 if (EltSize > VT.getVectorElementType().getSizeInBits())
9521 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9524 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9525 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9526 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9530 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9532 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9537 APFloat APF = C->getValueAPF();
9538 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9539 != APFloat::opOK || !isExact)
9542 c0 = (I == 0) ? cN : c0;
9543 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9550 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9551 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9552 /// when the VMUL has a constant operand that is a power of 2.
9554 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9555 /// vmul.f32 d16, d17, d16
9556 /// vcvt.s32.f32 d16, d16
9558 /// vcvt.s32.f32 d16, d16, #3
9559 static SDValue PerformVCVTCombine(SDNode *N,
9560 TargetLowering::DAGCombinerInfo &DCI,
9561 const ARMSubtarget *Subtarget) {
9562 SelectionDAG &DAG = DCI.DAG;
9563 SDValue Op = N->getOperand(0);
9565 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9566 Op.getOpcode() != ISD::FMUL)
9570 SDValue N0 = Op->getOperand(0);
9571 SDValue ConstVec = Op->getOperand(1);
9572 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9574 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9575 !isConstVecPow2(ConstVec, isSigned, C))
9578 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9579 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9580 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9581 // These instructions only exist converting from f32 to i32. We can handle
9582 // smaller integers by generating an extra truncate, but larger ones would
9587 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9588 Intrinsic::arm_neon_vcvtfp2fxu;
9589 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9590 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9591 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9592 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9593 DAG.getConstant(Log2_64(C), MVT::i32));
9595 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9596 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9601 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9602 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9603 /// when the VDIV has a constant operand that is a power of 2.
9605 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9606 /// vcvt.f32.s32 d16, d16
9607 /// vdiv.f32 d16, d17, d16
9609 /// vcvt.f32.s32 d16, d16, #3
9610 static SDValue PerformVDIVCombine(SDNode *N,
9611 TargetLowering::DAGCombinerInfo &DCI,
9612 const ARMSubtarget *Subtarget) {
9613 SelectionDAG &DAG = DCI.DAG;
9614 SDValue Op = N->getOperand(0);
9615 unsigned OpOpcode = Op.getNode()->getOpcode();
9617 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9618 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9622 SDValue ConstVec = N->getOperand(1);
9623 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9625 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9626 !isConstVecPow2(ConstVec, isSigned, C))
9629 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9630 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9631 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9632 // These instructions only exist converting from i32 to f32. We can handle
9633 // smaller integers by generating an extra extend, but larger ones would
9638 SDValue ConvInput = Op.getOperand(0);
9639 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9640 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9641 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9642 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9645 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9646 Intrinsic::arm_neon_vcvtfxu2fp;
9647 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9649 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9650 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9653 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9654 /// operand of a vector shift operation, where all the elements of the
9655 /// build_vector must have the same constant integer value.
9656 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9657 // Ignore bit_converts.
9658 while (Op.getOpcode() == ISD::BITCAST)
9659 Op = Op.getOperand(0);
9660 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9661 APInt SplatBits, SplatUndef;
9662 unsigned SplatBitSize;
9664 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9665 HasAnyUndefs, ElementBits) ||
9666 SplatBitSize > ElementBits)
9668 Cnt = SplatBits.getSExtValue();
9672 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9673 /// operand of a vector shift left operation. That value must be in the range:
9674 /// 0 <= Value < ElementBits for a left shift; or
9675 /// 0 <= Value <= ElementBits for a long left shift.
9676 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9677 assert(VT.isVector() && "vector shift count is not a vector type");
9678 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9679 if (! getVShiftImm(Op, ElementBits, Cnt))
9681 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9684 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9685 /// operand of a vector shift right operation. For a shift opcode, the value
9686 /// is positive, but for an intrinsic the value count must be negative. The
9687 /// absolute value must be in the range:
9688 /// 1 <= |Value| <= ElementBits for a right shift; or
9689 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9690 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9692 assert(VT.isVector() && "vector shift count is not a vector type");
9693 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9694 if (! getVShiftImm(Op, ElementBits, Cnt))
9698 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9701 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9702 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9703 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9706 // Don't do anything for most intrinsics.
9709 // Vector shifts: check for immediate versions and lower them.
9710 // Note: This is done during DAG combining instead of DAG legalizing because
9711 // the build_vectors for 64-bit vector element shift counts are generally
9712 // not legal, and it is hard to see their values after they get legalized to
9713 // loads from a constant pool.
9714 case Intrinsic::arm_neon_vshifts:
9715 case Intrinsic::arm_neon_vshiftu:
9716 case Intrinsic::arm_neon_vshiftls:
9717 case Intrinsic::arm_neon_vshiftlu:
9718 case Intrinsic::arm_neon_vshiftn:
9719 case Intrinsic::arm_neon_vrshifts:
9720 case Intrinsic::arm_neon_vrshiftu:
9721 case Intrinsic::arm_neon_vrshiftn:
9722 case Intrinsic::arm_neon_vqshifts:
9723 case Intrinsic::arm_neon_vqshiftu:
9724 case Intrinsic::arm_neon_vqshiftsu:
9725 case Intrinsic::arm_neon_vqshiftns:
9726 case Intrinsic::arm_neon_vqshiftnu:
9727 case Intrinsic::arm_neon_vqshiftnsu:
9728 case Intrinsic::arm_neon_vqrshiftns:
9729 case Intrinsic::arm_neon_vqrshiftnu:
9730 case Intrinsic::arm_neon_vqrshiftnsu: {
9731 EVT VT = N->getOperand(1).getValueType();
9733 unsigned VShiftOpc = 0;
9736 case Intrinsic::arm_neon_vshifts:
9737 case Intrinsic::arm_neon_vshiftu:
9738 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9739 VShiftOpc = ARMISD::VSHL;
9742 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9743 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9744 ARMISD::VSHRs : ARMISD::VSHRu);
9749 case Intrinsic::arm_neon_vshiftls:
9750 case Intrinsic::arm_neon_vshiftlu:
9751 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9753 llvm_unreachable("invalid shift count for vshll intrinsic");
9755 case Intrinsic::arm_neon_vrshifts:
9756 case Intrinsic::arm_neon_vrshiftu:
9757 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9761 case Intrinsic::arm_neon_vqshifts:
9762 case Intrinsic::arm_neon_vqshiftu:
9763 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9767 case Intrinsic::arm_neon_vqshiftsu:
9768 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9770 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9772 case Intrinsic::arm_neon_vshiftn:
9773 case Intrinsic::arm_neon_vrshiftn:
9774 case Intrinsic::arm_neon_vqshiftns:
9775 case Intrinsic::arm_neon_vqshiftnu:
9776 case Intrinsic::arm_neon_vqshiftnsu:
9777 case Intrinsic::arm_neon_vqrshiftns:
9778 case Intrinsic::arm_neon_vqrshiftnu:
9779 case Intrinsic::arm_neon_vqrshiftnsu:
9780 // Narrowing shifts require an immediate right shift.
9781 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9783 llvm_unreachable("invalid shift count for narrowing vector shift "
9787 llvm_unreachable("unhandled vector shift");
9791 case Intrinsic::arm_neon_vshifts:
9792 case Intrinsic::arm_neon_vshiftu:
9793 // Opcode already set above.
9795 case Intrinsic::arm_neon_vshiftls:
9796 case Intrinsic::arm_neon_vshiftlu:
9797 if (Cnt == VT.getVectorElementType().getSizeInBits())
9798 VShiftOpc = ARMISD::VSHLLi;
9800 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9801 ARMISD::VSHLLs : ARMISD::VSHLLu);
9803 case Intrinsic::arm_neon_vshiftn:
9804 VShiftOpc = ARMISD::VSHRN; break;
9805 case Intrinsic::arm_neon_vrshifts:
9806 VShiftOpc = ARMISD::VRSHRs; break;
9807 case Intrinsic::arm_neon_vrshiftu:
9808 VShiftOpc = ARMISD::VRSHRu; break;
9809 case Intrinsic::arm_neon_vrshiftn:
9810 VShiftOpc = ARMISD::VRSHRN; break;
9811 case Intrinsic::arm_neon_vqshifts:
9812 VShiftOpc = ARMISD::VQSHLs; break;
9813 case Intrinsic::arm_neon_vqshiftu:
9814 VShiftOpc = ARMISD::VQSHLu; break;
9815 case Intrinsic::arm_neon_vqshiftsu:
9816 VShiftOpc = ARMISD::VQSHLsu; break;
9817 case Intrinsic::arm_neon_vqshiftns:
9818 VShiftOpc = ARMISD::VQSHRNs; break;
9819 case Intrinsic::arm_neon_vqshiftnu:
9820 VShiftOpc = ARMISD::VQSHRNu; break;
9821 case Intrinsic::arm_neon_vqshiftnsu:
9822 VShiftOpc = ARMISD::VQSHRNsu; break;
9823 case Intrinsic::arm_neon_vqrshiftns:
9824 VShiftOpc = ARMISD::VQRSHRNs; break;
9825 case Intrinsic::arm_neon_vqrshiftnu:
9826 VShiftOpc = ARMISD::VQRSHRNu; break;
9827 case Intrinsic::arm_neon_vqrshiftnsu:
9828 VShiftOpc = ARMISD::VQRSHRNsu; break;
9831 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9832 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9835 case Intrinsic::arm_neon_vshiftins: {
9836 EVT VT = N->getOperand(1).getValueType();
9838 unsigned VShiftOpc = 0;
9840 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9841 VShiftOpc = ARMISD::VSLI;
9842 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9843 VShiftOpc = ARMISD::VSRI;
9845 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9848 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9849 N->getOperand(1), N->getOperand(2),
9850 DAG.getConstant(Cnt, MVT::i32));
9853 case Intrinsic::arm_neon_vqrshifts:
9854 case Intrinsic::arm_neon_vqrshiftu:
9855 // No immediate versions of these to check for.
9862 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9863 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9864 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9865 /// vector element shift counts are generally not legal, and it is hard to see
9866 /// their values after they get legalized to loads from a constant pool.
9867 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9868 const ARMSubtarget *ST) {
9869 EVT VT = N->getValueType(0);
9870 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9871 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9872 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9873 SDValue N1 = N->getOperand(1);
9874 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9875 SDValue N0 = N->getOperand(0);
9876 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9877 DAG.MaskedValueIsZero(N0.getOperand(0),
9878 APInt::getHighBitsSet(32, 16)))
9879 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9883 // Nothing to be done for scalar shifts.
9884 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9885 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9888 assert(ST->hasNEON() && "unexpected vector shift");
9891 switch (N->getOpcode()) {
9892 default: llvm_unreachable("unexpected shift opcode");
9895 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9896 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9897 DAG.getConstant(Cnt, MVT::i32));
9902 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9903 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9904 ARMISD::VSHRs : ARMISD::VSHRu);
9905 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9906 DAG.getConstant(Cnt, MVT::i32));
9912 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9913 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9914 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9915 const ARMSubtarget *ST) {
9916 SDValue N0 = N->getOperand(0);
9918 // Check for sign- and zero-extensions of vector extract operations of 8-
9919 // and 16-bit vector elements. NEON supports these directly. They are
9920 // handled during DAG combining because type legalization will promote them
9921 // to 32-bit types and it is messy to recognize the operations after that.
9922 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9923 SDValue Vec = N0.getOperand(0);
9924 SDValue Lane = N0.getOperand(1);
9925 EVT VT = N->getValueType(0);
9926 EVT EltVT = N0.getValueType();
9927 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9929 if (VT == MVT::i32 &&
9930 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9931 TLI.isTypeLegal(Vec.getValueType()) &&
9932 isa<ConstantSDNode>(Lane)) {
9935 switch (N->getOpcode()) {
9936 default: llvm_unreachable("unexpected opcode");
9937 case ISD::SIGN_EXTEND:
9938 Opc = ARMISD::VGETLANEs;
9940 case ISD::ZERO_EXTEND:
9941 case ISD::ANY_EXTEND:
9942 Opc = ARMISD::VGETLANEu;
9945 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9952 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9953 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9954 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9955 const ARMSubtarget *ST) {
9956 // If the target supports NEON, try to use vmax/vmin instructions for f32
9957 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9958 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9959 // a NaN; only do the transformation when it matches that behavior.
9961 // For now only do this when using NEON for FP operations; if using VFP, it
9962 // is not obvious that the benefit outweighs the cost of switching to the
9964 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9965 N->getValueType(0) != MVT::f32)
9968 SDValue CondLHS = N->getOperand(0);
9969 SDValue CondRHS = N->getOperand(1);
9970 SDValue LHS = N->getOperand(2);
9971 SDValue RHS = N->getOperand(3);
9972 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9974 unsigned Opcode = 0;
9976 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9977 IsReversed = false; // x CC y ? x : y
9978 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9979 IsReversed = true ; // x CC y ? y : x
9993 // If LHS is NaN, an ordered comparison will be false and the result will
9994 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9995 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9996 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9997 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9999 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10000 // will return -0, so vmin can only be used for unsafe math or if one of
10001 // the operands is known to be nonzero.
10002 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10003 !DAG.getTarget().Options.UnsafeFPMath &&
10004 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10006 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10015 // If LHS is NaN, an ordered comparison will be false and the result will
10016 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
10017 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10018 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10019 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10021 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10022 // will return +0, so vmax can only be used for unsafe math or if one of
10023 // the operands is known to be nonzero.
10024 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10025 !DAG.getTarget().Options.UnsafeFPMath &&
10026 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10028 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10034 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10037 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10039 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10040 SDValue Cmp = N->getOperand(4);
10041 if (Cmp.getOpcode() != ARMISD::CMPZ)
10042 // Only looking at EQ and NE cases.
10045 EVT VT = N->getValueType(0);
10047 SDValue LHS = Cmp.getOperand(0);
10048 SDValue RHS = Cmp.getOperand(1);
10049 SDValue FalseVal = N->getOperand(0);
10050 SDValue TrueVal = N->getOperand(1);
10051 SDValue ARMcc = N->getOperand(2);
10052 ARMCC::CondCodes CC =
10053 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10071 /// FIXME: Turn this into a target neutral optimization?
10073 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10074 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10075 N->getOperand(3), Cmp);
10076 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10078 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10079 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10080 N->getOperand(3), NewCmp);
10083 if (Res.getNode()) {
10084 APInt KnownZero, KnownOne;
10085 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10086 // Capture demanded bits information that would be otherwise lost.
10087 if (KnownZero == 0xfffffffe)
10088 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10089 DAG.getValueType(MVT::i1));
10090 else if (KnownZero == 0xffffff00)
10091 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10092 DAG.getValueType(MVT::i8));
10093 else if (KnownZero == 0xffff0000)
10094 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10095 DAG.getValueType(MVT::i16));
10101 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10102 DAGCombinerInfo &DCI) const {
10103 switch (N->getOpcode()) {
10105 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10106 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10107 case ISD::SUB: return PerformSUBCombine(N, DCI);
10108 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10109 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10110 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10111 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10112 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10113 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10114 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10115 case ISD::STORE: return PerformSTORECombine(N, DCI);
10116 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10117 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10118 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10119 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10120 case ISD::FP_TO_SINT:
10121 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10122 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10123 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10126 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10127 case ISD::SIGN_EXTEND:
10128 case ISD::ZERO_EXTEND:
10129 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10130 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10131 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10132 case ARMISD::VLD2DUP:
10133 case ARMISD::VLD3DUP:
10134 case ARMISD::VLD4DUP:
10135 return CombineBaseUpdate(N, DCI);
10136 case ARMISD::BUILD_VECTOR:
10137 return PerformARMBUILD_VECTORCombine(N, DCI);
10138 case ISD::INTRINSIC_VOID:
10139 case ISD::INTRINSIC_W_CHAIN:
10140 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10141 case Intrinsic::arm_neon_vld1:
10142 case Intrinsic::arm_neon_vld2:
10143 case Intrinsic::arm_neon_vld3:
10144 case Intrinsic::arm_neon_vld4:
10145 case Intrinsic::arm_neon_vld2lane:
10146 case Intrinsic::arm_neon_vld3lane:
10147 case Intrinsic::arm_neon_vld4lane:
10148 case Intrinsic::arm_neon_vst1:
10149 case Intrinsic::arm_neon_vst2:
10150 case Intrinsic::arm_neon_vst3:
10151 case Intrinsic::arm_neon_vst4:
10152 case Intrinsic::arm_neon_vst2lane:
10153 case Intrinsic::arm_neon_vst3lane:
10154 case Intrinsic::arm_neon_vst4lane:
10155 return CombineBaseUpdate(N, DCI);
10163 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10165 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10168 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10169 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10170 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10172 switch (VT.getSimpleVT().SimpleTy) {
10178 // Unaligned access can use (for example) LRDB, LRDH, LDR
10179 if (AllowsUnaligned) {
10181 *Fast = Subtarget->hasV7Ops();
10188 // For any little-endian targets with neon, we can support unaligned ld/st
10189 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10190 // A big-endian target may also explictly support unaligned accesses
10191 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10201 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10202 unsigned AlignCheck) {
10203 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10204 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10207 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10208 unsigned DstAlign, unsigned SrcAlign,
10209 bool IsMemset, bool ZeroMemset,
10211 MachineFunction &MF) const {
10212 const Function *F = MF.getFunction();
10214 // See if we can use NEON instructions for this...
10215 if ((!IsMemset || ZeroMemset) &&
10216 Subtarget->hasNEON() &&
10217 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10218 Attribute::NoImplicitFloat)) {
10221 (memOpAlign(SrcAlign, DstAlign, 16) ||
10222 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10224 } else if (Size >= 8 &&
10225 (memOpAlign(SrcAlign, DstAlign, 8) ||
10226 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10231 // Lowering to i32/i16 if the size permits.
10234 else if (Size >= 2)
10237 // Let the target-independent logic figure it out.
10241 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10242 if (Val.getOpcode() != ISD::LOAD)
10245 EVT VT1 = Val.getValueType();
10246 if (!VT1.isSimple() || !VT1.isInteger() ||
10247 !VT2.isSimple() || !VT2.isInteger())
10250 switch (VT1.getSimpleVT().SimpleTy) {
10255 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10262 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10263 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10266 if (!isTypeLegal(EVT::getEVT(Ty1)))
10269 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10271 // Assuming the caller doesn't have a zeroext or signext return parameter,
10272 // truncation all the way down to i1 is valid.
10277 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10281 unsigned Scale = 1;
10282 switch (VT.getSimpleVT().SimpleTy) {
10283 default: return false;
10298 if ((V & (Scale - 1)) != 0)
10301 return V == (V & ((1LL << 5) - 1));
10304 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10305 const ARMSubtarget *Subtarget) {
10306 bool isNeg = false;
10312 switch (VT.getSimpleVT().SimpleTy) {
10313 default: return false;
10318 // + imm12 or - imm8
10320 return V == (V & ((1LL << 8) - 1));
10321 return V == (V & ((1LL << 12) - 1));
10324 // Same as ARM mode. FIXME: NEON?
10325 if (!Subtarget->hasVFP2())
10330 return V == (V & ((1LL << 8) - 1));
10334 /// isLegalAddressImmediate - Return true if the integer value can be used
10335 /// as the offset of the target addressing mode for load / store of the
10337 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10338 const ARMSubtarget *Subtarget) {
10342 if (!VT.isSimple())
10345 if (Subtarget->isThumb1Only())
10346 return isLegalT1AddressImmediate(V, VT);
10347 else if (Subtarget->isThumb2())
10348 return isLegalT2AddressImmediate(V, VT, Subtarget);
10353 switch (VT.getSimpleVT().SimpleTy) {
10354 default: return false;
10359 return V == (V & ((1LL << 12) - 1));
10362 return V == (V & ((1LL << 8) - 1));
10365 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10370 return V == (V & ((1LL << 8) - 1));
10374 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10376 int Scale = AM.Scale;
10380 switch (VT.getSimpleVT().SimpleTy) {
10381 default: return false;
10389 Scale = Scale & ~1;
10390 return Scale == 2 || Scale == 4 || Scale == 8;
10393 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10397 // Note, we allow "void" uses (basically, uses that aren't loads or
10398 // stores), because arm allows folding a scale into many arithmetic
10399 // operations. This should be made more precise and revisited later.
10401 // Allow r << imm, but the imm has to be a multiple of two.
10402 if (Scale & 1) return false;
10403 return isPowerOf2_32(Scale);
10407 /// isLegalAddressingMode - Return true if the addressing mode represented
10408 /// by AM is legal for this target, for a load/store of the specified type.
10409 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10411 EVT VT = getValueType(Ty, true);
10412 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10415 // Can never fold addr of global into load/store.
10419 switch (AM.Scale) {
10420 case 0: // no scale reg, must be "r+i" or "r", or "i".
10423 if (Subtarget->isThumb1Only())
10427 // ARM doesn't support any R+R*scale+imm addr modes.
10431 if (!VT.isSimple())
10434 if (Subtarget->isThumb2())
10435 return isLegalT2ScaledAddressingMode(AM, VT);
10437 int Scale = AM.Scale;
10438 switch (VT.getSimpleVT().SimpleTy) {
10439 default: return false;
10443 if (Scale < 0) Scale = -Scale;
10447 return isPowerOf2_32(Scale & ~1);
10451 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10456 // Note, we allow "void" uses (basically, uses that aren't loads or
10457 // stores), because arm allows folding a scale into many arithmetic
10458 // operations. This should be made more precise and revisited later.
10460 // Allow r << imm, but the imm has to be a multiple of two.
10461 if (Scale & 1) return false;
10462 return isPowerOf2_32(Scale);
10468 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10469 /// icmp immediate, that is the target has icmp instructions which can compare
10470 /// a register against the immediate without having to materialize the
10471 /// immediate into a register.
10472 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10473 // Thumb2 and ARM modes can use cmn for negative immediates.
10474 if (!Subtarget->isThumb())
10475 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10476 if (Subtarget->isThumb2())
10477 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10478 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10479 return Imm >= 0 && Imm <= 255;
10482 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10483 /// *or sub* immediate, that is the target has add or sub instructions which can
10484 /// add a register with the immediate without having to materialize the
10485 /// immediate into a register.
10486 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10487 // Same encoding for add/sub, just flip the sign.
10488 int64_t AbsImm = llvm::abs64(Imm);
10489 if (!Subtarget->isThumb())
10490 return ARM_AM::getSOImmVal(AbsImm) != -1;
10491 if (Subtarget->isThumb2())
10492 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10493 // Thumb1 only has 8-bit unsigned immediate.
10494 return AbsImm >= 0 && AbsImm <= 255;
10497 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10498 bool isSEXTLoad, SDValue &Base,
10499 SDValue &Offset, bool &isInc,
10500 SelectionDAG &DAG) {
10501 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10504 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10505 // AddressingMode 3
10506 Base = Ptr->getOperand(0);
10507 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10508 int RHSC = (int)RHS->getZExtValue();
10509 if (RHSC < 0 && RHSC > -256) {
10510 assert(Ptr->getOpcode() == ISD::ADD);
10512 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10516 isInc = (Ptr->getOpcode() == ISD::ADD);
10517 Offset = Ptr->getOperand(1);
10519 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10520 // AddressingMode 2
10521 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10522 int RHSC = (int)RHS->getZExtValue();
10523 if (RHSC < 0 && RHSC > -0x1000) {
10524 assert(Ptr->getOpcode() == ISD::ADD);
10526 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10527 Base = Ptr->getOperand(0);
10532 if (Ptr->getOpcode() == ISD::ADD) {
10534 ARM_AM::ShiftOpc ShOpcVal=
10535 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10536 if (ShOpcVal != ARM_AM::no_shift) {
10537 Base = Ptr->getOperand(1);
10538 Offset = Ptr->getOperand(0);
10540 Base = Ptr->getOperand(0);
10541 Offset = Ptr->getOperand(1);
10546 isInc = (Ptr->getOpcode() == ISD::ADD);
10547 Base = Ptr->getOperand(0);
10548 Offset = Ptr->getOperand(1);
10552 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10556 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10557 bool isSEXTLoad, SDValue &Base,
10558 SDValue &Offset, bool &isInc,
10559 SelectionDAG &DAG) {
10560 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10563 Base = Ptr->getOperand(0);
10564 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10565 int RHSC = (int)RHS->getZExtValue();
10566 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10567 assert(Ptr->getOpcode() == ISD::ADD);
10569 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10571 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10572 isInc = Ptr->getOpcode() == ISD::ADD;
10573 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10581 /// getPreIndexedAddressParts - returns true by value, base pointer and
10582 /// offset pointer and addressing mode by reference if the node's address
10583 /// can be legally represented as pre-indexed load / store address.
10585 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10587 ISD::MemIndexedMode &AM,
10588 SelectionDAG &DAG) const {
10589 if (Subtarget->isThumb1Only())
10594 bool isSEXTLoad = false;
10595 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10596 Ptr = LD->getBasePtr();
10597 VT = LD->getMemoryVT();
10598 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10599 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10600 Ptr = ST->getBasePtr();
10601 VT = ST->getMemoryVT();
10606 bool isLegal = false;
10607 if (Subtarget->isThumb2())
10608 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10609 Offset, isInc, DAG);
10611 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10612 Offset, isInc, DAG);
10616 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10620 /// getPostIndexedAddressParts - returns true by value, base pointer and
10621 /// offset pointer and addressing mode by reference if this node can be
10622 /// combined with a load / store to form a post-indexed load / store.
10623 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10626 ISD::MemIndexedMode &AM,
10627 SelectionDAG &DAG) const {
10628 if (Subtarget->isThumb1Only())
10633 bool isSEXTLoad = false;
10634 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10635 VT = LD->getMemoryVT();
10636 Ptr = LD->getBasePtr();
10637 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10638 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10639 VT = ST->getMemoryVT();
10640 Ptr = ST->getBasePtr();
10645 bool isLegal = false;
10646 if (Subtarget->isThumb2())
10647 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10650 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10656 // Swap base ptr and offset to catch more post-index load / store when
10657 // it's legal. In Thumb2 mode, offset must be an immediate.
10658 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10659 !Subtarget->isThumb2())
10660 std::swap(Base, Offset);
10662 // Post-indexed load / store update the base pointer.
10667 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10671 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10674 const SelectionDAG &DAG,
10675 unsigned Depth) const {
10676 unsigned BitWidth = KnownOne.getBitWidth();
10677 KnownZero = KnownOne = APInt(BitWidth, 0);
10678 switch (Op.getOpcode()) {
10684 // These nodes' second result is a boolean
10685 if (Op.getResNo() == 0)
10687 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10689 case ARMISD::CMOV: {
10690 // Bits are known zero/one if known on the LHS and RHS.
10691 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10692 if (KnownZero == 0 && KnownOne == 0) return;
10694 APInt KnownZeroRHS, KnownOneRHS;
10695 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10696 KnownZero &= KnownZeroRHS;
10697 KnownOne &= KnownOneRHS;
10703 //===----------------------------------------------------------------------===//
10704 // ARM Inline Assembly Support
10705 //===----------------------------------------------------------------------===//
10707 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10708 // Looking for "rev" which is V6+.
10709 if (!Subtarget->hasV6Ops())
10712 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10713 std::string AsmStr = IA->getAsmString();
10714 SmallVector<StringRef, 4> AsmPieces;
10715 SplitString(AsmStr, AsmPieces, ";\n");
10717 switch (AsmPieces.size()) {
10718 default: return false;
10720 AsmStr = AsmPieces[0];
10722 SplitString(AsmStr, AsmPieces, " \t,");
10725 if (AsmPieces.size() == 3 &&
10726 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10727 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10728 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10729 if (Ty && Ty->getBitWidth() == 32)
10730 return IntrinsicLowering::LowerToByteSwap(CI);
10738 /// getConstraintType - Given a constraint letter, return the type of
10739 /// constraint it is for this target.
10740 ARMTargetLowering::ConstraintType
10741 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10742 if (Constraint.size() == 1) {
10743 switch (Constraint[0]) {
10745 case 'l': return C_RegisterClass;
10746 case 'w': return C_RegisterClass;
10747 case 'h': return C_RegisterClass;
10748 case 'x': return C_RegisterClass;
10749 case 't': return C_RegisterClass;
10750 case 'j': return C_Other; // Constant for movw.
10751 // An address with a single base register. Due to the way we
10752 // currently handle addresses it is the same as an 'r' memory constraint.
10753 case 'Q': return C_Memory;
10755 } else if (Constraint.size() == 2) {
10756 switch (Constraint[0]) {
10758 // All 'U+' constraints are addresses.
10759 case 'U': return C_Memory;
10762 return TargetLowering::getConstraintType(Constraint);
10765 /// Examine constraint type and operand type and determine a weight value.
10766 /// This object must already have been set up with the operand type
10767 /// and the current alternative constraint selected.
10768 TargetLowering::ConstraintWeight
10769 ARMTargetLowering::getSingleConstraintMatchWeight(
10770 AsmOperandInfo &info, const char *constraint) const {
10771 ConstraintWeight weight = CW_Invalid;
10772 Value *CallOperandVal = info.CallOperandVal;
10773 // If we don't have a value, we can't do a match,
10774 // but allow it at the lowest weight.
10775 if (CallOperandVal == NULL)
10777 Type *type = CallOperandVal->getType();
10778 // Look at the constraint type.
10779 switch (*constraint) {
10781 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10784 if (type->isIntegerTy()) {
10785 if (Subtarget->isThumb())
10786 weight = CW_SpecificReg;
10788 weight = CW_Register;
10792 if (type->isFloatingPointTy())
10793 weight = CW_Register;
10799 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10801 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10803 if (Constraint.size() == 1) {
10804 // GCC ARM Constraint Letters
10805 switch (Constraint[0]) {
10806 case 'l': // Low regs or general regs.
10807 if (Subtarget->isThumb())
10808 return RCPair(0U, &ARM::tGPRRegClass);
10809 return RCPair(0U, &ARM::GPRRegClass);
10810 case 'h': // High regs or no regs.
10811 if (Subtarget->isThumb())
10812 return RCPair(0U, &ARM::hGPRRegClass);
10815 return RCPair(0U, &ARM::GPRRegClass);
10817 if (VT == MVT::Other)
10819 if (VT == MVT::f32)
10820 return RCPair(0U, &ARM::SPRRegClass);
10821 if (VT.getSizeInBits() == 64)
10822 return RCPair(0U, &ARM::DPRRegClass);
10823 if (VT.getSizeInBits() == 128)
10824 return RCPair(0U, &ARM::QPRRegClass);
10827 if (VT == MVT::Other)
10829 if (VT == MVT::f32)
10830 return RCPair(0U, &ARM::SPR_8RegClass);
10831 if (VT.getSizeInBits() == 64)
10832 return RCPair(0U, &ARM::DPR_8RegClass);
10833 if (VT.getSizeInBits() == 128)
10834 return RCPair(0U, &ARM::QPR_8RegClass);
10837 if (VT == MVT::f32)
10838 return RCPair(0U, &ARM::SPRRegClass);
10842 if (StringRef("{cc}").equals_lower(Constraint))
10843 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10845 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10848 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10849 /// vector. If it is invalid, don't add anything to Ops.
10850 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10851 std::string &Constraint,
10852 std::vector<SDValue>&Ops,
10853 SelectionDAG &DAG) const {
10854 SDValue Result(0, 0);
10856 // Currently only support length 1 constraints.
10857 if (Constraint.length() != 1) return;
10859 char ConstraintLetter = Constraint[0];
10860 switch (ConstraintLetter) {
10863 case 'I': case 'J': case 'K': case 'L':
10864 case 'M': case 'N': case 'O':
10865 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10869 int64_t CVal64 = C->getSExtValue();
10870 int CVal = (int) CVal64;
10871 // None of these constraints allow values larger than 32 bits. Check
10872 // that the value fits in an int.
10873 if (CVal != CVal64)
10876 switch (ConstraintLetter) {
10878 // Constant suitable for movw, must be between 0 and
10880 if (Subtarget->hasV6T2Ops())
10881 if (CVal >= 0 && CVal <= 65535)
10885 if (Subtarget->isThumb1Only()) {
10886 // This must be a constant between 0 and 255, for ADD
10888 if (CVal >= 0 && CVal <= 255)
10890 } else if (Subtarget->isThumb2()) {
10891 // A constant that can be used as an immediate value in a
10892 // data-processing instruction.
10893 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10896 // A constant that can be used as an immediate value in a
10897 // data-processing instruction.
10898 if (ARM_AM::getSOImmVal(CVal) != -1)
10904 if (Subtarget->isThumb()) { // FIXME thumb2
10905 // This must be a constant between -255 and -1, for negated ADD
10906 // immediates. This can be used in GCC with an "n" modifier that
10907 // prints the negated value, for use with SUB instructions. It is
10908 // not useful otherwise but is implemented for compatibility.
10909 if (CVal >= -255 && CVal <= -1)
10912 // This must be a constant between -4095 and 4095. It is not clear
10913 // what this constraint is intended for. Implemented for
10914 // compatibility with GCC.
10915 if (CVal >= -4095 && CVal <= 4095)
10921 if (Subtarget->isThumb1Only()) {
10922 // A 32-bit value where only one byte has a nonzero value. Exclude
10923 // zero to match GCC. This constraint is used by GCC internally for
10924 // constants that can be loaded with a move/shift combination.
10925 // It is not useful otherwise but is implemented for compatibility.
10926 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10928 } else if (Subtarget->isThumb2()) {
10929 // A constant whose bitwise inverse can be used as an immediate
10930 // value in a data-processing instruction. This can be used in GCC
10931 // with a "B" modifier that prints the inverted value, for use with
10932 // BIC and MVN instructions. It is not useful otherwise but is
10933 // implemented for compatibility.
10934 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10937 // A constant whose bitwise inverse can be used as an immediate
10938 // value in a data-processing instruction. This can be used in GCC
10939 // with a "B" modifier that prints the inverted value, for use with
10940 // BIC and MVN instructions. It is not useful otherwise but is
10941 // implemented for compatibility.
10942 if (ARM_AM::getSOImmVal(~CVal) != -1)
10948 if (Subtarget->isThumb1Only()) {
10949 // This must be a constant between -7 and 7,
10950 // for 3-operand ADD/SUB immediate instructions.
10951 if (CVal >= -7 && CVal < 7)
10953 } else if (Subtarget->isThumb2()) {
10954 // A constant whose negation can be used as an immediate value in a
10955 // data-processing instruction. This can be used in GCC with an "n"
10956 // modifier that prints the negated value, for use with SUB
10957 // instructions. It is not useful otherwise but is implemented for
10959 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10962 // A constant whose negation can be used as an immediate value in a
10963 // data-processing instruction. This can be used in GCC with an "n"
10964 // modifier that prints the negated value, for use with SUB
10965 // instructions. It is not useful otherwise but is implemented for
10967 if (ARM_AM::getSOImmVal(-CVal) != -1)
10973 if (Subtarget->isThumb()) { // FIXME thumb2
10974 // This must be a multiple of 4 between 0 and 1020, for
10975 // ADD sp + immediate.
10976 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10979 // A power of two or a constant between 0 and 32. This is used in
10980 // GCC for the shift amount on shifted register operands, but it is
10981 // useful in general for any shift amounts.
10982 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10988 if (Subtarget->isThumb()) { // FIXME thumb2
10989 // This must be a constant between 0 and 31, for shift amounts.
10990 if (CVal >= 0 && CVal <= 31)
10996 if (Subtarget->isThumb()) { // FIXME thumb2
10997 // This must be a multiple of 4 between -508 and 508, for
10998 // ADD/SUB sp = sp + immediate.
10999 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11004 Result = DAG.getTargetConstant(CVal, Op.getValueType());
11008 if (Result.getNode()) {
11009 Ops.push_back(Result);
11012 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11015 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11016 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11017 unsigned Opcode = Op->getOpcode();
11018 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11019 "Invalid opcode for Div/Rem lowering");
11020 bool isSigned = (Opcode == ISD::SDIVREM);
11021 EVT VT = Op->getValueType(0);
11022 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11025 switch (VT.getSimpleVT().SimpleTy) {
11026 default: llvm_unreachable("Unexpected request for libcall!");
11027 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11028 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11029 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11030 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11033 SDValue InChain = DAG.getEntryNode();
11035 TargetLowering::ArgListTy Args;
11036 TargetLowering::ArgListEntry Entry;
11037 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11038 EVT ArgVT = Op->getOperand(i).getValueType();
11039 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11040 Entry.Node = Op->getOperand(i);
11042 Entry.isSExt = isSigned;
11043 Entry.isZExt = !isSigned;
11044 Args.push_back(Entry);
11047 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11050 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11054 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11055 0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11056 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11057 Callee, Args, DAG, dl);
11058 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11060 return CallInfo.first;
11064 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11065 // The ARM target isn't yet aware of offsets.
11069 bool ARM::isBitFieldInvertedMask(unsigned v) {
11070 if (v == 0xffffffff)
11073 // there can be 1's on either or both "outsides", all the "inside"
11074 // bits must be 0's
11075 unsigned TO = CountTrailingOnes_32(v);
11076 unsigned LO = CountLeadingOnes_32(v);
11077 v = (v >> TO) << TO;
11078 v = (v << LO) >> LO;
11082 /// isFPImmLegal - Returns true if the target can instruction select the
11083 /// specified FP immediate natively. If false, the legalizer will
11084 /// materialize the FP immediate as a load from a constant pool.
11085 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11086 if (!Subtarget->hasVFP3())
11088 if (VT == MVT::f32)
11089 return ARM_AM::getFP32Imm(Imm) != -1;
11090 if (VT == MVT::f64)
11091 return ARM_AM::getFP64Imm(Imm) != -1;
11095 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11096 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11097 /// specified in the intrinsic calls.
11098 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11100 unsigned Intrinsic) const {
11101 switch (Intrinsic) {
11102 case Intrinsic::arm_neon_vld1:
11103 case Intrinsic::arm_neon_vld2:
11104 case Intrinsic::arm_neon_vld3:
11105 case Intrinsic::arm_neon_vld4:
11106 case Intrinsic::arm_neon_vld2lane:
11107 case Intrinsic::arm_neon_vld3lane:
11108 case Intrinsic::arm_neon_vld4lane: {
11109 Info.opc = ISD::INTRINSIC_W_CHAIN;
11110 // Conservatively set memVT to the entire set of vectors loaded.
11111 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11112 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11113 Info.ptrVal = I.getArgOperand(0);
11115 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11116 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11117 Info.vol = false; // volatile loads with NEON intrinsics not supported
11118 Info.readMem = true;
11119 Info.writeMem = false;
11122 case Intrinsic::arm_neon_vst1:
11123 case Intrinsic::arm_neon_vst2:
11124 case Intrinsic::arm_neon_vst3:
11125 case Intrinsic::arm_neon_vst4:
11126 case Intrinsic::arm_neon_vst2lane:
11127 case Intrinsic::arm_neon_vst3lane:
11128 case Intrinsic::arm_neon_vst4lane: {
11129 Info.opc = ISD::INTRINSIC_VOID;
11130 // Conservatively set memVT to the entire set of vectors stored.
11131 unsigned NumElts = 0;
11132 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11133 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11134 if (!ArgTy->isVectorTy())
11136 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11138 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11139 Info.ptrVal = I.getArgOperand(0);
11141 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11142 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11143 Info.vol = false; // volatile stores with NEON intrinsics not supported
11144 Info.readMem = false;
11145 Info.writeMem = true;
11148 case Intrinsic::arm_ldrex: {
11149 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11150 Info.opc = ISD::INTRINSIC_W_CHAIN;
11151 Info.memVT = MVT::getVT(PtrTy->getElementType());
11152 Info.ptrVal = I.getArgOperand(0);
11154 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11156 Info.readMem = true;
11157 Info.writeMem = false;
11160 case Intrinsic::arm_strex: {
11161 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11162 Info.opc = ISD::INTRINSIC_W_CHAIN;
11163 Info.memVT = MVT::getVT(PtrTy->getElementType());
11164 Info.ptrVal = I.getArgOperand(1);
11166 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11168 Info.readMem = false;
11169 Info.writeMem = true;
11172 case Intrinsic::arm_strexd: {
11173 Info.opc = ISD::INTRINSIC_W_CHAIN;
11174 Info.memVT = MVT::i64;
11175 Info.ptrVal = I.getArgOperand(2);
11179 Info.readMem = false;
11180 Info.writeMem = true;
11183 case Intrinsic::arm_ldrexd: {
11184 Info.opc = ISD::INTRINSIC_W_CHAIN;
11185 Info.memVT = MVT::i64;
11186 Info.ptrVal = I.getArgOperand(0);
11190 Info.readMem = true;
11191 Info.writeMem = false;