1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
53 #define DEBUG_TYPE "arm-isel"
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61 cl::desc("Generate calls via indirect call instructions"),
65 ARMInterworking("arm-interworking", cl::Hidden,
66 cl::desc("Enable / disable ARM interworking (for debugging only)"),
70 class ARMCCState : public CCState {
72 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
74 LLVMContext &C, ParmContext PC)
75 : CCState(CC, isVarArg, MF, TM, locs, C) {
76 assert(((PC == Call) || (PC == Prologue)) &&
77 "ARMCCState users must specify whether their context is call"
78 "or prologue generation.");
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86 ARM::R0, ARM::R1, ARM::R2, ARM::R3
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90 MVT PromotedBitwiseVT) {
91 if (VT != PromotedLdStVT) {
92 setOperationAction(ISD::LOAD, VT, Promote);
93 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
95 setOperationAction(ISD::STORE, VT, Promote);
96 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
99 MVT ElemTy = VT.getVectorElementType();
100 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101 setOperationAction(ISD::SETCC, VT, Custom);
102 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104 if (ElemTy == MVT::i32) {
105 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
110 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
115 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
116 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
117 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
118 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119 setOperationAction(ISD::SELECT, VT, Expand);
120 setOperationAction(ISD::SELECT_CC, VT, Expand);
121 setOperationAction(ISD::VSELECT, VT, Expand);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123 if (VT.isInteger()) {
124 setOperationAction(ISD::SHL, VT, Custom);
125 setOperationAction(ISD::SRA, VT, Custom);
126 setOperationAction(ISD::SRL, VT, Custom);
129 // Promote all bit-wise operations.
130 if (VT.isInteger() && VT != PromotedBitwiseVT) {
131 setOperationAction(ISD::AND, VT, Promote);
132 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133 setOperationAction(ISD::OR, VT, Promote);
134 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
135 setOperationAction(ISD::XOR, VT, Promote);
136 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
139 // Neon does not support vector divide/remainder operations.
140 setOperationAction(ISD::SDIV, VT, Expand);
141 setOperationAction(ISD::UDIV, VT, Expand);
142 setOperationAction(ISD::FDIV, VT, Expand);
143 setOperationAction(ISD::SREM, VT, Expand);
144 setOperationAction(ISD::UREM, VT, Expand);
145 setOperationAction(ISD::FREM, VT, Expand);
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149 addRegisterClass(VT, &ARM::DPRRegClass);
150 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154 addRegisterClass(VT, &ARM::DPairRegClass);
155 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
158 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
159 if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
160 return new TargetLoweringObjectFileMachO();
162 return new ARMElfTargetObjectFile();
165 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
166 : TargetLowering(TM, createTLOF(TM)) {
167 Subtarget = &TM.getSubtarget<ARMSubtarget>();
168 RegInfo = TM.getRegisterInfo();
169 Itins = TM.getInstrItineraryData();
171 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173 if (Subtarget->isTargetMachO()) {
174 // Uses VFP for Thumb libfuncs if available.
175 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
176 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
177 // Single-precision floating-point arithmetic.
178 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
179 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
180 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
181 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
183 // Double-precision floating-point arithmetic.
184 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
185 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
186 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
187 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
189 // Single-precision comparisons.
190 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
191 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
192 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
193 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
194 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
195 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
196 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
197 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
199 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
200 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
208 // Double-precision comparisons.
209 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
210 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
211 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
212 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
213 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
214 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
215 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
216 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
218 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
219 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
227 // Floating-point to integer conversions.
228 // i64 conversions are done via library routines even when generating VFP
229 // instructions, so use the same ones.
230 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
231 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
232 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
233 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
235 // Conversions between floating types.
236 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
237 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
239 // Integer to floating-point conversions.
240 // i64 conversions are done via library routines even when generating VFP
241 // instructions, so use the same ones.
242 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
243 // e.g., __floatunsidf vs. __floatunssidfvfp.
244 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
245 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
246 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
247 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251 // These libcalls are not available in 32-bit.
252 setLibcallName(RTLIB::SHL_I128, nullptr);
253 setLibcallName(RTLIB::SRL_I128, nullptr);
254 setLibcallName(RTLIB::SRA_I128, nullptr);
256 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
257 !Subtarget->isTargetWindows()) {
258 // Double-precision floating-point arithmetic helper functions
259 // RTABI chapter 4.1.2, Table 2
260 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
261 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
262 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
263 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
264 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
265 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
266 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
267 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
269 // Double-precision floating-point comparison helper functions
270 // RTABI chapter 4.1.2, Table 3
271 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
272 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
273 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
274 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
275 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
276 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
277 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
278 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
279 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
280 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
281 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
282 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
283 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
284 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
285 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
286 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
287 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
288 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
289 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
290 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
296 // Single-precision floating-point arithmetic helper functions
297 // RTABI chapter 4.1.2, Table 4
298 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
299 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
300 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
301 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
302 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
303 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
304 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
305 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
307 // Single-precision floating-point comparison helper functions
308 // RTABI chapter 4.1.2, Table 5
309 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
310 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
311 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
312 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
313 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
314 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
315 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
316 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
317 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
318 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
319 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
320 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
321 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
322 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
323 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
324 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
325 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
326 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
327 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
328 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
334 // Floating-point to integer conversions.
335 // RTABI chapter 4.1.2, Table 6
336 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
337 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
338 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
339 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
340 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
341 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
342 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
343 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
344 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
345 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
346 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
347 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
353 // Conversions between floating types.
354 // RTABI chapter 4.1.2, Table 7
355 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
356 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
357 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
358 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
360 // Integer to floating-point conversions.
361 // RTABI chapter 4.1.2, Table 8
362 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
363 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
364 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
365 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
366 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
367 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
368 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
369 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
370 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
371 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
372 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
373 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379 // Long long helper functions
380 // RTABI chapter 4.2, Table 9
381 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
382 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
383 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
384 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
385 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
386 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
387 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
388 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
392 // Integer division functions
393 // RTABI chapter 4.3.1
394 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
395 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
396 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
397 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
398 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
399 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
400 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
401 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
402 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
403 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
404 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
405 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412 // RTABI chapter 4.3.4
413 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
414 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
415 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
416 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
417 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
418 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421 if (Subtarget->isTargetWindows()) {
422 static const struct {
423 const RTLIB::Libcall Op;
424 const char * const Name;
425 const CallingConv::ID CC;
427 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
428 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
429 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
430 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
431 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
432 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
433 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
434 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
437 for (const auto &LC : LibraryCalls) {
438 setLibcallName(LC.Op, LC.Name);
439 setLibcallCallingConv(LC.Op, LC.CC);
443 // Use divmod compiler-rt calls for iOS 5.0 and later.
444 if (Subtarget->getTargetTriple().isiOS() &&
445 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
446 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
447 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
450 if (Subtarget->isThumb1Only())
451 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
453 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
454 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
455 !Subtarget->isThumb1Only()) {
456 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
457 if (!Subtarget->isFPOnlySP())
458 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
460 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
463 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
464 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
465 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
466 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
467 setTruncStoreAction((MVT::SimpleValueType)VT,
468 (MVT::SimpleValueType)InnerVT, Expand);
469 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
470 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
471 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
473 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
474 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
475 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
476 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
479 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
480 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
482 if (Subtarget->hasNEON()) {
483 addDRTypeForNEON(MVT::v2f32);
484 addDRTypeForNEON(MVT::v8i8);
485 addDRTypeForNEON(MVT::v4i16);
486 addDRTypeForNEON(MVT::v2i32);
487 addDRTypeForNEON(MVT::v1i64);
489 addQRTypeForNEON(MVT::v4f32);
490 addQRTypeForNEON(MVT::v2f64);
491 addQRTypeForNEON(MVT::v16i8);
492 addQRTypeForNEON(MVT::v8i16);
493 addQRTypeForNEON(MVT::v4i32);
494 addQRTypeForNEON(MVT::v2i64);
496 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
497 // neither Neon nor VFP support any arithmetic operations on it.
498 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
499 // supported for v4f32.
500 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
501 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
502 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
503 // FIXME: Code duplication: FDIV and FREM are expanded always, see
504 // ARMTargetLowering::addTypeForNEON method for details.
505 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
506 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
507 // FIXME: Create unittest.
508 // In another words, find a way when "copysign" appears in DAG with vector
510 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
511 // FIXME: Code duplication: SETCC has custom operation action, see
512 // ARMTargetLowering::addTypeForNEON method for details.
513 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
514 // FIXME: Create unittest for FNEG and for FABS.
515 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
516 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
517 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
518 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
519 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
520 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
521 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
522 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
523 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
524 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
525 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
526 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
527 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
528 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
529 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
530 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
531 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
532 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
533 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
535 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
536 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
537 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
538 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
539 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
540 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
541 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
542 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
543 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
544 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
545 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
546 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
547 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
548 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
549 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
551 // Mark v2f32 intrinsics.
552 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
553 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
554 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
555 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
556 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
557 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
558 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
559 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
560 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
561 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
562 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
563 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
564 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
565 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
566 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
568 // Neon does not support some operations on v1i64 and v2i64 types.
569 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
570 // Custom handling for some quad-vector types to detect VMULL.
571 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
572 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
573 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
574 // Custom handling for some vector types to avoid expensive expansions
575 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
576 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
577 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
578 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
579 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
580 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
581 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
582 // a destination type that is wider than the source, and nor does
583 // it have a FP_TO_[SU]INT instruction with a narrower destination than
585 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
586 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
587 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
588 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
590 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
591 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
593 // NEON does not have single instruction CTPOP for vectors with element
594 // types wider than 8-bits. However, custom lowering can leverage the
595 // v8i8/v16i8 vcnt instruction.
596 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
597 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
598 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
599 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
601 // NEON only has FMA instructions as of VFP4.
602 if (!Subtarget->hasVFP4()) {
603 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
604 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
607 setTargetDAGCombine(ISD::INTRINSIC_VOID);
608 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
609 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
610 setTargetDAGCombine(ISD::SHL);
611 setTargetDAGCombine(ISD::SRL);
612 setTargetDAGCombine(ISD::SRA);
613 setTargetDAGCombine(ISD::SIGN_EXTEND);
614 setTargetDAGCombine(ISD::ZERO_EXTEND);
615 setTargetDAGCombine(ISD::ANY_EXTEND);
616 setTargetDAGCombine(ISD::SELECT_CC);
617 setTargetDAGCombine(ISD::BUILD_VECTOR);
618 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
619 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
620 setTargetDAGCombine(ISD::STORE);
621 setTargetDAGCombine(ISD::FP_TO_SINT);
622 setTargetDAGCombine(ISD::FP_TO_UINT);
623 setTargetDAGCombine(ISD::FDIV);
625 // It is legal to extload from v4i8 to v4i16 or v4i32.
626 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
627 MVT::v4i16, MVT::v2i16,
629 for (unsigned i = 0; i < 6; ++i) {
630 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
631 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
632 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
636 // ARM and Thumb2 support UMLAL/SMLAL.
637 if (!Subtarget->isThumb1Only())
638 setTargetDAGCombine(ISD::ADDC);
641 computeRegisterProperties();
643 // ARM does not have f32 extending load.
644 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
646 // ARM does not have i1 sign extending load.
647 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
649 // ARM supports all 4 flavors of integer indexed load / store.
650 if (!Subtarget->isThumb1Only()) {
651 for (unsigned im = (unsigned)ISD::PRE_INC;
652 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
653 setIndexedLoadAction(im, MVT::i1, Legal);
654 setIndexedLoadAction(im, MVT::i8, Legal);
655 setIndexedLoadAction(im, MVT::i16, Legal);
656 setIndexedLoadAction(im, MVT::i32, Legal);
657 setIndexedStoreAction(im, MVT::i1, Legal);
658 setIndexedStoreAction(im, MVT::i8, Legal);
659 setIndexedStoreAction(im, MVT::i16, Legal);
660 setIndexedStoreAction(im, MVT::i32, Legal);
664 setOperationAction(ISD::SADDO, MVT::i32, Custom);
665 setOperationAction(ISD::UADDO, MVT::i32, Custom);
666 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
667 setOperationAction(ISD::USUBO, MVT::i32, Custom);
669 // i64 operation support.
670 setOperationAction(ISD::MUL, MVT::i64, Expand);
671 setOperationAction(ISD::MULHU, MVT::i32, Expand);
672 if (Subtarget->isThumb1Only()) {
673 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
674 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
676 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
677 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
678 setOperationAction(ISD::MULHS, MVT::i32, Expand);
680 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
681 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
682 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
683 setOperationAction(ISD::SRL, MVT::i64, Custom);
684 setOperationAction(ISD::SRA, MVT::i64, Custom);
686 if (!Subtarget->isThumb1Only()) {
687 // FIXME: We should do this for Thumb1 as well.
688 setOperationAction(ISD::ADDC, MVT::i32, Custom);
689 setOperationAction(ISD::ADDE, MVT::i32, Custom);
690 setOperationAction(ISD::SUBC, MVT::i32, Custom);
691 setOperationAction(ISD::SUBE, MVT::i32, Custom);
694 // ARM does not have ROTL.
695 setOperationAction(ISD::ROTL, MVT::i32, Expand);
696 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
697 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
698 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
699 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
701 // These just redirect to CTTZ and CTLZ on ARM.
702 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
703 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
705 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
707 // Only ARMv6 has BSWAP.
708 if (!Subtarget->hasV6Ops())
709 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
711 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
712 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
713 // These are expanded into libcalls if the cpu doesn't have HW divider.
714 setOperationAction(ISD::SDIV, MVT::i32, Expand);
715 setOperationAction(ISD::UDIV, MVT::i32, Expand);
718 // FIXME: Also set divmod for SREM on EABI
719 setOperationAction(ISD::SREM, MVT::i32, Expand);
720 setOperationAction(ISD::UREM, MVT::i32, Expand);
721 // Register based DivRem for AEABI (RTABI 4.2)
722 if (Subtarget->isTargetAEABI()) {
723 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
724 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
725 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
726 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
727 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
728 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
729 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
730 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
732 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
733 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
734 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
735 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
736 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
737 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
738 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
739 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
741 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
742 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
744 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
745 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
748 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
749 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
750 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
751 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
752 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
754 setOperationAction(ISD::TRAP, MVT::Other, Legal);
756 // Use the default implementation.
757 setOperationAction(ISD::VASTART, MVT::Other, Custom);
758 setOperationAction(ISD::VAARG, MVT::Other, Expand);
759 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
760 setOperationAction(ISD::VAEND, MVT::Other, Expand);
761 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
762 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
764 if (!Subtarget->isTargetMachO()) {
765 // Non-MachO platforms may return values in these registers via the
766 // personality function.
767 setExceptionPointerRegister(ARM::R0);
768 setExceptionSelectorRegister(ARM::R1);
771 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
772 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
773 // the default expansion.
774 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
775 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
776 // to ldrex/strex loops already.
777 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
779 // On v8, we have particularly efficient implementations of atomic fences
780 // if they can be combined with nearby atomic loads and stores.
781 if (!Subtarget->hasV8Ops()) {
782 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
783 setInsertFencesForAtomic(true);
786 // If there's anything we can use as a barrier, go through custom lowering
788 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
789 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
791 // Set them all for expansion, which will force libcalls.
792 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
793 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
794 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
795 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
796 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
797 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
798 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
799 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
800 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
801 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
802 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
803 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
804 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
805 // Unordered/Monotonic case.
806 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
807 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
810 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
812 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
813 if (!Subtarget->hasV6Ops()) {
814 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
815 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
817 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
819 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
820 !Subtarget->isThumb1Only()) {
821 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
822 // iff target supports vfp2.
823 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
824 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
827 // We want to custom lower some of our intrinsics.
828 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
829 if (Subtarget->isTargetDarwin()) {
830 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
831 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
832 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
835 setOperationAction(ISD::SETCC, MVT::i32, Expand);
836 setOperationAction(ISD::SETCC, MVT::f32, Expand);
837 setOperationAction(ISD::SETCC, MVT::f64, Expand);
838 setOperationAction(ISD::SELECT, MVT::i32, Custom);
839 setOperationAction(ISD::SELECT, MVT::f32, Custom);
840 setOperationAction(ISD::SELECT, MVT::f64, Custom);
841 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
842 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
843 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
845 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
846 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
847 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
848 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
849 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
851 // We don't support sin/cos/fmod/copysign/pow
852 setOperationAction(ISD::FSIN, MVT::f64, Expand);
853 setOperationAction(ISD::FSIN, MVT::f32, Expand);
854 setOperationAction(ISD::FCOS, MVT::f32, Expand);
855 setOperationAction(ISD::FCOS, MVT::f64, Expand);
856 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
857 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
858 setOperationAction(ISD::FREM, MVT::f64, Expand);
859 setOperationAction(ISD::FREM, MVT::f32, Expand);
860 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
861 !Subtarget->isThumb1Only()) {
862 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
863 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
865 setOperationAction(ISD::FPOW, MVT::f64, Expand);
866 setOperationAction(ISD::FPOW, MVT::f32, Expand);
868 if (!Subtarget->hasVFP4()) {
869 setOperationAction(ISD::FMA, MVT::f64, Expand);
870 setOperationAction(ISD::FMA, MVT::f32, Expand);
873 // Various VFP goodness
874 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
875 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
876 if (Subtarget->hasVFP2()) {
877 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
878 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
879 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
880 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
882 // Special handling for half-precision FP.
883 if (!Subtarget->hasFP16()) {
884 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
885 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
889 // Combine sin / cos into one node or libcall if possible.
890 if (Subtarget->hasSinCos()) {
891 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
892 setLibcallName(RTLIB::SINCOS_F64, "sincos");
893 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
894 // For iOS, we don't want to the normal expansion of a libcall to
895 // sincos. We want to issue a libcall to __sincos_stret.
896 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
897 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
901 // We have target-specific dag combine patterns for the following nodes:
902 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
903 setTargetDAGCombine(ISD::ADD);
904 setTargetDAGCombine(ISD::SUB);
905 setTargetDAGCombine(ISD::MUL);
906 setTargetDAGCombine(ISD::AND);
907 setTargetDAGCombine(ISD::OR);
908 setTargetDAGCombine(ISD::XOR);
910 if (Subtarget->hasV6Ops())
911 setTargetDAGCombine(ISD::SRL);
913 setStackPointerRegisterToSaveRestore(ARM::SP);
915 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
916 !Subtarget->hasVFP2())
917 setSchedulingPreference(Sched::RegPressure);
919 setSchedulingPreference(Sched::Hybrid);
921 //// temporary - rewrite interface to use type
922 MaxStoresPerMemset = 8;
923 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
924 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
925 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
926 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
927 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
929 // On ARM arguments smaller than 4 bytes are extended, so all arguments
930 // are at least 4 bytes aligned.
931 setMinStackArgumentAlignment(4);
933 // Prefer likely predicted branches to selects on out-of-order cores.
934 PredictableSelectIsExpensive = Subtarget->isLikeA9();
936 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
939 // FIXME: It might make sense to define the representative register class as the
940 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
941 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
942 // SPR's representative would be DPR_VFP2. This should work well if register
943 // pressure tracking were modified such that a register use would increment the
944 // pressure of the register class's representative and all of it's super
945 // classes' representatives transitively. We have not implemented this because
946 // of the difficulty prior to coalescing of modeling operand register classes
947 // due to the common occurrence of cross class copies and subregister insertions
949 std::pair<const TargetRegisterClass*, uint8_t>
950 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
951 const TargetRegisterClass *RRC = nullptr;
953 switch (VT.SimpleTy) {
955 return TargetLowering::findRepresentativeClass(VT);
956 // Use DPR as representative register class for all floating point
957 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
958 // the cost is 1 for both f32 and f64.
959 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
960 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
961 RRC = &ARM::DPRRegClass;
962 // When NEON is used for SP, only half of the register file is available
963 // because operations that define both SP and DP results will be constrained
964 // to the VFP2 class (D0-D15). We currently model this constraint prior to
965 // coalescing by double-counting the SP regs. See the FIXME above.
966 if (Subtarget->useNEONForSinglePrecisionFP())
969 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
970 case MVT::v4f32: case MVT::v2f64:
971 RRC = &ARM::DPRRegClass;
975 RRC = &ARM::DPRRegClass;
979 RRC = &ARM::DPRRegClass;
983 return std::make_pair(RRC, Cost);
986 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
988 default: return nullptr;
989 case ARMISD::Wrapper: return "ARMISD::Wrapper";
990 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
991 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
992 case ARMISD::CALL: return "ARMISD::CALL";
993 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
994 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
995 case ARMISD::tCALL: return "ARMISD::tCALL";
996 case ARMISD::BRCOND: return "ARMISD::BRCOND";
997 case ARMISD::BR_JT: return "ARMISD::BR_JT";
998 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
999 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1000 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1001 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1002 case ARMISD::CMP: return "ARMISD::CMP";
1003 case ARMISD::CMN: return "ARMISD::CMN";
1004 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1005 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1006 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1007 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1008 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1010 case ARMISD::CMOV: return "ARMISD::CMOV";
1012 case ARMISD::RBIT: return "ARMISD::RBIT";
1014 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1015 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1016 case ARMISD::SITOF: return "ARMISD::SITOF";
1017 case ARMISD::UITOF: return "ARMISD::UITOF";
1019 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1020 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1021 case ARMISD::RRX: return "ARMISD::RRX";
1023 case ARMISD::ADDC: return "ARMISD::ADDC";
1024 case ARMISD::ADDE: return "ARMISD::ADDE";
1025 case ARMISD::SUBC: return "ARMISD::SUBC";
1026 case ARMISD::SUBE: return "ARMISD::SUBE";
1028 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1029 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1031 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1032 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1034 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1036 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1038 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1040 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1042 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1044 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1045 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1046 case ARMISD::VCGE: return "ARMISD::VCGE";
1047 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1048 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1049 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1050 case ARMISD::VCGT: return "ARMISD::VCGT";
1051 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1052 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1053 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1054 case ARMISD::VTST: return "ARMISD::VTST";
1056 case ARMISD::VSHL: return "ARMISD::VSHL";
1057 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1058 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1059 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1060 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1061 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1062 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1063 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1064 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1065 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1066 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1067 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1068 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1069 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1070 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1071 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1072 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1073 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1074 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1075 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1076 case ARMISD::VDUP: return "ARMISD::VDUP";
1077 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1078 case ARMISD::VEXT: return "ARMISD::VEXT";
1079 case ARMISD::VREV64: return "ARMISD::VREV64";
1080 case ARMISD::VREV32: return "ARMISD::VREV32";
1081 case ARMISD::VREV16: return "ARMISD::VREV16";
1082 case ARMISD::VZIP: return "ARMISD::VZIP";
1083 case ARMISD::VUZP: return "ARMISD::VUZP";
1084 case ARMISD::VTRN: return "ARMISD::VTRN";
1085 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1086 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1087 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1088 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1089 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1090 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1091 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1092 case ARMISD::FMAX: return "ARMISD::FMAX";
1093 case ARMISD::FMIN: return "ARMISD::FMIN";
1094 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1095 case ARMISD::VMINNM: return "ARMISD::VMIN";
1096 case ARMISD::BFI: return "ARMISD::BFI";
1097 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1098 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1099 case ARMISD::VBSL: return "ARMISD::VBSL";
1100 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1101 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1102 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1103 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1104 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1105 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1106 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1107 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1108 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1109 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1110 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1111 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1112 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1113 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1114 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1115 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1116 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1117 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1118 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1119 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1123 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1124 if (!VT.isVector()) return getPointerTy();
1125 return VT.changeVectorElementTypeToInteger();
1128 /// getRegClassFor - Return the register class that should be used for the
1129 /// specified value type.
1130 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1131 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1132 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1133 // load / store 4 to 8 consecutive D registers.
1134 if (Subtarget->hasNEON()) {
1135 if (VT == MVT::v4i64)
1136 return &ARM::QQPRRegClass;
1137 if (VT == MVT::v8i64)
1138 return &ARM::QQQQPRRegClass;
1140 return TargetLowering::getRegClassFor(VT);
1143 // Create a fast isel object.
1145 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1146 const TargetLibraryInfo *libInfo) const {
1147 return ARM::createFastISel(funcInfo, libInfo);
1150 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1151 /// be used for loads / stores from the global.
1152 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1153 return (Subtarget->isThumb1Only() ? 127 : 4095);
1156 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1157 unsigned NumVals = N->getNumValues();
1159 return Sched::RegPressure;
1161 for (unsigned i = 0; i != NumVals; ++i) {
1162 EVT VT = N->getValueType(i);
1163 if (VT == MVT::Glue || VT == MVT::Other)
1165 if (VT.isFloatingPoint() || VT.isVector())
1169 if (!N->isMachineOpcode())
1170 return Sched::RegPressure;
1172 // Load are scheduled for latency even if there instruction itinerary
1173 // is not available.
1174 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1175 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1177 if (MCID.getNumDefs() == 0)
1178 return Sched::RegPressure;
1179 if (!Itins->isEmpty() &&
1180 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1183 return Sched::RegPressure;
1186 //===----------------------------------------------------------------------===//
1188 //===----------------------------------------------------------------------===//
1190 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1191 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1193 default: llvm_unreachable("Unknown condition code!");
1194 case ISD::SETNE: return ARMCC::NE;
1195 case ISD::SETEQ: return ARMCC::EQ;
1196 case ISD::SETGT: return ARMCC::GT;
1197 case ISD::SETGE: return ARMCC::GE;
1198 case ISD::SETLT: return ARMCC::LT;
1199 case ISD::SETLE: return ARMCC::LE;
1200 case ISD::SETUGT: return ARMCC::HI;
1201 case ISD::SETUGE: return ARMCC::HS;
1202 case ISD::SETULT: return ARMCC::LO;
1203 case ISD::SETULE: return ARMCC::LS;
1207 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1208 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1209 ARMCC::CondCodes &CondCode2) {
1210 CondCode2 = ARMCC::AL;
1212 default: llvm_unreachable("Unknown FP condition!");
1214 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1216 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1218 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1219 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1220 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1221 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1222 case ISD::SETO: CondCode = ARMCC::VC; break;
1223 case ISD::SETUO: CondCode = ARMCC::VS; break;
1224 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1225 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1226 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1228 case ISD::SETULT: CondCode = ARMCC::LT; break;
1230 case ISD::SETULE: CondCode = ARMCC::LE; break;
1232 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1236 //===----------------------------------------------------------------------===//
1237 // Calling Convention Implementation
1238 //===----------------------------------------------------------------------===//
1240 #include "ARMGenCallingConv.inc"
1242 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1243 /// account presence of floating point hardware and calling convention
1244 /// limitations, such as support for variadic functions.
1246 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1247 bool isVarArg) const {
1250 llvm_unreachable("Unsupported calling convention");
1251 case CallingConv::ARM_AAPCS:
1252 case CallingConv::ARM_APCS:
1253 case CallingConv::GHC:
1255 case CallingConv::ARM_AAPCS_VFP:
1256 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1257 case CallingConv::C:
1258 if (!Subtarget->isAAPCS_ABI())
1259 return CallingConv::ARM_APCS;
1260 else if (Subtarget->hasVFP2() &&
1261 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1263 return CallingConv::ARM_AAPCS_VFP;
1265 return CallingConv::ARM_AAPCS;
1266 case CallingConv::Fast:
1267 if (!Subtarget->isAAPCS_ABI()) {
1268 if (Subtarget->hasVFP2() && !isVarArg)
1269 return CallingConv::Fast;
1270 return CallingConv::ARM_APCS;
1271 } else if (Subtarget->hasVFP2() && !isVarArg)
1272 return CallingConv::ARM_AAPCS_VFP;
1274 return CallingConv::ARM_AAPCS;
1278 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1279 /// CallingConvention.
1280 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1282 bool isVarArg) const {
1283 switch (getEffectiveCallingConv(CC, isVarArg)) {
1285 llvm_unreachable("Unsupported calling convention");
1286 case CallingConv::ARM_APCS:
1287 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1288 case CallingConv::ARM_AAPCS:
1289 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1290 case CallingConv::ARM_AAPCS_VFP:
1291 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1292 case CallingConv::Fast:
1293 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1294 case CallingConv::GHC:
1295 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1299 /// LowerCallResult - Lower the result values of a call into the
1300 /// appropriate copies out of appropriate physical registers.
1302 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1303 CallingConv::ID CallConv, bool isVarArg,
1304 const SmallVectorImpl<ISD::InputArg> &Ins,
1305 SDLoc dl, SelectionDAG &DAG,
1306 SmallVectorImpl<SDValue> &InVals,
1307 bool isThisReturn, SDValue ThisVal) const {
1309 // Assign locations to each value returned by this call.
1310 SmallVector<CCValAssign, 16> RVLocs;
1311 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1312 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1313 CCInfo.AnalyzeCallResult(Ins,
1314 CCAssignFnForNode(CallConv, /* Return*/ true,
1317 // Copy all of the result registers out of their specified physreg.
1318 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1319 CCValAssign VA = RVLocs[i];
1321 // Pass 'this' value directly from the argument to return value, to avoid
1322 // reg unit interference
1323 if (i == 0 && isThisReturn) {
1324 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1325 "unexpected return calling convention register assignment");
1326 InVals.push_back(ThisVal);
1331 if (VA.needsCustom()) {
1332 // Handle f64 or half of a v2f64.
1333 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1335 Chain = Lo.getValue(1);
1336 InFlag = Lo.getValue(2);
1337 VA = RVLocs[++i]; // skip ahead to next loc
1338 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1340 Chain = Hi.getValue(1);
1341 InFlag = Hi.getValue(2);
1342 if (!Subtarget->isLittle())
1344 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1346 if (VA.getLocVT() == MVT::v2f64) {
1347 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1348 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1349 DAG.getConstant(0, MVT::i32));
1351 VA = RVLocs[++i]; // skip ahead to next loc
1352 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1353 Chain = Lo.getValue(1);
1354 InFlag = Lo.getValue(2);
1355 VA = RVLocs[++i]; // skip ahead to next loc
1356 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1357 Chain = Hi.getValue(1);
1358 InFlag = Hi.getValue(2);
1359 if (!Subtarget->isLittle())
1361 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1362 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1363 DAG.getConstant(1, MVT::i32));
1366 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1368 Chain = Val.getValue(1);
1369 InFlag = Val.getValue(2);
1372 switch (VA.getLocInfo()) {
1373 default: llvm_unreachable("Unknown loc info!");
1374 case CCValAssign::Full: break;
1375 case CCValAssign::BCvt:
1376 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1380 InVals.push_back(Val);
1386 /// LowerMemOpCallTo - Store the argument to the stack.
1388 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1389 SDValue StackPtr, SDValue Arg,
1390 SDLoc dl, SelectionDAG &DAG,
1391 const CCValAssign &VA,
1392 ISD::ArgFlagsTy Flags) const {
1393 unsigned LocMemOffset = VA.getLocMemOffset();
1394 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1395 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1396 return DAG.getStore(Chain, dl, Arg, PtrOff,
1397 MachinePointerInfo::getStack(LocMemOffset),
1401 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1402 SDValue Chain, SDValue &Arg,
1403 RegsToPassVector &RegsToPass,
1404 CCValAssign &VA, CCValAssign &NextVA,
1406 SmallVectorImpl<SDValue> &MemOpChains,
1407 ISD::ArgFlagsTy Flags) const {
1409 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1410 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1411 unsigned id = Subtarget->isLittle() ? 0 : 1;
1412 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1414 if (NextVA.isRegLoc())
1415 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1417 assert(NextVA.isMemLoc());
1418 if (!StackPtr.getNode())
1419 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1421 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1427 /// LowerCall - Lowering a call into a callseq_start <-
1428 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1431 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1432 SmallVectorImpl<SDValue> &InVals) const {
1433 SelectionDAG &DAG = CLI.DAG;
1435 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1436 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1437 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1438 SDValue Chain = CLI.Chain;
1439 SDValue Callee = CLI.Callee;
1440 bool &isTailCall = CLI.IsTailCall;
1441 CallingConv::ID CallConv = CLI.CallConv;
1442 bool doesNotRet = CLI.DoesNotReturn;
1443 bool isVarArg = CLI.IsVarArg;
1445 MachineFunction &MF = DAG.getMachineFunction();
1446 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1447 bool isThisReturn = false;
1448 bool isSibCall = false;
1450 // Disable tail calls if they're not supported.
1451 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1455 // Check if it's really possible to do a tail call.
1456 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1457 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1458 Outs, OutVals, Ins, DAG);
1459 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1460 report_fatal_error("failed to perform tail call elimination on a call "
1461 "site marked musttail");
1462 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1463 // detected sibcalls.
1470 // Analyze operands of the call, assigning locations to each operand.
1471 SmallVector<CCValAssign, 16> ArgLocs;
1472 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1473 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1474 CCInfo.AnalyzeCallOperands(Outs,
1475 CCAssignFnForNode(CallConv, /* Return*/ false,
1478 // Get a count of how many bytes are to be pushed on the stack.
1479 unsigned NumBytes = CCInfo.getNextStackOffset();
1481 // For tail calls, memory operands are available in our caller's stack.
1485 // Adjust the stack pointer for the new arguments...
1486 // These operations are automatically eliminated by the prolog/epilog pass
1488 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1491 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1493 RegsToPassVector RegsToPass;
1494 SmallVector<SDValue, 8> MemOpChains;
1496 // Walk the register/memloc assignments, inserting copies/loads. In the case
1497 // of tail call optimization, arguments are handled later.
1498 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1500 ++i, ++realArgIdx) {
1501 CCValAssign &VA = ArgLocs[i];
1502 SDValue Arg = OutVals[realArgIdx];
1503 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1504 bool isByVal = Flags.isByVal();
1506 // Promote the value if needed.
1507 switch (VA.getLocInfo()) {
1508 default: llvm_unreachable("Unknown loc info!");
1509 case CCValAssign::Full: break;
1510 case CCValAssign::SExt:
1511 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1513 case CCValAssign::ZExt:
1514 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1516 case CCValAssign::AExt:
1517 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1519 case CCValAssign::BCvt:
1520 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1524 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1525 if (VA.needsCustom()) {
1526 if (VA.getLocVT() == MVT::v2f64) {
1527 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1528 DAG.getConstant(0, MVT::i32));
1529 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1530 DAG.getConstant(1, MVT::i32));
1532 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1533 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1535 VA = ArgLocs[++i]; // skip ahead to next loc
1536 if (VA.isRegLoc()) {
1537 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1538 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1540 assert(VA.isMemLoc());
1542 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1543 dl, DAG, VA, Flags));
1546 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1547 StackPtr, MemOpChains, Flags);
1549 } else if (VA.isRegLoc()) {
1550 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1551 assert(VA.getLocVT() == MVT::i32 &&
1552 "unexpected calling convention register assignment");
1553 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1554 "unexpected use of 'returned'");
1555 isThisReturn = true;
1557 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1558 } else if (isByVal) {
1559 assert(VA.isMemLoc());
1560 unsigned offset = 0;
1562 // True if this byval aggregate will be split between registers
1564 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1565 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1567 if (CurByValIdx < ByValArgsCount) {
1569 unsigned RegBegin, RegEnd;
1570 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1572 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1574 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1575 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1576 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1577 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1578 MachinePointerInfo(),
1579 false, false, false,
1580 DAG.InferPtrAlignment(AddArg));
1581 MemOpChains.push_back(Load.getValue(1));
1582 RegsToPass.push_back(std::make_pair(j, Load));
1585 // If parameter size outsides register area, "offset" value
1586 // helps us to calculate stack slot for remained part properly.
1587 offset = RegEnd - RegBegin;
1589 CCInfo.nextInRegsParam();
1592 if (Flags.getByValSize() > 4*offset) {
1593 unsigned LocMemOffset = VA.getLocMemOffset();
1594 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1595 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1597 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1598 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1599 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1601 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1603 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1604 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1605 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1608 } else if (!isSibCall) {
1609 assert(VA.isMemLoc());
1611 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1612 dl, DAG, VA, Flags));
1616 if (!MemOpChains.empty())
1617 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1619 // Build a sequence of copy-to-reg nodes chained together with token chain
1620 // and flag operands which copy the outgoing args into the appropriate regs.
1622 // Tail call byval lowering might overwrite argument registers so in case of
1623 // tail call optimization the copies to registers are lowered later.
1625 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1626 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1627 RegsToPass[i].second, InFlag);
1628 InFlag = Chain.getValue(1);
1631 // For tail calls lower the arguments to the 'real' stack slot.
1633 // Force all the incoming stack arguments to be loaded from the stack
1634 // before any new outgoing arguments are stored to the stack, because the
1635 // outgoing stack slots may alias the incoming argument stack slots, and
1636 // the alias isn't otherwise explicit. This is slightly more conservative
1637 // than necessary, because it means that each store effectively depends
1638 // on every argument instead of just those arguments it would clobber.
1640 // Do not flag preceding copytoreg stuff together with the following stuff.
1642 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1643 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1644 RegsToPass[i].second, InFlag);
1645 InFlag = Chain.getValue(1);
1650 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1651 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1652 // node so that legalize doesn't hack it.
1653 bool isDirect = false;
1654 bool isARMFunc = false;
1655 bool isLocalARMFunc = false;
1656 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1658 if (EnableARMLongCalls) {
1659 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1660 && "long-calls with non-static relocation model!");
1661 // Handle a global address or an external symbol. If it's not one of
1662 // those, the target's already in a register, so we don't need to do
1664 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1665 const GlobalValue *GV = G->getGlobal();
1666 // Create a constant pool entry for the callee address
1667 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1668 ARMConstantPoolValue *CPV =
1669 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1671 // Get the address of the callee into a register
1672 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1673 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1674 Callee = DAG.getLoad(getPointerTy(), dl,
1675 DAG.getEntryNode(), CPAddr,
1676 MachinePointerInfo::getConstantPool(),
1677 false, false, false, 0);
1678 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1679 const char *Sym = S->getSymbol();
1681 // Create a constant pool entry for the callee address
1682 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1683 ARMConstantPoolValue *CPV =
1684 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1685 ARMPCLabelIndex, 0);
1686 // Get the address of the callee into a register
1687 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1688 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1689 Callee = DAG.getLoad(getPointerTy(), dl,
1690 DAG.getEntryNode(), CPAddr,
1691 MachinePointerInfo::getConstantPool(),
1692 false, false, false, 0);
1694 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1695 const GlobalValue *GV = G->getGlobal();
1697 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1698 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1699 getTargetMachine().getRelocationModel() != Reloc::Static;
1700 isARMFunc = !Subtarget->isThumb() || isStub;
1701 // ARM call to a local ARM function is predicable.
1702 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1703 // tBX takes a register source operand.
1704 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1705 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1706 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1707 DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1709 // On ELF targets for PIC code, direct calls should go through the PLT
1710 unsigned OpFlags = 0;
1711 if (Subtarget->isTargetELF() &&
1712 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1713 OpFlags = ARMII::MO_PLT;
1714 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1716 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1718 bool isStub = Subtarget->isTargetMachO() &&
1719 getTargetMachine().getRelocationModel() != Reloc::Static;
1720 isARMFunc = !Subtarget->isThumb() || isStub;
1721 // tBX takes a register source operand.
1722 const char *Sym = S->getSymbol();
1723 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1724 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1725 ARMConstantPoolValue *CPV =
1726 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1727 ARMPCLabelIndex, 4);
1728 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1729 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1730 Callee = DAG.getLoad(getPointerTy(), dl,
1731 DAG.getEntryNode(), CPAddr,
1732 MachinePointerInfo::getConstantPool(),
1733 false, false, false, 0);
1734 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1735 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1736 getPointerTy(), Callee, PICLabel);
1738 unsigned OpFlags = 0;
1739 // On ELF targets for PIC code, direct calls should go through the PLT
1740 if (Subtarget->isTargetELF() &&
1741 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1742 OpFlags = ARMII::MO_PLT;
1743 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1747 // FIXME: handle tail calls differently.
1749 bool HasMinSizeAttr = Subtarget->isMinSize();
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);
1806 // Returns a chain and a flag for retval copy to use.
1807 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
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 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1835 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1836 unsigned AlignInRegs = Align / 4;
1837 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1838 for (unsigned i = 0; i < Waste; ++i)
1839 reg = State->AllocateReg(GPRArgRegs, 4);
1842 unsigned excess = 4 * (ARM::R4 - reg);
1844 // Special case when NSAA != SP and parameter size greater than size of
1845 // all remained GPR regs. In that case we can't split parameter, we must
1846 // send it to stack. We also must set NCRN to R4, so waste all
1847 // remained registers.
1848 const unsigned NSAAOffset = State->getNextStackOffset();
1849 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1850 while (State->AllocateReg(GPRArgRegs, 4))
1855 // First register for byval parameter is the first register that wasn't
1856 // allocated before this method call, so it would be "reg".
1857 // If parameter is small enough to be saved in range [reg, r4), then
1858 // the end (first after last) register would be reg + param-size-in-regs,
1859 // else parameter would be splitted between registers and stack,
1860 // end register would be r4 in this case.
1861 unsigned ByValRegBegin = reg;
1862 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1863 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1864 // Note, first register is allocated in the beginning of function already,
1865 // allocate remained amount of registers we need.
1866 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1867 State->AllocateReg(GPRArgRegs, 4);
1868 // A byval parameter that is split between registers and memory needs its
1869 // size truncated here.
1870 // In the case where the entire structure fits in registers, we set the
1871 // size in memory to zero.
1880 /// MatchingStackOffset - Return true if the given stack call argument is
1881 /// already available in the same position (relatively) of the caller's
1882 /// incoming argument stack.
1884 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1885 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1886 const TargetInstrInfo *TII) {
1887 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1889 if (Arg.getOpcode() == ISD::CopyFromReg) {
1890 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1891 if (!TargetRegisterInfo::isVirtualRegister(VR))
1893 MachineInstr *Def = MRI->getVRegDef(VR);
1896 if (!Flags.isByVal()) {
1897 if (!TII->isLoadFromStackSlot(Def, FI))
1902 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1903 if (Flags.isByVal())
1904 // ByVal argument is passed in as a pointer but it's now being
1905 // dereferenced. e.g.
1906 // define @foo(%struct.X* %A) {
1907 // tail call @bar(%struct.X* byval %A)
1910 SDValue Ptr = Ld->getBasePtr();
1911 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1914 FI = FINode->getIndex();
1918 assert(FI != INT_MAX);
1919 if (!MFI->isFixedObjectIndex(FI))
1921 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1924 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1925 /// for tail call optimization. Targets which want to do tail call
1926 /// optimization should implement this function.
1928 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1929 CallingConv::ID CalleeCC,
1931 bool isCalleeStructRet,
1932 bool isCallerStructRet,
1933 const SmallVectorImpl<ISD::OutputArg> &Outs,
1934 const SmallVectorImpl<SDValue> &OutVals,
1935 const SmallVectorImpl<ISD::InputArg> &Ins,
1936 SelectionDAG& DAG) const {
1937 const Function *CallerF = DAG.getMachineFunction().getFunction();
1938 CallingConv::ID CallerCC = CallerF->getCallingConv();
1939 bool CCMatch = CallerCC == CalleeCC;
1941 // Look for obvious safe cases to perform tail call optimization that do not
1942 // require ABI changes. This is what gcc calls sibcall.
1944 // Do not sibcall optimize vararg calls unless the call site is not passing
1946 if (isVarArg && !Outs.empty())
1949 // Exception-handling functions need a special set of instructions to indicate
1950 // a return to the hardware. Tail-calling another function would probably
1952 if (CallerF->hasFnAttribute("interrupt"))
1955 // Also avoid sibcall optimization if either caller or callee uses struct
1956 // return semantics.
1957 if (isCalleeStructRet || isCallerStructRet)
1960 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1961 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1962 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1963 // support in the assembler and linker to be used. This would need to be
1964 // fixed to fully support tail calls in Thumb1.
1966 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1967 // LR. This means if we need to reload LR, it takes an extra instructions,
1968 // which outweighs the value of the tail call; but here we don't know yet
1969 // whether LR is going to be used. Probably the right approach is to
1970 // generate the tail call here and turn it back into CALL/RET in
1971 // emitEpilogue if LR is used.
1973 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1974 // but we need to make sure there are enough registers; the only valid
1975 // registers are the 4 used for parameters. We don't currently do this
1977 if (Subtarget->isThumb1Only())
1980 // If the calling conventions do not match, then we'd better make sure the
1981 // results are returned in the same way as what the caller expects.
1983 SmallVector<CCValAssign, 16> RVLocs1;
1984 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1985 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1986 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1988 SmallVector<CCValAssign, 16> RVLocs2;
1989 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1990 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1991 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1993 if (RVLocs1.size() != RVLocs2.size())
1995 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1996 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1998 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2000 if (RVLocs1[i].isRegLoc()) {
2001 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2004 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2010 // If Caller's vararg or byval argument has been split between registers and
2011 // stack, do not perform tail call, since part of the argument is in caller's
2013 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2014 getInfo<ARMFunctionInfo>();
2015 if (AFI_Caller->getArgRegsSaveSize())
2018 // If the callee takes no arguments then go on to check the results of the
2020 if (!Outs.empty()) {
2021 // Check if stack adjustment is needed. For now, do not do this if any
2022 // argument is passed on the stack.
2023 SmallVector<CCValAssign, 16> ArgLocs;
2024 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2025 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2026 CCInfo.AnalyzeCallOperands(Outs,
2027 CCAssignFnForNode(CalleeCC, false, isVarArg));
2028 if (CCInfo.getNextStackOffset()) {
2029 MachineFunction &MF = DAG.getMachineFunction();
2031 // Check if the arguments are already laid out in the right way as
2032 // the caller's fixed stack objects.
2033 MachineFrameInfo *MFI = MF.getFrameInfo();
2034 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2035 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2036 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2038 ++i, ++realArgIdx) {
2039 CCValAssign &VA = ArgLocs[i];
2040 EVT RegVT = VA.getLocVT();
2041 SDValue Arg = OutVals[realArgIdx];
2042 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2043 if (VA.getLocInfo() == CCValAssign::Indirect)
2045 if (VA.needsCustom()) {
2046 // f64 and vector types are split into multiple registers or
2047 // register/stack-slot combinations. The types will not match
2048 // the registers; give up on memory f64 refs until we figure
2049 // out what to do about this.
2052 if (!ArgLocs[++i].isRegLoc())
2054 if (RegVT == MVT::v2f64) {
2055 if (!ArgLocs[++i].isRegLoc())
2057 if (!ArgLocs[++i].isRegLoc())
2060 } else if (!VA.isRegLoc()) {
2061 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2073 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2074 MachineFunction &MF, bool isVarArg,
2075 const SmallVectorImpl<ISD::OutputArg> &Outs,
2076 LLVMContext &Context) const {
2077 SmallVector<CCValAssign, 16> RVLocs;
2078 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2079 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2083 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2084 SDLoc DL, SelectionDAG &DAG) {
2085 const MachineFunction &MF = DAG.getMachineFunction();
2086 const Function *F = MF.getFunction();
2088 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2090 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2091 // version of the "preferred return address". These offsets affect the return
2092 // instruction if this is a return from PL1 without hypervisor extensions.
2093 // IRQ/FIQ: +4 "subs pc, lr, #4"
2094 // SWI: 0 "subs pc, lr, #0"
2095 // ABORT: +4 "subs pc, lr, #4"
2096 // UNDEF: +4/+2 "subs pc, lr, #0"
2097 // UNDEF varies depending on where the exception came from ARM or Thumb
2098 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2101 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2104 else if (IntKind == "SWI" || IntKind == "UNDEF")
2107 report_fatal_error("Unsupported interrupt attribute. If present, value "
2108 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2110 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2112 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2116 ARMTargetLowering::LowerReturn(SDValue Chain,
2117 CallingConv::ID CallConv, bool isVarArg,
2118 const SmallVectorImpl<ISD::OutputArg> &Outs,
2119 const SmallVectorImpl<SDValue> &OutVals,
2120 SDLoc dl, SelectionDAG &DAG) const {
2122 // CCValAssign - represent the assignment of the return value to a location.
2123 SmallVector<CCValAssign, 16> RVLocs;
2125 // CCState - Info about the registers and stack slots.
2126 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2127 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2129 // Analyze outgoing return values.
2130 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2134 SmallVector<SDValue, 4> RetOps;
2135 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2136 bool isLittleEndian = Subtarget->isLittle();
2138 // Copy the result values into the output registers.
2139 for (unsigned i = 0, realRVLocIdx = 0;
2141 ++i, ++realRVLocIdx) {
2142 CCValAssign &VA = RVLocs[i];
2143 assert(VA.isRegLoc() && "Can only return in registers!");
2145 SDValue Arg = OutVals[realRVLocIdx];
2147 switch (VA.getLocInfo()) {
2148 default: llvm_unreachable("Unknown loc info!");
2149 case CCValAssign::Full: break;
2150 case CCValAssign::BCvt:
2151 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2155 if (VA.needsCustom()) {
2156 if (VA.getLocVT() == MVT::v2f64) {
2157 // Extract the first half and return it in two registers.
2158 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2159 DAG.getConstant(0, MVT::i32));
2160 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2161 DAG.getVTList(MVT::i32, MVT::i32), Half);
2163 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2164 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2166 Flag = Chain.getValue(1);
2167 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2168 VA = RVLocs[++i]; // skip ahead to next loc
2169 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2170 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2172 Flag = Chain.getValue(1);
2173 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2174 VA = RVLocs[++i]; // skip ahead to next loc
2176 // Extract the 2nd half and fall through to handle it as an f64 value.
2177 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2178 DAG.getConstant(1, MVT::i32));
2180 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2182 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2183 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2184 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2185 fmrrd.getValue(isLittleEndian ? 0 : 1),
2187 Flag = Chain.getValue(1);
2188 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2189 VA = RVLocs[++i]; // skip ahead to next loc
2190 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2191 fmrrd.getValue(isLittleEndian ? 1 : 0),
2194 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2196 // Guarantee that all emitted copies are
2197 // stuck together, avoiding something bad.
2198 Flag = Chain.getValue(1);
2199 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2202 // Update chain and glue.
2205 RetOps.push_back(Flag);
2207 // CPUs which aren't M-class use a special sequence to return from
2208 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2209 // though we use "subs pc, lr, #N").
2211 // M-class CPUs actually use a normal return sequence with a special
2212 // (hardware-provided) value in LR, so the normal code path works.
2213 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2214 !Subtarget->isMClass()) {
2215 if (Subtarget->isThumb1Only())
2216 report_fatal_error("interrupt attribute is not supported in Thumb1");
2217 return LowerInterruptReturn(RetOps, dl, DAG);
2220 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2223 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2224 if (N->getNumValues() != 1)
2226 if (!N->hasNUsesOfValue(1, 0))
2229 SDValue TCChain = Chain;
2230 SDNode *Copy = *N->use_begin();
2231 if (Copy->getOpcode() == ISD::CopyToReg) {
2232 // If the copy has a glue operand, we conservatively assume it isn't safe to
2233 // perform a tail call.
2234 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2236 TCChain = Copy->getOperand(0);
2237 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2238 SDNode *VMov = Copy;
2239 // f64 returned in a pair of GPRs.
2240 SmallPtrSet<SDNode*, 2> Copies;
2241 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2243 if (UI->getOpcode() != ISD::CopyToReg)
2247 if (Copies.size() > 2)
2250 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2252 SDValue UseChain = UI->getOperand(0);
2253 if (Copies.count(UseChain.getNode()))
2260 } else if (Copy->getOpcode() == ISD::BITCAST) {
2261 // f32 returned in a single GPR.
2262 if (!Copy->hasOneUse())
2264 Copy = *Copy->use_begin();
2265 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2267 TCChain = Copy->getOperand(0);
2272 bool HasRet = false;
2273 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2275 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2276 UI->getOpcode() != ARMISD::INTRET_FLAG)
2288 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2289 if (!Subtarget->supportsTailCall())
2292 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2295 return !Subtarget->isThumb1Only();
2298 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2299 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2300 // one of the above mentioned nodes. It has to be wrapped because otherwise
2301 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2302 // be used to form addressing mode. These wrapped nodes will be selected
2304 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2305 EVT PtrVT = Op.getValueType();
2306 // FIXME there is no actual debug info here
2308 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2310 if (CP->isMachineConstantPoolEntry())
2311 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2312 CP->getAlignment());
2314 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2315 CP->getAlignment());
2316 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2319 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2320 return MachineJumpTableInfo::EK_Inline;
2323 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2324 SelectionDAG &DAG) const {
2325 MachineFunction &MF = DAG.getMachineFunction();
2326 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2327 unsigned ARMPCLabelIndex = 0;
2329 EVT PtrVT = getPointerTy();
2330 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2331 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2333 if (RelocM == Reloc::Static) {
2334 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2336 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2337 ARMPCLabelIndex = AFI->createPICLabelUId();
2338 ARMConstantPoolValue *CPV =
2339 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2340 ARMCP::CPBlockAddress, PCAdj);
2341 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2343 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2344 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2345 MachinePointerInfo::getConstantPool(),
2346 false, false, false, 0);
2347 if (RelocM == Reloc::Static)
2349 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2350 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2353 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2355 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2356 SelectionDAG &DAG) const {
2358 EVT PtrVT = getPointerTy();
2359 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2360 MachineFunction &MF = DAG.getMachineFunction();
2361 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2362 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2363 ARMConstantPoolValue *CPV =
2364 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2365 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2366 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2367 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2368 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2369 MachinePointerInfo::getConstantPool(),
2370 false, false, false, 0);
2371 SDValue Chain = Argument.getValue(1);
2373 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2374 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2376 // call __tls_get_addr.
2379 Entry.Node = Argument;
2380 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2381 Args.push_back(Entry);
2382 // FIXME: is there useful debug info available here?
2383 TargetLowering::CallLoweringInfo CLI(Chain,
2384 (Type *) Type::getInt32Ty(*DAG.getContext()),
2385 false, false, false, false,
2386 0, CallingConv::C, /*isTailCall=*/false,
2387 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2388 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2389 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2390 return CallResult.first;
2393 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2394 // "local exec" model.
2396 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2398 TLSModel::Model model) const {
2399 const GlobalValue *GV = GA->getGlobal();
2402 SDValue Chain = DAG.getEntryNode();
2403 EVT PtrVT = getPointerTy();
2404 // Get the Thread Pointer
2405 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2407 if (model == TLSModel::InitialExec) {
2408 MachineFunction &MF = DAG.getMachineFunction();
2409 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2410 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2411 // Initial exec model.
2412 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2413 ARMConstantPoolValue *CPV =
2414 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2415 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2417 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2418 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2419 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2420 MachinePointerInfo::getConstantPool(),
2421 false, false, false, 0);
2422 Chain = Offset.getValue(1);
2424 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2425 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2427 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2428 MachinePointerInfo::getConstantPool(),
2429 false, false, false, 0);
2432 assert(model == TLSModel::LocalExec);
2433 ARMConstantPoolValue *CPV =
2434 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2435 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2436 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2437 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2438 MachinePointerInfo::getConstantPool(),
2439 false, false, false, 0);
2442 // The address of the thread local variable is the add of the thread
2443 // pointer with the offset of the variable.
2444 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2448 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2449 // TODO: implement the "local dynamic" model
2450 assert(Subtarget->isTargetELF() &&
2451 "TLS not implemented for non-ELF targets");
2452 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2454 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2457 case TLSModel::GeneralDynamic:
2458 case TLSModel::LocalDynamic:
2459 return LowerToTLSGeneralDynamicModel(GA, DAG);
2460 case TLSModel::InitialExec:
2461 case TLSModel::LocalExec:
2462 return LowerToTLSExecModels(GA, DAG, model);
2464 llvm_unreachable("bogus TLS model");
2467 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2468 SelectionDAG &DAG) const {
2469 EVT PtrVT = getPointerTy();
2471 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2472 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2473 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2474 ARMConstantPoolValue *CPV =
2475 ARMConstantPoolConstant::Create(GV,
2476 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2477 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2478 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2479 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2481 MachinePointerInfo::getConstantPool(),
2482 false, false, false, 0);
2483 SDValue Chain = Result.getValue(1);
2484 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2485 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2487 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2488 MachinePointerInfo::getGOT(),
2489 false, false, false, 0);
2493 // If we have T2 ops, we can materialize the address directly via movt/movw
2494 // pair. This is always cheaper.
2495 if (Subtarget->useMovt()) {
2497 // FIXME: Once remat is capable of dealing with instructions with register
2498 // operands, expand this into two nodes.
2499 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2500 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2502 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2503 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2504 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2505 MachinePointerInfo::getConstantPool(),
2506 false, false, false, 0);
2510 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2511 SelectionDAG &DAG) const {
2512 EVT PtrVT = getPointerTy();
2514 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2515 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2517 if (Subtarget->useMovt())
2520 // FIXME: Once remat is capable of dealing with instructions with register
2521 // operands, expand this into multiple nodes
2523 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2525 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2526 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2528 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2529 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2530 MachinePointerInfo::getGOT(), false, false, false, 0);
2534 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2535 SelectionDAG &DAG) const {
2536 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2537 assert(Subtarget->useMovt() && "Windows on ARM expects to use movw/movt");
2539 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2540 EVT PtrVT = getPointerTy();
2545 // FIXME: Once remat is capable of dealing with instructions with register
2546 // operands, expand this into two nodes.
2547 return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2548 DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2551 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2552 SelectionDAG &DAG) const {
2553 assert(Subtarget->isTargetELF() &&
2554 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2555 MachineFunction &MF = DAG.getMachineFunction();
2556 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2557 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2558 EVT PtrVT = getPointerTy();
2560 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2561 ARMConstantPoolValue *CPV =
2562 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2563 ARMPCLabelIndex, PCAdj);
2564 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2565 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2566 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2567 MachinePointerInfo::getConstantPool(),
2568 false, false, false, 0);
2569 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2570 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2574 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2576 SDValue Val = DAG.getConstant(0, MVT::i32);
2577 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2578 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2579 Op.getOperand(1), Val);
2583 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2585 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2586 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2590 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2591 const ARMSubtarget *Subtarget) const {
2592 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2595 default: return SDValue(); // Don't custom lower most intrinsics.
2596 case Intrinsic::arm_thread_pointer: {
2597 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2598 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2600 case Intrinsic::eh_sjlj_lsda: {
2601 MachineFunction &MF = DAG.getMachineFunction();
2602 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2603 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2604 EVT PtrVT = getPointerTy();
2605 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2607 unsigned PCAdj = (RelocM != Reloc::PIC_)
2608 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2609 ARMConstantPoolValue *CPV =
2610 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2611 ARMCP::CPLSDA, PCAdj);
2612 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2613 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2615 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2616 MachinePointerInfo::getConstantPool(),
2617 false, false, false, 0);
2619 if (RelocM == Reloc::PIC_) {
2620 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2621 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2625 case Intrinsic::arm_neon_vmulls:
2626 case Intrinsic::arm_neon_vmullu: {
2627 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2628 ? ARMISD::VMULLs : ARMISD::VMULLu;
2629 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2630 Op.getOperand(1), Op.getOperand(2));
2635 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2636 const ARMSubtarget *Subtarget) {
2637 // FIXME: handle "fence singlethread" more efficiently.
2639 if (!Subtarget->hasDataBarrier()) {
2640 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2641 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2643 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2644 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2645 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2646 DAG.getConstant(0, MVT::i32));
2649 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2650 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2651 unsigned Domain = ARM_MB::ISH;
2652 if (Subtarget->isMClass()) {
2653 // Only a full system barrier exists in the M-class architectures.
2654 Domain = ARM_MB::SY;
2655 } else if (Subtarget->isSwift() && Ord == Release) {
2656 // Swift happens to implement ISHST barriers in a way that's compatible with
2657 // Release semantics but weaker than ISH so we'd be fools not to use
2658 // it. Beware: other processors probably don't!
2659 Domain = ARM_MB::ISHST;
2662 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2663 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2664 DAG.getConstant(Domain, MVT::i32));
2667 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2668 const ARMSubtarget *Subtarget) {
2669 // ARM pre v5TE and Thumb1 does not have preload instructions.
2670 if (!(Subtarget->isThumb2() ||
2671 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2672 // Just preserve the chain.
2673 return Op.getOperand(0);
2676 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2678 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2679 // ARMv7 with MP extension has PLDW.
2680 return Op.getOperand(0);
2682 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2683 if (Subtarget->isThumb()) {
2685 isRead = ~isRead & 1;
2686 isData = ~isData & 1;
2689 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2690 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2691 DAG.getConstant(isData, MVT::i32));
2694 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2695 MachineFunction &MF = DAG.getMachineFunction();
2696 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2698 // vastart just stores the address of the VarArgsFrameIndex slot into the
2699 // memory location argument.
2701 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2702 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2703 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2704 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2705 MachinePointerInfo(SV), false, false, 0);
2709 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2710 SDValue &Root, SelectionDAG &DAG,
2712 MachineFunction &MF = DAG.getMachineFunction();
2713 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2715 const TargetRegisterClass *RC;
2716 if (AFI->isThumb1OnlyFunction())
2717 RC = &ARM::tGPRRegClass;
2719 RC = &ARM::GPRRegClass;
2721 // Transform the arguments stored in physical registers into virtual ones.
2722 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2723 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2726 if (NextVA.isMemLoc()) {
2727 MachineFrameInfo *MFI = MF.getFrameInfo();
2728 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2730 // Create load node to retrieve arguments from the stack.
2731 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2732 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2733 MachinePointerInfo::getFixedStack(FI),
2734 false, false, false, 0);
2736 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2737 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2739 if (!Subtarget->isLittle())
2740 std::swap (ArgValue, ArgValue2);
2741 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2745 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2746 unsigned InRegsParamRecordIdx,
2748 unsigned &ArgRegsSize,
2749 unsigned &ArgRegsSaveSize)
2752 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2753 unsigned RBegin, REnd;
2754 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2755 NumGPRs = REnd - RBegin;
2757 unsigned int firstUnalloced;
2758 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2759 sizeof(GPRArgRegs) /
2760 sizeof(GPRArgRegs[0]));
2761 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2764 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2765 ArgRegsSize = NumGPRs * 4;
2767 // If parameter is split between stack and GPRs...
2768 if (NumGPRs && Align > 4 &&
2769 (ArgRegsSize < ArgSize ||
2770 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2771 // Add padding for part of param recovered from GPRs. For example,
2772 // if Align == 8, its last byte must be at address K*8 - 1.
2773 // We need to do it, since remained (stack) part of parameter has
2774 // stack alignment, and we need to "attach" "GPRs head" without gaps
2777 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2778 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2780 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2782 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2783 ArgRegsSaveSize = ArgRegsSize + Padding;
2785 // We don't need to extend regs save size for byval parameters if they
2786 // are passed via GPRs only.
2787 ArgRegsSaveSize = ArgRegsSize;
2790 // The remaining GPRs hold either the beginning of variable-argument
2791 // data, or the beginning of an aggregate passed by value (usually
2792 // byval). Either way, we allocate stack slots adjacent to the data
2793 // provided by our caller, and store the unallocated registers there.
2794 // If this is a variadic function, the va_list pointer will begin with
2795 // these values; otherwise, this reassembles a (byval) structure that
2796 // was split between registers and memory.
2797 // Return: The frame index registers were stored into.
2799 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2800 SDLoc dl, SDValue &Chain,
2801 const Value *OrigArg,
2802 unsigned InRegsParamRecordIdx,
2803 unsigned OffsetFromOrigArg,
2807 unsigned ByValStoreOffset,
2808 unsigned TotalArgRegsSaveSize) const {
2810 // Currently, two use-cases possible:
2811 // Case #1. Non-var-args function, and we meet first byval parameter.
2812 // Setup first unallocated register as first byval register;
2813 // eat all remained registers
2814 // (these two actions are performed by HandleByVal method).
2815 // Then, here, we initialize stack frame with
2816 // "store-reg" instructions.
2817 // Case #2. Var-args function, that doesn't contain byval parameters.
2818 // The same: eat all remained unallocated registers,
2819 // initialize stack frame.
2821 MachineFunction &MF = DAG.getMachineFunction();
2822 MachineFrameInfo *MFI = MF.getFrameInfo();
2823 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2824 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2825 unsigned RBegin, REnd;
2826 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2827 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2828 firstRegToSaveIndex = RBegin - ARM::R0;
2829 lastRegToSaveIndex = REnd - ARM::R0;
2831 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2832 (GPRArgRegs, array_lengthof(GPRArgRegs));
2833 lastRegToSaveIndex = 4;
2836 unsigned ArgRegsSize, ArgRegsSaveSize;
2837 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2838 ArgRegsSize, ArgRegsSaveSize);
2840 // Store any by-val regs to their spots on the stack so that they may be
2841 // loaded by deferencing the result of formal parameter pointer or va_next.
2842 // Note: once stack area for byval/varargs registers
2843 // was initialized, it can't be initialized again.
2844 if (ArgRegsSaveSize) {
2845 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2848 assert(AFI->getStoredByValParamsPadding() == 0 &&
2849 "The only parameter may be padded.");
2850 AFI->setStoredByValParamsPadding(Padding);
2853 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2856 (int64_t)TotalArgRegsSaveSize,
2858 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2860 MFI->CreateFixedObject(Padding,
2861 ArgOffset + ByValStoreOffset -
2862 (int64_t)ArgRegsSaveSize,
2866 SmallVector<SDValue, 4> MemOps;
2867 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2868 ++firstRegToSaveIndex, ++i) {
2869 const TargetRegisterClass *RC;
2870 if (AFI->isThumb1OnlyFunction())
2871 RC = &ARM::tGPRRegClass;
2873 RC = &ARM::GPRRegClass;
2875 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2876 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2878 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2879 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2881 MemOps.push_back(Store);
2882 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2883 DAG.getConstant(4, getPointerTy()));
2886 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2888 if (!MemOps.empty())
2889 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2893 // We cannot allocate a zero-byte object for the first variadic argument,
2894 // so just make up a size.
2897 // This will point to the next argument passed via stack.
2898 return MFI->CreateFixedObject(
2899 ArgSize, ArgOffset, !ForceMutable);
2903 // Setup stack frame, the va_list pointer will start from.
2905 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2906 SDLoc dl, SDValue &Chain,
2908 unsigned TotalArgRegsSaveSize,
2909 bool ForceMutable) const {
2910 MachineFunction &MF = DAG.getMachineFunction();
2911 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2913 // Try to store any remaining integer argument regs
2914 // to their spots on the stack so that they may be loaded by deferencing
2915 // the result of va_next.
2916 // If there is no regs to be stored, just point address after last
2917 // argument passed via stack.
2919 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2920 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2921 0, TotalArgRegsSaveSize);
2923 AFI->setVarArgsFrameIndex(FrameIndex);
2927 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2928 CallingConv::ID CallConv, bool isVarArg,
2929 const SmallVectorImpl<ISD::InputArg>
2931 SDLoc dl, SelectionDAG &DAG,
2932 SmallVectorImpl<SDValue> &InVals)
2934 MachineFunction &MF = DAG.getMachineFunction();
2935 MachineFrameInfo *MFI = MF.getFrameInfo();
2937 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2939 // Assign locations to all of the incoming arguments.
2940 SmallVector<CCValAssign, 16> ArgLocs;
2941 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2942 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2943 CCInfo.AnalyzeFormalArguments(Ins,
2944 CCAssignFnForNode(CallConv, /* Return*/ false,
2947 SmallVector<SDValue, 16> ArgValues;
2948 int lastInsIndex = -1;
2950 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2951 unsigned CurArgIdx = 0;
2953 // Initially ArgRegsSaveSize is zero.
2954 // Then we increase this value each time we meet byval parameter.
2955 // We also increase this value in case of varargs function.
2956 AFI->setArgRegsSaveSize(0);
2958 unsigned ByValStoreOffset = 0;
2959 unsigned TotalArgRegsSaveSize = 0;
2960 unsigned ArgRegsSaveSizeMaxAlign = 4;
2962 // Calculate the amount of stack space that we need to allocate to store
2963 // byval and variadic arguments that are passed in registers.
2964 // We need to know this before we allocate the first byval or variadic
2965 // argument, as they will be allocated a stack slot below the CFA (Canonical
2966 // Frame Address, the stack pointer at entry to the function).
2967 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2968 CCValAssign &VA = ArgLocs[i];
2969 if (VA.isMemLoc()) {
2970 int index = VA.getValNo();
2971 if (index != lastInsIndex) {
2972 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2973 if (Flags.isByVal()) {
2974 unsigned ExtraArgRegsSize;
2975 unsigned ExtraArgRegsSaveSize;
2976 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2977 Flags.getByValSize(),
2978 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2980 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2981 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2982 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2983 CCInfo.nextInRegsParam();
2985 lastInsIndex = index;
2989 CCInfo.rewindByValRegsInfo();
2992 unsigned ExtraArgRegsSize;
2993 unsigned ExtraArgRegsSaveSize;
2994 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2995 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2996 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2998 // If the arg regs save area contains N-byte aligned values, the
2999 // bottom of it must be at least N-byte aligned.
3000 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3001 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3003 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3004 CCValAssign &VA = ArgLocs[i];
3005 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3006 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3007 // Arguments stored in registers.
3008 if (VA.isRegLoc()) {
3009 EVT RegVT = VA.getLocVT();
3011 if (VA.needsCustom()) {
3012 // f64 and vector types are split up into multiple registers or
3013 // combinations of registers and stack slots.
3014 if (VA.getLocVT() == MVT::v2f64) {
3015 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3017 VA = ArgLocs[++i]; // skip ahead to next loc
3019 if (VA.isMemLoc()) {
3020 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3021 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3022 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3023 MachinePointerInfo::getFixedStack(FI),
3024 false, false, false, 0);
3026 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3029 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3030 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3031 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3032 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3033 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3035 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3038 const TargetRegisterClass *RC;
3040 if (RegVT == MVT::f32)
3041 RC = &ARM::SPRRegClass;
3042 else if (RegVT == MVT::f64)
3043 RC = &ARM::DPRRegClass;
3044 else if (RegVT == MVT::v2f64)
3045 RC = &ARM::QPRRegClass;
3046 else if (RegVT == MVT::i32)
3047 RC = AFI->isThumb1OnlyFunction() ?
3048 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3049 (const TargetRegisterClass*)&ARM::GPRRegClass;
3051 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3053 // Transform the arguments in physical registers into virtual ones.
3054 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3055 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3058 // If this is an 8 or 16-bit value, it is really passed promoted
3059 // to 32 bits. Insert an assert[sz]ext to capture this, then
3060 // truncate to the right size.
3061 switch (VA.getLocInfo()) {
3062 default: llvm_unreachable("Unknown loc info!");
3063 case CCValAssign::Full: break;
3064 case CCValAssign::BCvt:
3065 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3067 case CCValAssign::SExt:
3068 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3069 DAG.getValueType(VA.getValVT()));
3070 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3072 case CCValAssign::ZExt:
3073 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3074 DAG.getValueType(VA.getValVT()));
3075 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3079 InVals.push_back(ArgValue);
3081 } else { // VA.isRegLoc()
3084 assert(VA.isMemLoc());
3085 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3087 int index = ArgLocs[i].getValNo();
3089 // Some Ins[] entries become multiple ArgLoc[] entries.
3090 // Process them only once.
3091 if (index != lastInsIndex)
3093 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3094 // FIXME: For now, all byval parameter objects are marked mutable.
3095 // This can be changed with more analysis.
3096 // In case of tail call optimization mark all arguments mutable.
3097 // Since they could be overwritten by lowering of arguments in case of
3099 if (Flags.isByVal()) {
3100 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3102 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3103 int FrameIndex = StoreByValRegs(
3104 CCInfo, DAG, dl, Chain, CurOrigArg,
3106 Ins[VA.getValNo()].PartOffset,
3107 VA.getLocMemOffset(),
3108 Flags.getByValSize(),
3109 true /*force mutable frames*/,
3111 TotalArgRegsSaveSize);
3112 ByValStoreOffset += Flags.getByValSize();
3113 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3114 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3115 CCInfo.nextInRegsParam();
3117 unsigned FIOffset = VA.getLocMemOffset();
3118 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3121 // Create load nodes to retrieve arguments from the stack.
3122 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3123 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3124 MachinePointerInfo::getFixedStack(FI),
3125 false, false, false, 0));
3127 lastInsIndex = index;
3134 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3135 CCInfo.getNextStackOffset(),
3136 TotalArgRegsSaveSize);
3138 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3143 /// isFloatingPointZero - Return true if this is +0.0.
3144 static bool isFloatingPointZero(SDValue Op) {
3145 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3146 return CFP->getValueAPF().isPosZero();
3147 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3148 // Maybe this has already been legalized into the constant pool?
3149 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3150 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3151 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3152 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3153 return CFP->getValueAPF().isPosZero();
3159 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3160 /// the given operands.
3162 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3163 SDValue &ARMcc, SelectionDAG &DAG,
3165 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3166 unsigned C = RHSC->getZExtValue();
3167 if (!isLegalICmpImmediate(C)) {
3168 // Constant does not fit, try adjusting it by one?
3173 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3174 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3175 RHS = DAG.getConstant(C-1, MVT::i32);
3180 if (C != 0 && isLegalICmpImmediate(C-1)) {
3181 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3182 RHS = DAG.getConstant(C-1, MVT::i32);
3187 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3188 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3189 RHS = DAG.getConstant(C+1, MVT::i32);
3194 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3195 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3196 RHS = DAG.getConstant(C+1, MVT::i32);
3203 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3204 ARMISD::NodeType CompareType;
3207 CompareType = ARMISD::CMP;
3212 CompareType = ARMISD::CMPZ;
3215 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3216 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3219 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3221 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3224 if (!isFloatingPointZero(RHS))
3225 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3227 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3228 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3231 /// duplicateCmp - Glue values can have only one use, so this function
3232 /// duplicates a comparison node.
3234 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3235 unsigned Opc = Cmp.getOpcode();
3237 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3238 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3240 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3241 Cmp = Cmp.getOperand(0);
3242 Opc = Cmp.getOpcode();
3243 if (Opc == ARMISD::CMPFP)
3244 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3246 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3247 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3249 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3252 std::pair<SDValue, SDValue>
3253 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3254 SDValue &ARMcc) const {
3255 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3257 SDValue Value, OverflowCmp;
3258 SDValue LHS = Op.getOperand(0);
3259 SDValue RHS = Op.getOperand(1);
3262 // FIXME: We are currently always generating CMPs because we don't support
3263 // generating CMN through the backend. This is not as good as the natural
3264 // CMP case because it causes a register dependency and cannot be folded
3267 switch (Op.getOpcode()) {
3269 llvm_unreachable("Unknown overflow instruction!");
3271 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3272 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3273 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3276 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3277 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3278 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3281 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3282 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3283 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3286 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3287 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3288 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3292 return std::make_pair(Value, OverflowCmp);
3297 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3298 // Let legalize expand this if it isn't a legal type yet.
3299 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3302 SDValue Value, OverflowCmp;
3304 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3305 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3306 // We use 0 and 1 as false and true values.
3307 SDValue TVal = DAG.getConstant(1, MVT::i32);
3308 SDValue FVal = DAG.getConstant(0, MVT::i32);
3309 EVT VT = Op.getValueType();
3311 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3312 ARMcc, CCR, OverflowCmp);
3314 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3315 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3319 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3320 SDValue Cond = Op.getOperand(0);
3321 SDValue SelectTrue = Op.getOperand(1);
3322 SDValue SelectFalse = Op.getOperand(2);
3324 unsigned Opc = Cond.getOpcode();
3326 if (Cond.getResNo() == 1 &&
3327 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3328 Opc == ISD::USUBO)) {
3329 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3332 SDValue Value, OverflowCmp;
3334 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3335 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3336 EVT VT = Op.getValueType();
3338 return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3339 ARMcc, CCR, OverflowCmp);
3345 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3346 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3348 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3349 const ConstantSDNode *CMOVTrue =
3350 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3351 const ConstantSDNode *CMOVFalse =
3352 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3354 if (CMOVTrue && CMOVFalse) {
3355 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3356 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3360 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3362 False = SelectFalse;
3363 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3368 if (True.getNode() && False.getNode()) {
3369 EVT VT = Op.getValueType();
3370 SDValue ARMcc = Cond.getOperand(2);
3371 SDValue CCR = Cond.getOperand(3);
3372 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3373 assert(True.getValueType() == VT);
3374 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3379 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3380 // undefined bits before doing a full-word comparison with zero.
3381 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3382 DAG.getConstant(1, Cond.getValueType()));
3384 return DAG.getSelectCC(dl, Cond,
3385 DAG.getConstant(0, Cond.getValueType()),
3386 SelectTrue, SelectFalse, ISD::SETNE);
3389 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3390 if (CC == ISD::SETNE)
3392 return ISD::getSetCCInverse(CC, true);
3395 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3396 bool &swpCmpOps, bool &swpVselOps) {
3397 // Start by selecting the GE condition code for opcodes that return true for
3399 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3401 CondCode = ARMCC::GE;
3403 // and GT for opcodes that return false for 'equality'.
3404 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3406 CondCode = ARMCC::GT;
3408 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3409 // to swap the compare operands.
3410 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3414 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3415 // If we have an unordered opcode, we need to swap the operands to the VSEL
3416 // instruction (effectively negating the condition).
3418 // This also has the effect of swapping which one of 'less' or 'greater'
3419 // returns true, so we also swap the compare operands. It also switches
3420 // whether we return true for 'equality', so we compensate by picking the
3421 // opposite condition code to our original choice.
3422 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3423 CC == ISD::SETUGT) {
3424 swpCmpOps = !swpCmpOps;
3425 swpVselOps = !swpVselOps;
3426 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3429 // 'ordered' is 'anything but unordered', so use the VS condition code and
3430 // swap the VSEL operands.
3431 if (CC == ISD::SETO) {
3432 CondCode = ARMCC::VS;
3436 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3437 // code and swap the VSEL operands.
3438 if (CC == ISD::SETUNE) {
3439 CondCode = ARMCC::EQ;
3444 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3445 EVT VT = Op.getValueType();
3446 SDValue LHS = Op.getOperand(0);
3447 SDValue RHS = Op.getOperand(1);
3448 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3449 SDValue TrueVal = Op.getOperand(2);
3450 SDValue FalseVal = Op.getOperand(3);
3453 if (LHS.getValueType() == MVT::i32) {
3454 // Try to generate VSEL on ARMv8.
3455 // The VSEL instruction can't use all the usual ARM condition
3456 // codes: it only has two bits to select the condition code, so it's
3457 // constrained to use only GE, GT, VS and EQ.
3459 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3460 // swap the operands of the previous compare instruction (effectively
3461 // inverting the compare condition, swapping 'less' and 'greater') and
3462 // sometimes need to swap the operands to the VSEL (which inverts the
3463 // condition in the sense of firing whenever the previous condition didn't)
3464 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3465 TrueVal.getValueType() == MVT::f64)) {
3466 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3467 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3468 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3469 CC = getInverseCCForVSEL(CC);
3470 std::swap(TrueVal, FalseVal);
3475 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3476 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3477 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3481 ARMCC::CondCodes CondCode, CondCode2;
3482 FPCCToARMCC(CC, CondCode, CondCode2);
3484 // Try to generate VSEL on ARMv8.
3485 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3486 TrueVal.getValueType() == MVT::f64)) {
3487 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3488 // same operands, as follows:
3489 // c = fcmp [ogt, olt, ugt, ult] a, b
3491 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3492 // handled differently than the original code sequence.
3493 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3495 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3496 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3497 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3498 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3501 bool swpCmpOps = false;
3502 bool swpVselOps = false;
3503 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3505 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3506 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3508 std::swap(LHS, RHS);
3510 std::swap(TrueVal, FalseVal);
3514 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3515 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3516 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3517 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3519 if (CondCode2 != ARMCC::AL) {
3520 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3521 // FIXME: Needs another CMP because flag can have but one use.
3522 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3523 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3524 Result, TrueVal, ARMcc2, CCR, Cmp2);
3529 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3530 /// to morph to an integer compare sequence.
3531 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3532 const ARMSubtarget *Subtarget) {
3533 SDNode *N = Op.getNode();
3534 if (!N->hasOneUse())
3535 // Otherwise it requires moving the value from fp to integer registers.
3537 if (!N->getNumValues())
3539 EVT VT = Op.getValueType();
3540 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3541 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3542 // vmrs are very slow, e.g. cortex-a8.
3545 if (isFloatingPointZero(Op)) {
3549 return ISD::isNormalLoad(N);
3552 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3553 if (isFloatingPointZero(Op))
3554 return DAG.getConstant(0, MVT::i32);
3556 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3557 return DAG.getLoad(MVT::i32, SDLoc(Op),
3558 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3559 Ld->isVolatile(), Ld->isNonTemporal(),
3560 Ld->isInvariant(), Ld->getAlignment());
3562 llvm_unreachable("Unknown VFP cmp argument!");
3565 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3566 SDValue &RetVal1, SDValue &RetVal2) {
3567 if (isFloatingPointZero(Op)) {
3568 RetVal1 = DAG.getConstant(0, MVT::i32);
3569 RetVal2 = DAG.getConstant(0, MVT::i32);
3573 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3574 SDValue Ptr = Ld->getBasePtr();
3575 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3576 Ld->getChain(), Ptr,
3577 Ld->getPointerInfo(),
3578 Ld->isVolatile(), Ld->isNonTemporal(),
3579 Ld->isInvariant(), Ld->getAlignment());
3581 EVT PtrType = Ptr.getValueType();
3582 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3583 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3584 PtrType, Ptr, DAG.getConstant(4, PtrType));
3585 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3586 Ld->getChain(), NewPtr,
3587 Ld->getPointerInfo().getWithOffset(4),
3588 Ld->isVolatile(), Ld->isNonTemporal(),
3589 Ld->isInvariant(), NewAlign);
3593 llvm_unreachable("Unknown VFP cmp argument!");
3596 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3597 /// f32 and even f64 comparisons to integer ones.
3599 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3600 SDValue Chain = Op.getOperand(0);
3601 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3602 SDValue LHS = Op.getOperand(2);
3603 SDValue RHS = Op.getOperand(3);
3604 SDValue Dest = Op.getOperand(4);
3607 bool LHSSeenZero = false;
3608 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3609 bool RHSSeenZero = false;
3610 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3611 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3612 // If unsafe fp math optimization is enabled and there are no other uses of
3613 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3614 // to an integer comparison.
3615 if (CC == ISD::SETOEQ)
3617 else if (CC == ISD::SETUNE)
3620 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3622 if (LHS.getValueType() == MVT::f32) {
3623 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3624 bitcastf32Toi32(LHS, DAG), Mask);
3625 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3626 bitcastf32Toi32(RHS, DAG), Mask);
3627 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3628 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3629 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3630 Chain, Dest, ARMcc, CCR, Cmp);
3635 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3636 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3637 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3638 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3639 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3640 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3641 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3642 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3643 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3649 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3650 SDValue Chain = Op.getOperand(0);
3651 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3652 SDValue LHS = Op.getOperand(2);
3653 SDValue RHS = Op.getOperand(3);
3654 SDValue Dest = Op.getOperand(4);
3657 if (LHS.getValueType() == MVT::i32) {
3659 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3660 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3661 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3662 Chain, Dest, ARMcc, CCR, Cmp);
3665 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3667 if (getTargetMachine().Options.UnsafeFPMath &&
3668 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3669 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3670 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3671 if (Result.getNode())
3675 ARMCC::CondCodes CondCode, CondCode2;
3676 FPCCToARMCC(CC, CondCode, CondCode2);
3678 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3679 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3680 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3681 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3682 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3683 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3684 if (CondCode2 != ARMCC::AL) {
3685 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3686 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3687 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3692 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3693 SDValue Chain = Op.getOperand(0);
3694 SDValue Table = Op.getOperand(1);
3695 SDValue Index = Op.getOperand(2);
3698 EVT PTy = getPointerTy();
3699 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3700 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3701 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3702 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3703 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3704 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3705 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3706 if (Subtarget->isThumb2()) {
3707 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3708 // which does another jump to the destination. This also makes it easier
3709 // to translate it to TBB / TBH later.
3710 // FIXME: This might not work if the function is extremely large.
3711 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3712 Addr, Op.getOperand(2), JTI, UId);
3714 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3715 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3716 MachinePointerInfo::getJumpTable(),
3717 false, false, false, 0);
3718 Chain = Addr.getValue(1);
3719 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3720 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3722 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3723 MachinePointerInfo::getJumpTable(),
3724 false, false, false, 0);
3725 Chain = Addr.getValue(1);
3726 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3730 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3731 EVT VT = Op.getValueType();
3734 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3735 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3737 return DAG.UnrollVectorOp(Op.getNode());
3740 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3741 "Invalid type for custom lowering!");
3742 if (VT != MVT::v4i16)
3743 return DAG.UnrollVectorOp(Op.getNode());
3745 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3746 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3749 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3750 EVT VT = Op.getValueType();
3752 return LowerVectorFP_TO_INT(Op, DAG);
3757 switch (Op.getOpcode()) {
3758 default: llvm_unreachable("Invalid opcode!");
3759 case ISD::FP_TO_SINT:
3760 Opc = ARMISD::FTOSI;
3762 case ISD::FP_TO_UINT:
3763 Opc = ARMISD::FTOUI;
3766 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3767 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3770 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3771 EVT VT = Op.getValueType();
3774 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3775 if (VT.getVectorElementType() == MVT::f32)
3777 return DAG.UnrollVectorOp(Op.getNode());
3780 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3781 "Invalid type for custom lowering!");
3782 if (VT != MVT::v4f32)
3783 return DAG.UnrollVectorOp(Op.getNode());
3787 switch (Op.getOpcode()) {
3788 default: llvm_unreachable("Invalid opcode!");
3789 case ISD::SINT_TO_FP:
3790 CastOpc = ISD::SIGN_EXTEND;
3791 Opc = ISD::SINT_TO_FP;
3793 case ISD::UINT_TO_FP:
3794 CastOpc = ISD::ZERO_EXTEND;
3795 Opc = ISD::UINT_TO_FP;
3799 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3800 return DAG.getNode(Opc, dl, VT, Op);
3803 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3804 EVT VT = Op.getValueType();
3806 return LowerVectorINT_TO_FP(Op, DAG);
3811 switch (Op.getOpcode()) {
3812 default: llvm_unreachable("Invalid opcode!");
3813 case ISD::SINT_TO_FP:
3814 Opc = ARMISD::SITOF;
3816 case ISD::UINT_TO_FP:
3817 Opc = ARMISD::UITOF;
3821 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3822 return DAG.getNode(Opc, dl, VT, Op);
3825 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3826 // Implement fcopysign with a fabs and a conditional fneg.
3827 SDValue Tmp0 = Op.getOperand(0);
3828 SDValue Tmp1 = Op.getOperand(1);
3830 EVT VT = Op.getValueType();
3831 EVT SrcVT = Tmp1.getValueType();
3832 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3833 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3834 bool UseNEON = !InGPR && Subtarget->hasNEON();
3837 // Use VBSL to copy the sign bit.
3838 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3839 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3840 DAG.getTargetConstant(EncodedVal, MVT::i32));
3841 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3843 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3844 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3845 DAG.getConstant(32, MVT::i32));
3846 else /*if (VT == MVT::f32)*/
3847 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3848 if (SrcVT == MVT::f32) {
3849 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3851 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3852 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3853 DAG.getConstant(32, MVT::i32));
3854 } else if (VT == MVT::f32)
3855 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3856 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3857 DAG.getConstant(32, MVT::i32));
3858 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3859 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3861 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3863 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3864 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3865 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3867 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3868 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3869 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3870 if (VT == MVT::f32) {
3871 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3872 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3873 DAG.getConstant(0, MVT::i32));
3875 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3881 // Bitcast operand 1 to i32.
3882 if (SrcVT == MVT::f64)
3883 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3885 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3887 // Or in the signbit with integer operations.
3888 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3889 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3890 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3891 if (VT == MVT::f32) {
3892 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3893 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3894 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3895 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3898 // f64: Or the high part with signbit and then combine two parts.
3899 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3901 SDValue Lo = Tmp0.getValue(0);
3902 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3903 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3904 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3907 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3908 MachineFunction &MF = DAG.getMachineFunction();
3909 MachineFrameInfo *MFI = MF.getFrameInfo();
3910 MFI->setReturnAddressIsTaken(true);
3912 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3915 EVT VT = Op.getValueType();
3917 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3919 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3920 SDValue Offset = DAG.getConstant(4, MVT::i32);
3921 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3922 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3923 MachinePointerInfo(), false, false, false, 0);
3926 // Return LR, which contains the return address. Mark it an implicit live-in.
3927 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3928 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3931 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3932 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3933 MFI->setFrameAddressIsTaken(true);
3935 EVT VT = Op.getValueType();
3936 SDLoc dl(Op); // FIXME probably not meaningful
3937 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3938 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3939 ? ARM::R7 : ARM::R11;
3940 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3942 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3943 MachinePointerInfo(),
3944 false, false, false, 0);
3948 // FIXME? Maybe this could be a TableGen attribute on some registers and
3949 // this table could be generated automatically from RegInfo.
3950 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3952 unsigned Reg = StringSwitch<unsigned>(RegName)
3953 .Case("sp", ARM::SP)
3957 report_fatal_error("Invalid register name global variable");
3960 /// ExpandBITCAST - If the target supports VFP, this function is called to
3961 /// expand a bit convert where either the source or destination type is i64 to
3962 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3963 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3964 /// vectors), since the legalizer won't know what to do with that.
3965 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3966 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3968 SDValue Op = N->getOperand(0);
3970 // This function is only supposed to be called for i64 types, either as the
3971 // source or destination of the bit convert.
3972 EVT SrcVT = Op.getValueType();
3973 EVT DstVT = N->getValueType(0);
3974 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3975 "ExpandBITCAST called for non-i64 type");
3977 // Turn i64->f64 into VMOVDRR.
3978 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3979 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3980 DAG.getConstant(0, MVT::i32));
3981 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3982 DAG.getConstant(1, MVT::i32));
3983 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3984 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3987 // Turn f64->i64 into VMOVRRD.
3988 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3990 if (TLI.isBigEndian() && SrcVT.isVector() &&
3991 SrcVT.getVectorNumElements() > 1)
3992 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3993 DAG.getVTList(MVT::i32, MVT::i32),
3994 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3996 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3997 DAG.getVTList(MVT::i32, MVT::i32), Op);
3998 // Merge the pieces into a single i64 value.
3999 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4005 /// getZeroVector - Returns a vector of specified type with all zero elements.
4006 /// Zero vectors are used to represent vector negation and in those cases
4007 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4008 /// not support i64 elements, so sometimes the zero vectors will need to be
4009 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4011 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4012 assert(VT.isVector() && "Expected a vector type");
4013 // The canonical modified immediate encoding of a zero vector is....0!
4014 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4015 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4016 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4017 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4020 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4021 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4022 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4023 SelectionDAG &DAG) const {
4024 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4025 EVT VT = Op.getValueType();
4026 unsigned VTBits = VT.getSizeInBits();
4028 SDValue ShOpLo = Op.getOperand(0);
4029 SDValue ShOpHi = Op.getOperand(1);
4030 SDValue ShAmt = Op.getOperand(2);
4032 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4034 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4036 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4037 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4038 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4039 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4040 DAG.getConstant(VTBits, MVT::i32));
4041 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4042 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4043 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4045 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4046 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4048 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4049 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4052 SDValue Ops[2] = { Lo, Hi };
4053 return DAG.getMergeValues(Ops, dl);
4056 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4057 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4058 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4059 SelectionDAG &DAG) const {
4060 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4061 EVT VT = Op.getValueType();
4062 unsigned VTBits = VT.getSizeInBits();
4064 SDValue ShOpLo = Op.getOperand(0);
4065 SDValue ShOpHi = Op.getOperand(1);
4066 SDValue ShAmt = Op.getOperand(2);
4069 assert(Op.getOpcode() == ISD::SHL_PARTS);
4070 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4071 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4072 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4073 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4074 DAG.getConstant(VTBits, MVT::i32));
4075 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4076 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4078 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4079 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4080 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4082 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4083 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4086 SDValue Ops[2] = { Lo, Hi };
4087 return DAG.getMergeValues(Ops, dl);
4090 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4091 SelectionDAG &DAG) const {
4092 // The rounding mode is in bits 23:22 of the FPSCR.
4093 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4094 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4095 // so that the shift + and get folded into a bitfield extract.
4097 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4098 DAG.getConstant(Intrinsic::arm_get_fpscr,
4100 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4101 DAG.getConstant(1U << 22, MVT::i32));
4102 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4103 DAG.getConstant(22, MVT::i32));
4104 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4105 DAG.getConstant(3, MVT::i32));
4108 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4109 const ARMSubtarget *ST) {
4110 EVT VT = N->getValueType(0);
4113 if (!ST->hasV6T2Ops())
4116 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4117 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4120 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4121 /// for each 16-bit element from operand, repeated. The basic idea is to
4122 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4124 /// Trace for v4i16:
4125 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4126 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4127 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4128 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4129 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4130 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4131 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4132 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4133 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4134 EVT VT = N->getValueType(0);
4137 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4138 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4139 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4140 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4141 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4142 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4145 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4146 /// bit-count for each 16-bit element from the operand. We need slightly
4147 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4148 /// 64/128-bit registers.
4150 /// Trace for v4i16:
4151 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4152 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4153 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4154 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4155 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4156 EVT VT = N->getValueType(0);
4159 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4160 if (VT.is64BitVector()) {
4161 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4162 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4163 DAG.getIntPtrConstant(0));
4165 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4166 BitCounts, DAG.getIntPtrConstant(0));
4167 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4171 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4172 /// bit-count for each 32-bit element from the operand. The idea here is
4173 /// to split the vector into 16-bit elements, leverage the 16-bit count
4174 /// routine, and then combine the results.
4176 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4177 /// input = [v0 v1 ] (vi: 32-bit elements)
4178 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4179 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4180 /// vrev: N0 = [k1 k0 k3 k2 ]
4182 /// N1 =+[k1 k0 k3 k2 ]
4184 /// N2 =+[k1 k3 k0 k2 ]
4186 /// Extended =+[k1 k3 k0 k2 ]
4188 /// Extracted=+[k1 k3 ]
4190 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4191 EVT VT = N->getValueType(0);
4194 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4196 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4197 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4198 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4199 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4200 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4202 if (VT.is64BitVector()) {
4203 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4204 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4205 DAG.getIntPtrConstant(0));
4207 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4208 DAG.getIntPtrConstant(0));
4209 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4213 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4214 const ARMSubtarget *ST) {
4215 EVT VT = N->getValueType(0);
4217 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4218 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4219 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4220 "Unexpected type for custom ctpop lowering");
4222 if (VT.getVectorElementType() == MVT::i32)
4223 return lowerCTPOP32BitElements(N, DAG);
4225 return lowerCTPOP16BitElements(N, DAG);
4228 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4229 const ARMSubtarget *ST) {
4230 EVT VT = N->getValueType(0);
4236 // Lower vector shifts on NEON to use VSHL.
4237 assert(ST->hasNEON() && "unexpected vector shift");
4239 // Left shifts translate directly to the vshiftu intrinsic.
4240 if (N->getOpcode() == ISD::SHL)
4241 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4242 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4243 N->getOperand(0), N->getOperand(1));
4245 assert((N->getOpcode() == ISD::SRA ||
4246 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4248 // NEON uses the same intrinsics for both left and right shifts. For
4249 // right shifts, the shift amounts are negative, so negate the vector of
4251 EVT ShiftVT = N->getOperand(1).getValueType();
4252 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4253 getZeroVector(ShiftVT, DAG, dl),
4255 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4256 Intrinsic::arm_neon_vshifts :
4257 Intrinsic::arm_neon_vshiftu);
4258 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4259 DAG.getConstant(vshiftInt, MVT::i32),
4260 N->getOperand(0), NegatedCount);
4263 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4264 const ARMSubtarget *ST) {
4265 EVT VT = N->getValueType(0);
4268 // We can get here for a node like i32 = ISD::SHL i32, i64
4272 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4273 "Unknown shift to lower!");
4275 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4276 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4277 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4280 // If we are in thumb mode, we don't have RRX.
4281 if (ST->isThumb1Only()) return SDValue();
4283 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4284 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4285 DAG.getConstant(0, MVT::i32));
4286 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4287 DAG.getConstant(1, MVT::i32));
4289 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4290 // captures the result into a carry flag.
4291 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4292 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4294 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4295 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4297 // Merge the pieces into a single i64 value.
4298 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4301 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4302 SDValue TmpOp0, TmpOp1;
4303 bool Invert = false;
4307 SDValue Op0 = Op.getOperand(0);
4308 SDValue Op1 = Op.getOperand(1);
4309 SDValue CC = Op.getOperand(2);
4310 EVT VT = Op.getValueType();
4311 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4314 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4315 switch (SetCCOpcode) {
4316 default: llvm_unreachable("Illegal FP comparison");
4318 case ISD::SETNE: Invert = true; // Fallthrough
4320 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4322 case ISD::SETLT: Swap = true; // Fallthrough
4324 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4326 case ISD::SETLE: Swap = true; // Fallthrough
4328 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4329 case ISD::SETUGE: Swap = true; // Fallthrough
4330 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4331 case ISD::SETUGT: Swap = true; // Fallthrough
4332 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4333 case ISD::SETUEQ: Invert = true; // Fallthrough
4335 // Expand this to (OLT | OGT).
4339 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4340 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4342 case ISD::SETUO: Invert = true; // Fallthrough
4344 // Expand this to (OLT | OGE).
4348 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4349 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4353 // Integer comparisons.
4354 switch (SetCCOpcode) {
4355 default: llvm_unreachable("Illegal integer comparison");
4356 case ISD::SETNE: Invert = true;
4357 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4358 case ISD::SETLT: Swap = true;
4359 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4360 case ISD::SETLE: Swap = true;
4361 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4362 case ISD::SETULT: Swap = true;
4363 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4364 case ISD::SETULE: Swap = true;
4365 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4368 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4369 if (Opc == ARMISD::VCEQ) {
4372 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4374 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4377 // Ignore bitconvert.
4378 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4379 AndOp = AndOp.getOperand(0);
4381 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4383 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4384 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4391 std::swap(Op0, Op1);
4393 // If one of the operands is a constant vector zero, attempt to fold the
4394 // comparison to a specialized compare-against-zero form.
4396 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4398 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4399 if (Opc == ARMISD::VCGE)
4400 Opc = ARMISD::VCLEZ;
4401 else if (Opc == ARMISD::VCGT)
4402 Opc = ARMISD::VCLTZ;
4407 if (SingleOp.getNode()) {
4410 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4412 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4414 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4416 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4418 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4420 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4423 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4427 Result = DAG.getNOT(dl, Result, VT);
4432 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4433 /// valid vector constant for a NEON instruction with a "modified immediate"
4434 /// operand (e.g., VMOV). If so, return the encoded value.
4435 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4436 unsigned SplatBitSize, SelectionDAG &DAG,
4437 EVT &VT, bool is128Bits, NEONModImmType type) {
4438 unsigned OpCmode, Imm;
4440 // SplatBitSize is set to the smallest size that splats the vector, so a
4441 // zero vector will always have SplatBitSize == 8. However, NEON modified
4442 // immediate instructions others than VMOV do not support the 8-bit encoding
4443 // of a zero vector, and the default encoding of zero is supposed to be the
4448 switch (SplatBitSize) {
4450 if (type != VMOVModImm)
4452 // Any 1-byte value is OK. Op=0, Cmode=1110.
4453 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4456 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4460 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4461 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4462 if ((SplatBits & ~0xff) == 0) {
4463 // Value = 0x00nn: Op=x, Cmode=100x.
4468 if ((SplatBits & ~0xff00) == 0) {
4469 // Value = 0xnn00: Op=x, Cmode=101x.
4471 Imm = SplatBits >> 8;
4477 // NEON's 32-bit VMOV supports splat values where:
4478 // * only one byte is nonzero, or
4479 // * the least significant byte is 0xff and the second byte is nonzero, or
4480 // * the least significant 2 bytes are 0xff and the third is nonzero.
4481 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4482 if ((SplatBits & ~0xff) == 0) {
4483 // Value = 0x000000nn: Op=x, Cmode=000x.
4488 if ((SplatBits & ~0xff00) == 0) {
4489 // Value = 0x0000nn00: Op=x, Cmode=001x.
4491 Imm = SplatBits >> 8;
4494 if ((SplatBits & ~0xff0000) == 0) {
4495 // Value = 0x00nn0000: Op=x, Cmode=010x.
4497 Imm = SplatBits >> 16;
4500 if ((SplatBits & ~0xff000000) == 0) {
4501 // Value = 0xnn000000: Op=x, Cmode=011x.
4503 Imm = SplatBits >> 24;
4507 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4508 if (type == OtherModImm) return SDValue();
4510 if ((SplatBits & ~0xffff) == 0 &&
4511 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4512 // Value = 0x0000nnff: Op=x, Cmode=1100.
4514 Imm = SplatBits >> 8;
4518 if ((SplatBits & ~0xffffff) == 0 &&
4519 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4520 // Value = 0x00nnffff: Op=x, Cmode=1101.
4522 Imm = SplatBits >> 16;
4526 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4527 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4528 // VMOV.I32. A (very) minor optimization would be to replicate the value
4529 // and fall through here to test for a valid 64-bit splat. But, then the
4530 // caller would also need to check and handle the change in size.
4534 if (type != VMOVModImm)
4536 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4537 uint64_t BitMask = 0xff;
4539 unsigned ImmMask = 1;
4541 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4542 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4545 } else if ((SplatBits & BitMask) != 0) {
4551 // Op=1, Cmode=1110.
4553 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4558 llvm_unreachable("unexpected size for isNEONModifiedImm");
4561 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4562 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4565 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4566 const ARMSubtarget *ST) const {
4570 bool IsDouble = Op.getValueType() == MVT::f64;
4571 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4573 // Try splatting with a VMOV.f32...
4574 APFloat FPVal = CFP->getValueAPF();
4575 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4578 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4579 // We have code in place to select a valid ConstantFP already, no need to
4584 // It's a float and we are trying to use NEON operations where
4585 // possible. Lower it to a splat followed by an extract.
4587 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4588 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4590 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4591 DAG.getConstant(0, MVT::i32));
4594 // The rest of our options are NEON only, make sure that's allowed before
4596 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4600 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4602 // It wouldn't really be worth bothering for doubles except for one very
4603 // important value, which does happen to match: 0.0. So make sure we don't do
4605 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4608 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4609 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4611 if (NewVal != SDValue()) {
4613 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4616 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4618 // It's a float: cast and extract a vector element.
4619 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4621 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4622 DAG.getConstant(0, MVT::i32));
4625 // Finally, try a VMVN.i32
4626 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4628 if (NewVal != SDValue()) {
4630 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4633 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4635 // It's a float: cast and extract a vector element.
4636 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4638 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4639 DAG.getConstant(0, MVT::i32));
4645 // check if an VEXT instruction can handle the shuffle mask when the
4646 // vector sources of the shuffle are the same.
4647 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4648 unsigned NumElts = VT.getVectorNumElements();
4650 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4656 // If this is a VEXT shuffle, the immediate value is the index of the first
4657 // element. The other shuffle indices must be the successive elements after
4659 unsigned ExpectedElt = Imm;
4660 for (unsigned i = 1; i < NumElts; ++i) {
4661 // Increment the expected index. If it wraps around, just follow it
4662 // back to index zero and keep going.
4664 if (ExpectedElt == NumElts)
4667 if (M[i] < 0) continue; // ignore UNDEF indices
4668 if (ExpectedElt != static_cast<unsigned>(M[i]))
4676 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4677 bool &ReverseVEXT, unsigned &Imm) {
4678 unsigned NumElts = VT.getVectorNumElements();
4679 ReverseVEXT = false;
4681 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4687 // If this is a VEXT shuffle, the immediate value is the index of the first
4688 // element. The other shuffle indices must be the successive elements after
4690 unsigned ExpectedElt = Imm;
4691 for (unsigned i = 1; i < NumElts; ++i) {
4692 // Increment the expected index. If it wraps around, it may still be
4693 // a VEXT but the source vectors must be swapped.
4695 if (ExpectedElt == NumElts * 2) {
4700 if (M[i] < 0) continue; // ignore UNDEF indices
4701 if (ExpectedElt != static_cast<unsigned>(M[i]))
4705 // Adjust the index value if the source operands will be swapped.
4712 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4713 /// instruction with the specified blocksize. (The order of the elements
4714 /// within each block of the vector is reversed.)
4715 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4716 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4717 "Only possible block sizes for VREV are: 16, 32, 64");
4719 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4723 unsigned NumElts = VT.getVectorNumElements();
4724 unsigned BlockElts = M[0] + 1;
4725 // If the first shuffle index is UNDEF, be optimistic.
4727 BlockElts = BlockSize / EltSz;
4729 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4732 for (unsigned i = 0; i < NumElts; ++i) {
4733 if (M[i] < 0) continue; // ignore UNDEF indices
4734 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4741 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4742 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4743 // range, then 0 is placed into the resulting vector. So pretty much any mask
4744 // of 8 elements can work here.
4745 return VT == MVT::v8i8 && M.size() == 8;
4748 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4749 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4753 unsigned NumElts = VT.getVectorNumElements();
4754 WhichResult = (M[0] == 0 ? 0 : 1);
4755 for (unsigned i = 0; i < NumElts; i += 2) {
4756 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4757 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4763 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4764 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4765 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4766 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4767 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4771 unsigned NumElts = VT.getVectorNumElements();
4772 WhichResult = (M[0] == 0 ? 0 : 1);
4773 for (unsigned i = 0; i < NumElts; i += 2) {
4774 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4775 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4781 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4782 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4786 unsigned NumElts = VT.getVectorNumElements();
4787 WhichResult = (M[0] == 0 ? 0 : 1);
4788 for (unsigned i = 0; i != NumElts; ++i) {
4789 if (M[i] < 0) continue; // ignore UNDEF indices
4790 if ((unsigned) M[i] != 2 * i + WhichResult)
4794 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4795 if (VT.is64BitVector() && EltSz == 32)
4801 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4802 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4803 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4804 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4805 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4809 unsigned Half = VT.getVectorNumElements() / 2;
4810 WhichResult = (M[0] == 0 ? 0 : 1);
4811 for (unsigned j = 0; j != 2; ++j) {
4812 unsigned Idx = WhichResult;
4813 for (unsigned i = 0; i != Half; ++i) {
4814 int MIdx = M[i + j * Half];
4815 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4821 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4822 if (VT.is64BitVector() && EltSz == 32)
4828 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4829 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4833 unsigned NumElts = VT.getVectorNumElements();
4834 WhichResult = (M[0] == 0 ? 0 : 1);
4835 unsigned Idx = WhichResult * NumElts / 2;
4836 for (unsigned i = 0; i != NumElts; i += 2) {
4837 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4838 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4843 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4844 if (VT.is64BitVector() && EltSz == 32)
4850 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4851 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4852 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4853 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4854 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4858 unsigned NumElts = VT.getVectorNumElements();
4859 WhichResult = (M[0] == 0 ? 0 : 1);
4860 unsigned Idx = WhichResult * NumElts / 2;
4861 for (unsigned i = 0; i != NumElts; i += 2) {
4862 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4863 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4868 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4869 if (VT.is64BitVector() && EltSz == 32)
4875 /// \return true if this is a reverse operation on an vector.
4876 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4877 unsigned NumElts = VT.getVectorNumElements();
4878 // Make sure the mask has the right size.
4879 if (NumElts != M.size())
4882 // Look for <15, ..., 3, -1, 1, 0>.
4883 for (unsigned i = 0; i != NumElts; ++i)
4884 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4890 // If N is an integer constant that can be moved into a register in one
4891 // instruction, return an SDValue of such a constant (will become a MOV
4892 // instruction). Otherwise return null.
4893 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4894 const ARMSubtarget *ST, SDLoc dl) {
4896 if (!isa<ConstantSDNode>(N))
4898 Val = cast<ConstantSDNode>(N)->getZExtValue();
4900 if (ST->isThumb1Only()) {
4901 if (Val <= 255 || ~Val <= 255)
4902 return DAG.getConstant(Val, MVT::i32);
4904 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4905 return DAG.getConstant(Val, MVT::i32);
4910 // If this is a case we can't handle, return null and let the default
4911 // expansion code take care of it.
4912 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4913 const ARMSubtarget *ST) const {
4914 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4916 EVT VT = Op.getValueType();
4918 APInt SplatBits, SplatUndef;
4919 unsigned SplatBitSize;
4921 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4922 if (SplatBitSize <= 64) {
4923 // Check if an immediate VMOV works.
4925 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4926 SplatUndef.getZExtValue(), SplatBitSize,
4927 DAG, VmovVT, VT.is128BitVector(),
4929 if (Val.getNode()) {
4930 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4931 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4934 // Try an immediate VMVN.
4935 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4936 Val = isNEONModifiedImm(NegatedImm,
4937 SplatUndef.getZExtValue(), SplatBitSize,
4938 DAG, VmovVT, VT.is128BitVector(),
4940 if (Val.getNode()) {
4941 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4942 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4945 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4946 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4947 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4949 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4950 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4956 // Scan through the operands to see if only one value is used.
4958 // As an optimisation, even if more than one value is used it may be more
4959 // profitable to splat with one value then change some lanes.
4961 // Heuristically we decide to do this if the vector has a "dominant" value,
4962 // defined as splatted to more than half of the lanes.
4963 unsigned NumElts = VT.getVectorNumElements();
4964 bool isOnlyLowElement = true;
4965 bool usesOnlyOneValue = true;
4966 bool hasDominantValue = false;
4967 bool isConstant = true;
4969 // Map of the number of times a particular SDValue appears in the
4971 DenseMap<SDValue, unsigned> ValueCounts;
4973 for (unsigned i = 0; i < NumElts; ++i) {
4974 SDValue V = Op.getOperand(i);
4975 if (V.getOpcode() == ISD::UNDEF)
4978 isOnlyLowElement = false;
4979 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4982 ValueCounts.insert(std::make_pair(V, 0));
4983 unsigned &Count = ValueCounts[V];
4985 // Is this value dominant? (takes up more than half of the lanes)
4986 if (++Count > (NumElts / 2)) {
4987 hasDominantValue = true;
4991 if (ValueCounts.size() != 1)
4992 usesOnlyOneValue = false;
4993 if (!Value.getNode() && ValueCounts.size() > 0)
4994 Value = ValueCounts.begin()->first;
4996 if (ValueCounts.size() == 0)
4997 return DAG.getUNDEF(VT);
4999 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5000 // Keep going if we are hitting this case.
5001 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5002 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5004 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5006 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5007 // i32 and try again.
5008 if (hasDominantValue && EltSize <= 32) {
5012 // If we are VDUPing a value that comes directly from a vector, that will
5013 // cause an unnecessary move to and from a GPR, where instead we could
5014 // just use VDUPLANE. We can only do this if the lane being extracted
5015 // is at a constant index, as the VDUP from lane instructions only have
5016 // constant-index forms.
5017 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5018 isa<ConstantSDNode>(Value->getOperand(1))) {
5019 // We need to create a new undef vector to use for the VDUPLANE if the
5020 // size of the vector from which we get the value is different than the
5021 // size of the vector that we need to create. We will insert the element
5022 // such that the register coalescer will remove unnecessary copies.
5023 if (VT != Value->getOperand(0).getValueType()) {
5024 ConstantSDNode *constIndex;
5025 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5026 assert(constIndex && "The index is not a constant!");
5027 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5028 VT.getVectorNumElements();
5029 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5030 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5031 Value, DAG.getConstant(index, MVT::i32)),
5032 DAG.getConstant(index, MVT::i32));
5034 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5035 Value->getOperand(0), Value->getOperand(1));
5037 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5039 if (!usesOnlyOneValue) {
5040 // The dominant value was splatted as 'N', but we now have to insert
5041 // all differing elements.
5042 for (unsigned I = 0; I < NumElts; ++I) {
5043 if (Op.getOperand(I) == Value)
5045 SmallVector<SDValue, 3> Ops;
5047 Ops.push_back(Op.getOperand(I));
5048 Ops.push_back(DAG.getConstant(I, MVT::i32));
5049 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5054 if (VT.getVectorElementType().isFloatingPoint()) {
5055 SmallVector<SDValue, 8> Ops;
5056 for (unsigned i = 0; i < NumElts; ++i)
5057 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5059 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5060 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5061 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5063 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5065 if (usesOnlyOneValue) {
5066 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5067 if (isConstant && Val.getNode())
5068 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5072 // If all elements are constants and the case above didn't get hit, fall back
5073 // to the default expansion, which will generate a load from the constant
5078 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5080 SDValue shuffle = ReconstructShuffle(Op, DAG);
5081 if (shuffle != SDValue())
5085 // Vectors with 32- or 64-bit elements can be built by directly assigning
5086 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5087 // will be legalized.
5088 if (EltSize >= 32) {
5089 // Do the expansion with floating-point types, since that is what the VFP
5090 // registers are defined to use, and since i64 is not legal.
5091 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5092 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5093 SmallVector<SDValue, 8> Ops;
5094 for (unsigned i = 0; i < NumElts; ++i)
5095 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5096 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5097 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5100 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5101 // know the default expansion would otherwise fall back on something even
5102 // worse. For a vector with one or two non-undef values, that's
5103 // scalar_to_vector for the elements followed by a shuffle (provided the
5104 // shuffle is valid for the target) and materialization element by element
5105 // on the stack followed by a load for everything else.
5106 if (!isConstant && !usesOnlyOneValue) {
5107 SDValue Vec = DAG.getUNDEF(VT);
5108 for (unsigned i = 0 ; i < NumElts; ++i) {
5109 SDValue V = Op.getOperand(i);
5110 if (V.getOpcode() == ISD::UNDEF)
5112 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5113 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5121 // Gather data to see if the operation can be modelled as a
5122 // shuffle in combination with VEXTs.
5123 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5124 SelectionDAG &DAG) const {
5126 EVT VT = Op.getValueType();
5127 unsigned NumElts = VT.getVectorNumElements();
5129 SmallVector<SDValue, 2> SourceVecs;
5130 SmallVector<unsigned, 2> MinElts;
5131 SmallVector<unsigned, 2> MaxElts;
5133 for (unsigned i = 0; i < NumElts; ++i) {
5134 SDValue V = Op.getOperand(i);
5135 if (V.getOpcode() == ISD::UNDEF)
5137 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5138 // A shuffle can only come from building a vector from various
5139 // elements of other vectors.
5141 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5142 VT.getVectorElementType()) {
5143 // This code doesn't know how to handle shuffles where the vector
5144 // element types do not match (this happens because type legalization
5145 // promotes the return type of EXTRACT_VECTOR_ELT).
5146 // FIXME: It might be appropriate to extend this code to handle
5147 // mismatched types.
5151 // Record this extraction against the appropriate vector if possible...
5152 SDValue SourceVec = V.getOperand(0);
5153 // If the element number isn't a constant, we can't effectively
5154 // analyze what's going on.
5155 if (!isa<ConstantSDNode>(V.getOperand(1)))
5157 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5158 bool FoundSource = false;
5159 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5160 if (SourceVecs[j] == SourceVec) {
5161 if (MinElts[j] > EltNo)
5163 if (MaxElts[j] < EltNo)
5170 // Or record a new source if not...
5172 SourceVecs.push_back(SourceVec);
5173 MinElts.push_back(EltNo);
5174 MaxElts.push_back(EltNo);
5178 // Currently only do something sane when at most two source vectors
5180 if (SourceVecs.size() > 2)
5183 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5184 int VEXTOffsets[2] = {0, 0};
5186 // This loop extracts the usage patterns of the source vectors
5187 // and prepares appropriate SDValues for a shuffle if possible.
5188 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5189 if (SourceVecs[i].getValueType() == VT) {
5190 // No VEXT necessary
5191 ShuffleSrcs[i] = SourceVecs[i];
5194 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5195 // It probably isn't worth padding out a smaller vector just to
5196 // break it down again in a shuffle.
5200 // Since only 64-bit and 128-bit vectors are legal on ARM and
5201 // we've eliminated the other cases...
5202 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5203 "unexpected vector sizes in ReconstructShuffle");
5205 if (MaxElts[i] - MinElts[i] >= NumElts) {
5206 // Span too large for a VEXT to cope
5210 if (MinElts[i] >= NumElts) {
5211 // The extraction can just take the second half
5212 VEXTOffsets[i] = NumElts;
5213 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5215 DAG.getIntPtrConstant(NumElts));
5216 } else if (MaxElts[i] < NumElts) {
5217 // The extraction can just take the first half
5219 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5221 DAG.getIntPtrConstant(0));
5223 // An actual VEXT is needed
5224 VEXTOffsets[i] = MinElts[i];
5225 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5227 DAG.getIntPtrConstant(0));
5228 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5230 DAG.getIntPtrConstant(NumElts));
5231 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5232 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5236 SmallVector<int, 8> Mask;
5238 for (unsigned i = 0; i < NumElts; ++i) {
5239 SDValue Entry = Op.getOperand(i);
5240 if (Entry.getOpcode() == ISD::UNDEF) {
5245 SDValue ExtractVec = Entry.getOperand(0);
5246 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5247 .getOperand(1))->getSExtValue();
5248 if (ExtractVec == SourceVecs[0]) {
5249 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5251 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5255 // Final check before we try to produce nonsense...
5256 if (isShuffleMaskLegal(Mask, VT))
5257 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5263 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5264 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5265 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5266 /// are assumed to be legal.
5268 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5270 if (VT.getVectorNumElements() == 4 &&
5271 (VT.is128BitVector() || VT.is64BitVector())) {
5272 unsigned PFIndexes[4];
5273 for (unsigned i = 0; i != 4; ++i) {
5277 PFIndexes[i] = M[i];
5280 // Compute the index in the perfect shuffle table.
5281 unsigned PFTableIndex =
5282 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5283 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5284 unsigned Cost = (PFEntry >> 30);
5291 unsigned Imm, WhichResult;
5293 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5294 return (EltSize >= 32 ||
5295 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5296 isVREVMask(M, VT, 64) ||
5297 isVREVMask(M, VT, 32) ||
5298 isVREVMask(M, VT, 16) ||
5299 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5300 isVTBLMask(M, VT) ||
5301 isVTRNMask(M, VT, WhichResult) ||
5302 isVUZPMask(M, VT, WhichResult) ||
5303 isVZIPMask(M, VT, WhichResult) ||
5304 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5305 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5306 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5307 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5310 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5311 /// the specified operations to build the shuffle.
5312 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5313 SDValue RHS, SelectionDAG &DAG,
5315 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5316 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5317 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5320 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5329 OP_VUZPL, // VUZP, left result
5330 OP_VUZPR, // VUZP, right result
5331 OP_VZIPL, // VZIP, left result
5332 OP_VZIPR, // VZIP, right result
5333 OP_VTRNL, // VTRN, left result
5334 OP_VTRNR // VTRN, right result
5337 if (OpNum == OP_COPY) {
5338 if (LHSID == (1*9+2)*9+3) return LHS;
5339 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5343 SDValue OpLHS, OpRHS;
5344 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5345 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5346 EVT VT = OpLHS.getValueType();
5349 default: llvm_unreachable("Unknown shuffle opcode!");
5351 // VREV divides the vector in half and swaps within the half.
5352 if (VT.getVectorElementType() == MVT::i32 ||
5353 VT.getVectorElementType() == MVT::f32)
5354 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5355 // vrev <4 x i16> -> VREV32
5356 if (VT.getVectorElementType() == MVT::i16)
5357 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5358 // vrev <4 x i8> -> VREV16
5359 assert(VT.getVectorElementType() == MVT::i8);
5360 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5365 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5366 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5370 return DAG.getNode(ARMISD::VEXT, dl, VT,
5372 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5375 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5376 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5379 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5380 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5383 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5384 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5388 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5389 ArrayRef<int> ShuffleMask,
5390 SelectionDAG &DAG) {
5391 // Check to see if we can use the VTBL instruction.
5392 SDValue V1 = Op.getOperand(0);
5393 SDValue V2 = Op.getOperand(1);
5396 SmallVector<SDValue, 8> VTBLMask;
5397 for (ArrayRef<int>::iterator
5398 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5399 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5401 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5402 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5403 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5405 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5406 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5409 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5410 SelectionDAG &DAG) {
5412 SDValue OpLHS = Op.getOperand(0);
5413 EVT VT = OpLHS.getValueType();
5415 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5416 "Expect an v8i16/v16i8 type");
5417 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5418 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5419 // extract the first 8 bytes into the top double word and the last 8 bytes
5420 // into the bottom double word. The v8i16 case is similar.
5421 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5422 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5423 DAG.getConstant(ExtractNum, MVT::i32));
5426 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5427 SDValue V1 = Op.getOperand(0);
5428 SDValue V2 = Op.getOperand(1);
5430 EVT VT = Op.getValueType();
5431 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5433 // Convert shuffles that are directly supported on NEON to target-specific
5434 // DAG nodes, instead of keeping them as shuffles and matching them again
5435 // during code selection. This is more efficient and avoids the possibility
5436 // of inconsistencies between legalization and selection.
5437 // FIXME: floating-point vectors should be canonicalized to integer vectors
5438 // of the same time so that they get CSEd properly.
5439 ArrayRef<int> ShuffleMask = SVN->getMask();
5441 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5442 if (EltSize <= 32) {
5443 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5444 int Lane = SVN->getSplatIndex();
5445 // If this is undef splat, generate it via "just" vdup, if possible.
5446 if (Lane == -1) Lane = 0;
5448 // Test if V1 is a SCALAR_TO_VECTOR.
5449 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5450 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5452 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5453 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5455 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5456 !isa<ConstantSDNode>(V1.getOperand(0))) {
5457 bool IsScalarToVector = true;
5458 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5459 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5460 IsScalarToVector = false;
5463 if (IsScalarToVector)
5464 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5466 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5467 DAG.getConstant(Lane, MVT::i32));
5472 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5475 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5476 DAG.getConstant(Imm, MVT::i32));
5479 if (isVREVMask(ShuffleMask, VT, 64))
5480 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5481 if (isVREVMask(ShuffleMask, VT, 32))
5482 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5483 if (isVREVMask(ShuffleMask, VT, 16))
5484 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5486 if (V2->getOpcode() == ISD::UNDEF &&
5487 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5488 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5489 DAG.getConstant(Imm, MVT::i32));
5492 // Check for Neon shuffles that modify both input vectors in place.
5493 // If both results are used, i.e., if there are two shuffles with the same
5494 // source operands and with masks corresponding to both results of one of
5495 // these operations, DAG memoization will ensure that a single node is
5496 // used for both shuffles.
5497 unsigned WhichResult;
5498 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5499 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5500 V1, V2).getValue(WhichResult);
5501 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5502 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5503 V1, V2).getValue(WhichResult);
5504 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5505 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5506 V1, V2).getValue(WhichResult);
5508 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5509 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5510 V1, V1).getValue(WhichResult);
5511 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5512 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5513 V1, V1).getValue(WhichResult);
5514 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5515 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5516 V1, V1).getValue(WhichResult);
5519 // If the shuffle is not directly supported and it has 4 elements, use
5520 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5521 unsigned NumElts = VT.getVectorNumElements();
5523 unsigned PFIndexes[4];
5524 for (unsigned i = 0; i != 4; ++i) {
5525 if (ShuffleMask[i] < 0)
5528 PFIndexes[i] = ShuffleMask[i];
5531 // Compute the index in the perfect shuffle table.
5532 unsigned PFTableIndex =
5533 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5534 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5535 unsigned Cost = (PFEntry >> 30);
5538 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5541 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5542 if (EltSize >= 32) {
5543 // Do the expansion with floating-point types, since that is what the VFP
5544 // registers are defined to use, and since i64 is not legal.
5545 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5546 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5547 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5548 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5549 SmallVector<SDValue, 8> Ops;
5550 for (unsigned i = 0; i < NumElts; ++i) {
5551 if (ShuffleMask[i] < 0)
5552 Ops.push_back(DAG.getUNDEF(EltVT));
5554 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5555 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5556 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5559 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5560 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5563 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5564 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5566 if (VT == MVT::v8i8) {
5567 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5568 if (NewOp.getNode())
5575 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5576 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5577 SDValue Lane = Op.getOperand(2);
5578 if (!isa<ConstantSDNode>(Lane))
5584 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5585 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5586 SDValue Lane = Op.getOperand(1);
5587 if (!isa<ConstantSDNode>(Lane))
5590 SDValue Vec = Op.getOperand(0);
5591 if (Op.getValueType() == MVT::i32 &&
5592 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5594 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5600 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5601 // The only time a CONCAT_VECTORS operation can have legal types is when
5602 // two 64-bit vectors are concatenated to a 128-bit vector.
5603 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5604 "unexpected CONCAT_VECTORS");
5606 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5607 SDValue Op0 = Op.getOperand(0);
5608 SDValue Op1 = Op.getOperand(1);
5609 if (Op0.getOpcode() != ISD::UNDEF)
5610 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5611 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5612 DAG.getIntPtrConstant(0));
5613 if (Op1.getOpcode() != ISD::UNDEF)
5614 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5615 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5616 DAG.getIntPtrConstant(1));
5617 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5620 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5621 /// element has been zero/sign-extended, depending on the isSigned parameter,
5622 /// from an integer type half its size.
5623 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5625 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5626 EVT VT = N->getValueType(0);
5627 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5628 SDNode *BVN = N->getOperand(0).getNode();
5629 if (BVN->getValueType(0) != MVT::v4i32 ||
5630 BVN->getOpcode() != ISD::BUILD_VECTOR)
5632 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5633 unsigned HiElt = 1 - LoElt;
5634 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5635 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5636 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5637 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5638 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5641 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5642 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5645 if (Hi0->isNullValue() && Hi1->isNullValue())
5651 if (N->getOpcode() != ISD::BUILD_VECTOR)
5654 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5655 SDNode *Elt = N->getOperand(i).getNode();
5656 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5657 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5658 unsigned HalfSize = EltSize / 2;
5660 if (!isIntN(HalfSize, C->getSExtValue()))
5663 if (!isUIntN(HalfSize, C->getZExtValue()))
5674 /// isSignExtended - Check if a node is a vector value that is sign-extended
5675 /// or a constant BUILD_VECTOR with sign-extended elements.
5676 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5677 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5679 if (isExtendedBUILD_VECTOR(N, DAG, true))
5684 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5685 /// or a constant BUILD_VECTOR with zero-extended elements.
5686 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5687 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5689 if (isExtendedBUILD_VECTOR(N, DAG, false))
5694 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5695 if (OrigVT.getSizeInBits() >= 64)
5698 assert(OrigVT.isSimple() && "Expecting a simple value type");
5700 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5701 switch (OrigSimpleTy) {
5702 default: llvm_unreachable("Unexpected Vector Type");
5711 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5712 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5713 /// We insert the required extension here to get the vector to fill a D register.
5714 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5717 unsigned ExtOpcode) {
5718 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5719 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5720 // 64-bits we need to insert a new extension so that it will be 64-bits.
5721 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5722 if (OrigTy.getSizeInBits() >= 64)
5725 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5726 EVT NewVT = getExtensionTo64Bits(OrigTy);
5728 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5731 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5732 /// does not do any sign/zero extension. If the original vector is less
5733 /// than 64 bits, an appropriate extension will be added after the load to
5734 /// reach a total size of 64 bits. We have to add the extension separately
5735 /// because ARM does not have a sign/zero extending load for vectors.
5736 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5737 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5739 // The load already has the right type.
5740 if (ExtendedTy == LD->getMemoryVT())
5741 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5742 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5743 LD->isNonTemporal(), LD->isInvariant(),
5744 LD->getAlignment());
5746 // We need to create a zextload/sextload. We cannot just create a load
5747 // followed by a zext/zext node because LowerMUL is also run during normal
5748 // operation legalization where we can't create illegal types.
5749 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5750 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5751 LD->getMemoryVT(), LD->isVolatile(),
5752 LD->isNonTemporal(), LD->getAlignment());
5755 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5756 /// extending load, or BUILD_VECTOR with extended elements, return the
5757 /// unextended value. The unextended vector should be 64 bits so that it can
5758 /// be used as an operand to a VMULL instruction. If the original vector size
5759 /// before extension is less than 64 bits we add a an extension to resize
5760 /// the vector to 64 bits.
5761 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5762 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5763 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5764 N->getOperand(0)->getValueType(0),
5768 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5769 return SkipLoadExtensionForVMULL(LD, DAG);
5771 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5772 // have been legalized as a BITCAST from v4i32.
5773 if (N->getOpcode() == ISD::BITCAST) {
5774 SDNode *BVN = N->getOperand(0).getNode();
5775 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5776 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5777 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5778 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5779 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5781 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5782 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5783 EVT VT = N->getValueType(0);
5784 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5785 unsigned NumElts = VT.getVectorNumElements();
5786 MVT TruncVT = MVT::getIntegerVT(EltSize);
5787 SmallVector<SDValue, 8> Ops;
5788 for (unsigned i = 0; i != NumElts; ++i) {
5789 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5790 const APInt &CInt = C->getAPIntValue();
5791 // Element types smaller than 32 bits are not legal, so use i32 elements.
5792 // The values are implicitly truncated so sext vs. zext doesn't matter.
5793 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5795 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5796 MVT::getVectorVT(TruncVT, NumElts), Ops);
5799 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5800 unsigned Opcode = N->getOpcode();
5801 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5802 SDNode *N0 = N->getOperand(0).getNode();
5803 SDNode *N1 = N->getOperand(1).getNode();
5804 return N0->hasOneUse() && N1->hasOneUse() &&
5805 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5810 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5811 unsigned Opcode = N->getOpcode();
5812 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5813 SDNode *N0 = N->getOperand(0).getNode();
5814 SDNode *N1 = N->getOperand(1).getNode();
5815 return N0->hasOneUse() && N1->hasOneUse() &&
5816 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5821 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5822 // Multiplications are only custom-lowered for 128-bit vectors so that
5823 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5824 EVT VT = Op.getValueType();
5825 assert(VT.is128BitVector() && VT.isInteger() &&
5826 "unexpected type for custom-lowering ISD::MUL");
5827 SDNode *N0 = Op.getOperand(0).getNode();
5828 SDNode *N1 = Op.getOperand(1).getNode();
5829 unsigned NewOpc = 0;
5831 bool isN0SExt = isSignExtended(N0, DAG);
5832 bool isN1SExt = isSignExtended(N1, DAG);
5833 if (isN0SExt && isN1SExt)
5834 NewOpc = ARMISD::VMULLs;
5836 bool isN0ZExt = isZeroExtended(N0, DAG);
5837 bool isN1ZExt = isZeroExtended(N1, DAG);
5838 if (isN0ZExt && isN1ZExt)
5839 NewOpc = ARMISD::VMULLu;
5840 else if (isN1SExt || isN1ZExt) {
5841 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5842 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5843 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5844 NewOpc = ARMISD::VMULLs;
5846 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5847 NewOpc = ARMISD::VMULLu;
5849 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5851 NewOpc = ARMISD::VMULLu;
5857 if (VT == MVT::v2i64)
5858 // Fall through to expand this. It is not legal.
5861 // Other vector multiplications are legal.
5866 // Legalize to a VMULL instruction.
5869 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5871 Op0 = SkipExtensionForVMULL(N0, DAG);
5872 assert(Op0.getValueType().is64BitVector() &&
5873 Op1.getValueType().is64BitVector() &&
5874 "unexpected types for extended operands to VMULL");
5875 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5878 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5879 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5886 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5887 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5888 EVT Op1VT = Op1.getValueType();
5889 return DAG.getNode(N0->getOpcode(), DL, VT,
5890 DAG.getNode(NewOpc, DL, VT,
5891 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5892 DAG.getNode(NewOpc, DL, VT,
5893 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5897 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5899 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5900 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5901 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5902 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5903 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5904 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5905 // Get reciprocal estimate.
5906 // float4 recip = vrecpeq_f32(yf);
5907 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5908 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5909 // Because char has a smaller range than uchar, we can actually get away
5910 // without any newton steps. This requires that we use a weird bias
5911 // of 0xb000, however (again, this has been exhaustively tested).
5912 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5913 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5914 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5915 Y = DAG.getConstant(0xb000, MVT::i32);
5916 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5917 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5918 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5919 // Convert back to short.
5920 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5921 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5926 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5928 // Convert to float.
5929 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5930 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5931 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5932 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5933 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5934 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5936 // Use reciprocal estimate and one refinement step.
5937 // float4 recip = vrecpeq_f32(yf);
5938 // recip *= vrecpsq_f32(yf, recip);
5939 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5940 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5941 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5942 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5944 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5945 // Because short has a smaller range than ushort, we can actually get away
5946 // with only a single newton step. This requires that we use a weird bias
5947 // of 89, however (again, this has been exhaustively tested).
5948 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5949 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5950 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5951 N1 = DAG.getConstant(0x89, MVT::i32);
5952 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5953 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5954 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5955 // Convert back to integer and return.
5956 // return vmovn_s32(vcvt_s32_f32(result));
5957 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5958 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5962 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5963 EVT VT = Op.getValueType();
5964 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5965 "unexpected type for custom-lowering ISD::SDIV");
5968 SDValue N0 = Op.getOperand(0);
5969 SDValue N1 = Op.getOperand(1);
5972 if (VT == MVT::v8i8) {
5973 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5974 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5976 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5977 DAG.getIntPtrConstant(4));
5978 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5979 DAG.getIntPtrConstant(4));
5980 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5981 DAG.getIntPtrConstant(0));
5982 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5983 DAG.getIntPtrConstant(0));
5985 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5986 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5988 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5989 N0 = LowerCONCAT_VECTORS(N0, DAG);
5991 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5994 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5997 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5998 EVT VT = Op.getValueType();
5999 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6000 "unexpected type for custom-lowering ISD::UDIV");
6003 SDValue N0 = Op.getOperand(0);
6004 SDValue N1 = Op.getOperand(1);
6007 if (VT == MVT::v8i8) {
6008 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6009 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6011 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6012 DAG.getIntPtrConstant(4));
6013 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6014 DAG.getIntPtrConstant(4));
6015 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6016 DAG.getIntPtrConstant(0));
6017 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6018 DAG.getIntPtrConstant(0));
6020 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6021 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6023 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6024 N0 = LowerCONCAT_VECTORS(N0, DAG);
6026 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6027 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6032 // v4i16 sdiv ... Convert to float.
6033 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6034 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6035 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6036 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6037 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6038 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6040 // Use reciprocal estimate and two refinement steps.
6041 // float4 recip = vrecpeq_f32(yf);
6042 // recip *= vrecpsq_f32(yf, recip);
6043 // recip *= vrecpsq_f32(yf, recip);
6044 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6045 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6046 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6047 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6049 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6050 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6051 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6053 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6054 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6055 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6056 // and that it will never cause us to return an answer too large).
6057 // float4 result = as_float4(as_int4(xf*recip) + 2);
6058 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6059 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6060 N1 = DAG.getConstant(2, MVT::i32);
6061 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6062 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6063 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6064 // Convert back to integer and return.
6065 // return vmovn_u32(vcvt_s32_f32(result));
6066 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6067 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6071 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6072 EVT VT = Op.getNode()->getValueType(0);
6073 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6076 bool ExtraOp = false;
6077 switch (Op.getOpcode()) {
6078 default: llvm_unreachable("Invalid code");
6079 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6080 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6081 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6082 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6086 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6088 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6089 Op.getOperand(1), Op.getOperand(2));
6092 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6093 assert(Subtarget->isTargetDarwin());
6095 // For iOS, we want to call an alternative entry point: __sincos_stret,
6096 // return values are passed via sret.
6098 SDValue Arg = Op.getOperand(0);
6099 EVT ArgVT = Arg.getValueType();
6100 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6102 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6103 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6105 // Pair of floats / doubles used to pass the result.
6106 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6108 // Create stack object for sret.
6109 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6110 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6111 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6112 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6118 Entry.Ty = RetTy->getPointerTo();
6119 Entry.isSExt = false;
6120 Entry.isZExt = false;
6121 Entry.isSRet = true;
6122 Args.push_back(Entry);
6126 Entry.isSExt = false;
6127 Entry.isZExt = false;
6128 Args.push_back(Entry);
6130 const char *LibcallName = (ArgVT == MVT::f64)
6131 ? "__sincos_stret" : "__sincosf_stret";
6132 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6135 CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
6136 false, false, false, false, 0,
6137 CallingConv::C, /*isTaillCall=*/false,
6138 /*doesNotRet=*/false, /*isReturnValueUsed*/false,
6139 Callee, Args, DAG, dl);
6140 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6142 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6143 MachinePointerInfo(), false, false, false, 0);
6145 // Address of cos field.
6146 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6147 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6148 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6149 MachinePointerInfo(), false, false, false, 0);
6151 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6152 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6153 LoadSin.getValue(0), LoadCos.getValue(0));
6156 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6157 // Monotonic load/store is legal for all targets
6158 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6161 // Acquire/Release load/store is not legal for targets without a
6162 // dmb or equivalent available.
6166 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6167 SmallVectorImpl<SDValue> &Results,
6169 const ARMSubtarget *Subtarget) {
6171 SDValue Cycles32, OutChain;
6173 if (Subtarget->hasPerfMon()) {
6174 // Under Power Management extensions, the cycle-count is:
6175 // mrc p15, #0, <Rt>, c9, c13, #0
6176 SDValue Ops[] = { N->getOperand(0), // Chain
6177 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6178 DAG.getConstant(15, MVT::i32),
6179 DAG.getConstant(0, MVT::i32),
6180 DAG.getConstant(9, MVT::i32),
6181 DAG.getConstant(13, MVT::i32),
6182 DAG.getConstant(0, MVT::i32)
6185 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6186 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6187 OutChain = Cycles32.getValue(1);
6189 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6190 // there are older ARM CPUs that have implementation-specific ways of
6191 // obtaining this information (FIXME!).
6192 Cycles32 = DAG.getConstant(0, MVT::i32);
6193 OutChain = DAG.getEntryNode();
6197 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6198 Cycles32, DAG.getConstant(0, MVT::i32));
6199 Results.push_back(Cycles64);
6200 Results.push_back(OutChain);
6203 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6204 switch (Op.getOpcode()) {
6205 default: llvm_unreachable("Don't know how to custom lower this!");
6206 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6207 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6208 case ISD::GlobalAddress:
6209 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6210 default: llvm_unreachable("unknown object format");
6212 return LowerGlobalAddressWindows(Op, DAG);
6214 return LowerGlobalAddressELF(Op, DAG);
6216 return LowerGlobalAddressDarwin(Op, DAG);
6218 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6219 case ISD::SELECT: return LowerSELECT(Op, DAG);
6220 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6221 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6222 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6223 case ISD::VASTART: return LowerVASTART(Op, DAG);
6224 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6225 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6226 case ISD::SINT_TO_FP:
6227 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6228 case ISD::FP_TO_SINT:
6229 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6230 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6231 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6232 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6233 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6234 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6235 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6236 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6238 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6241 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6242 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6243 case ISD::SRL_PARTS:
6244 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6245 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6246 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6247 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6248 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6249 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6250 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6251 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6252 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6253 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6254 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6255 case ISD::MUL: return LowerMUL(Op, DAG);
6256 case ISD::SDIV: return LowerSDIV(Op, DAG);
6257 case ISD::UDIV: return LowerUDIV(Op, DAG);
6261 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6266 return LowerXALUO(Op, DAG);
6267 case ISD::ATOMIC_LOAD:
6268 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6269 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6271 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6275 /// ReplaceNodeResults - Replace the results of node with an illegal result
6276 /// type with new values built out of custom code.
6277 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6278 SmallVectorImpl<SDValue>&Results,
6279 SelectionDAG &DAG) const {
6281 switch (N->getOpcode()) {
6283 llvm_unreachable("Don't know how to custom expand this!");
6285 Res = ExpandBITCAST(N, DAG);
6289 Res = Expand64BitShift(N, DAG, Subtarget);
6291 case ISD::READCYCLECOUNTER:
6292 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6296 Results.push_back(Res);
6299 //===----------------------------------------------------------------------===//
6300 // ARM Scheduler Hooks
6301 //===----------------------------------------------------------------------===//
6303 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6304 /// registers the function context.
6305 void ARMTargetLowering::
6306 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6307 MachineBasicBlock *DispatchBB, int FI) const {
6308 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6309 DebugLoc dl = MI->getDebugLoc();
6310 MachineFunction *MF = MBB->getParent();
6311 MachineRegisterInfo *MRI = &MF->getRegInfo();
6312 MachineConstantPool *MCP = MF->getConstantPool();
6313 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6314 const Function *F = MF->getFunction();
6316 bool isThumb = Subtarget->isThumb();
6317 bool isThumb2 = Subtarget->isThumb2();
6319 unsigned PCLabelId = AFI->createPICLabelUId();
6320 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6321 ARMConstantPoolValue *CPV =
6322 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6323 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6325 const TargetRegisterClass *TRC = isThumb ?
6326 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6327 (const TargetRegisterClass*)&ARM::GPRRegClass;
6329 // Grab constant pool and fixed stack memory operands.
6330 MachineMemOperand *CPMMO =
6331 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6332 MachineMemOperand::MOLoad, 4, 4);
6334 MachineMemOperand *FIMMOSt =
6335 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6336 MachineMemOperand::MOStore, 4, 4);
6338 // Load the address of the dispatch MBB into the jump buffer.
6340 // Incoming value: jbuf
6341 // ldr.n r5, LCPI1_1
6344 // str r5, [$jbuf, #+4] ; &jbuf[1]
6345 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6346 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6347 .addConstantPoolIndex(CPI)
6348 .addMemOperand(CPMMO));
6349 // Set the low bit because of thumb mode.
6350 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6352 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6353 .addReg(NewVReg1, RegState::Kill)
6355 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6356 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6357 .addReg(NewVReg2, RegState::Kill)
6359 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6360 .addReg(NewVReg3, RegState::Kill)
6362 .addImm(36) // &jbuf[1] :: pc
6363 .addMemOperand(FIMMOSt));
6364 } else if (isThumb) {
6365 // Incoming value: jbuf
6366 // ldr.n r1, LCPI1_4
6370 // add r2, $jbuf, #+4 ; &jbuf[1]
6372 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6373 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6374 .addConstantPoolIndex(CPI)
6375 .addMemOperand(CPMMO));
6376 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6377 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6378 .addReg(NewVReg1, RegState::Kill)
6380 // Set the low bit because of thumb mode.
6381 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6382 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6383 .addReg(ARM::CPSR, RegState::Define)
6385 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6386 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6387 .addReg(ARM::CPSR, RegState::Define)
6388 .addReg(NewVReg2, RegState::Kill)
6389 .addReg(NewVReg3, RegState::Kill));
6390 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6391 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6393 .addImm(36)); // &jbuf[1] :: pc
6394 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6395 .addReg(NewVReg4, RegState::Kill)
6396 .addReg(NewVReg5, RegState::Kill)
6398 .addMemOperand(FIMMOSt));
6400 // Incoming value: jbuf
6403 // str r1, [$jbuf, #+4] ; &jbuf[1]
6404 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6405 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6406 .addConstantPoolIndex(CPI)
6408 .addMemOperand(CPMMO));
6409 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6410 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6411 .addReg(NewVReg1, RegState::Kill)
6412 .addImm(PCLabelId));
6413 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6414 .addReg(NewVReg2, RegState::Kill)
6416 .addImm(36) // &jbuf[1] :: pc
6417 .addMemOperand(FIMMOSt));
6421 MachineBasicBlock *ARMTargetLowering::
6422 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6423 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6424 DebugLoc dl = MI->getDebugLoc();
6425 MachineFunction *MF = MBB->getParent();
6426 MachineRegisterInfo *MRI = &MF->getRegInfo();
6427 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6428 MachineFrameInfo *MFI = MF->getFrameInfo();
6429 int FI = MFI->getFunctionContextIndex();
6431 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6432 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6433 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6435 // Get a mapping of the call site numbers to all of the landing pads they're
6437 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6438 unsigned MaxCSNum = 0;
6439 MachineModuleInfo &MMI = MF->getMMI();
6440 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6442 if (!BB->isLandingPad()) continue;
6444 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6446 for (MachineBasicBlock::iterator
6447 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6448 if (!II->isEHLabel()) continue;
6450 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6451 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6453 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6454 for (SmallVectorImpl<unsigned>::iterator
6455 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6456 CSI != CSE; ++CSI) {
6457 CallSiteNumToLPad[*CSI].push_back(BB);
6458 MaxCSNum = std::max(MaxCSNum, *CSI);
6464 // Get an ordered list of the machine basic blocks for the jump table.
6465 std::vector<MachineBasicBlock*> LPadList;
6466 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6467 LPadList.reserve(CallSiteNumToLPad.size());
6468 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6469 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6470 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6471 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6472 LPadList.push_back(*II);
6473 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6477 assert(!LPadList.empty() &&
6478 "No landing pad destinations for the dispatch jump table!");
6480 // Create the jump table and associated information.
6481 MachineJumpTableInfo *JTI =
6482 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6483 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6484 unsigned UId = AFI->createJumpTableUId();
6485 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6487 // Create the MBBs for the dispatch code.
6489 // Shove the dispatch's address into the return slot in the function context.
6490 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6491 DispatchBB->setIsLandingPad();
6493 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6494 unsigned trap_opcode;
6495 if (Subtarget->isThumb())
6496 trap_opcode = ARM::tTRAP;
6498 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6500 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6501 DispatchBB->addSuccessor(TrapBB);
6503 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6504 DispatchBB->addSuccessor(DispContBB);
6507 MF->insert(MF->end(), DispatchBB);
6508 MF->insert(MF->end(), DispContBB);
6509 MF->insert(MF->end(), TrapBB);
6511 // Insert code into the entry block that creates and registers the function
6513 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6515 MachineMemOperand *FIMMOLd =
6516 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6517 MachineMemOperand::MOLoad |
6518 MachineMemOperand::MOVolatile, 4, 4);
6520 MachineInstrBuilder MIB;
6521 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6523 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6524 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6526 // Add a register mask with no preserved registers. This results in all
6527 // registers being marked as clobbered.
6528 MIB.addRegMask(RI.getNoPreservedMask());
6530 unsigned NumLPads = LPadList.size();
6531 if (Subtarget->isThumb2()) {
6532 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6533 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6536 .addMemOperand(FIMMOLd));
6538 if (NumLPads < 256) {
6539 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6541 .addImm(LPadList.size()));
6543 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6544 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6545 .addImm(NumLPads & 0xFFFF));
6547 unsigned VReg2 = VReg1;
6548 if ((NumLPads & 0xFFFF0000) != 0) {
6549 VReg2 = MRI->createVirtualRegister(TRC);
6550 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6552 .addImm(NumLPads >> 16));
6555 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6560 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6565 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6566 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6567 .addJumpTableIndex(MJTI)
6570 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6573 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6574 .addReg(NewVReg3, RegState::Kill)
6576 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6578 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6579 .addReg(NewVReg4, RegState::Kill)
6581 .addJumpTableIndex(MJTI)
6583 } else if (Subtarget->isThumb()) {
6584 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6585 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6588 .addMemOperand(FIMMOLd));
6590 if (NumLPads < 256) {
6591 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6595 MachineConstantPool *ConstantPool = MF->getConstantPool();
6596 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6597 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6599 // MachineConstantPool wants an explicit alignment.
6600 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6602 Align = getDataLayout()->getTypeAllocSize(C->getType());
6603 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6605 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6606 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6607 .addReg(VReg1, RegState::Define)
6608 .addConstantPoolIndex(Idx));
6609 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6614 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6619 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6620 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6621 .addReg(ARM::CPSR, RegState::Define)
6625 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6626 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6627 .addJumpTableIndex(MJTI)
6630 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6631 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6632 .addReg(ARM::CPSR, RegState::Define)
6633 .addReg(NewVReg2, RegState::Kill)
6636 MachineMemOperand *JTMMOLd =
6637 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6638 MachineMemOperand::MOLoad, 4, 4);
6640 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6641 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6642 .addReg(NewVReg4, RegState::Kill)
6644 .addMemOperand(JTMMOLd));
6646 unsigned NewVReg6 = NewVReg5;
6647 if (RelocM == Reloc::PIC_) {
6648 NewVReg6 = MRI->createVirtualRegister(TRC);
6649 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6650 .addReg(ARM::CPSR, RegState::Define)
6651 .addReg(NewVReg5, RegState::Kill)
6655 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6656 .addReg(NewVReg6, RegState::Kill)
6657 .addJumpTableIndex(MJTI)
6660 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6661 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6664 .addMemOperand(FIMMOLd));
6666 if (NumLPads < 256) {
6667 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6670 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6671 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6672 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6673 .addImm(NumLPads & 0xFFFF));
6675 unsigned VReg2 = VReg1;
6676 if ((NumLPads & 0xFFFF0000) != 0) {
6677 VReg2 = MRI->createVirtualRegister(TRC);
6678 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6680 .addImm(NumLPads >> 16));
6683 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6687 MachineConstantPool *ConstantPool = MF->getConstantPool();
6688 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6689 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6691 // MachineConstantPool wants an explicit alignment.
6692 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6694 Align = getDataLayout()->getTypeAllocSize(C->getType());
6695 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6697 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6698 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6699 .addReg(VReg1, RegState::Define)
6700 .addConstantPoolIndex(Idx)
6702 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6704 .addReg(VReg1, RegState::Kill));
6707 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6712 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6714 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6716 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6717 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6718 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6719 .addJumpTableIndex(MJTI)
6722 MachineMemOperand *JTMMOLd =
6723 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6724 MachineMemOperand::MOLoad, 4, 4);
6725 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6727 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6728 .addReg(NewVReg3, RegState::Kill)
6731 .addMemOperand(JTMMOLd));
6733 if (RelocM == Reloc::PIC_) {
6734 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6735 .addReg(NewVReg5, RegState::Kill)
6737 .addJumpTableIndex(MJTI)
6740 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6741 .addReg(NewVReg5, RegState::Kill)
6742 .addJumpTableIndex(MJTI)
6747 // Add the jump table entries as successors to the MBB.
6748 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6749 for (std::vector<MachineBasicBlock*>::iterator
6750 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6751 MachineBasicBlock *CurMBB = *I;
6752 if (SeenMBBs.insert(CurMBB))
6753 DispContBB->addSuccessor(CurMBB);
6756 // N.B. the order the invoke BBs are processed in doesn't matter here.
6757 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6758 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6759 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6760 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6761 MachineBasicBlock *BB = *I;
6763 // Remove the landing pad successor from the invoke block and replace it
6764 // with the new dispatch block.
6765 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6767 while (!Successors.empty()) {
6768 MachineBasicBlock *SMBB = Successors.pop_back_val();
6769 if (SMBB->isLandingPad()) {
6770 BB->removeSuccessor(SMBB);
6771 MBBLPads.push_back(SMBB);
6775 BB->addSuccessor(DispatchBB);
6777 // Find the invoke call and mark all of the callee-saved registers as
6778 // 'implicit defined' so that they're spilled. This prevents code from
6779 // moving instructions to before the EH block, where they will never be
6781 for (MachineBasicBlock::reverse_iterator
6782 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6783 if (!II->isCall()) continue;
6785 DenseMap<unsigned, bool> DefRegs;
6786 for (MachineInstr::mop_iterator
6787 OI = II->operands_begin(), OE = II->operands_end();
6789 if (!OI->isReg()) continue;
6790 DefRegs[OI->getReg()] = true;
6793 MachineInstrBuilder MIB(*MF, &*II);
6795 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6796 unsigned Reg = SavedRegs[i];
6797 if (Subtarget->isThumb2() &&
6798 !ARM::tGPRRegClass.contains(Reg) &&
6799 !ARM::hGPRRegClass.contains(Reg))
6801 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6803 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6806 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6813 // Mark all former landing pads as non-landing pads. The dispatch is the only
6815 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6816 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6817 (*I)->setIsLandingPad(false);
6819 // The instruction is gone now.
6820 MI->eraseFromParent();
6826 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6827 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6828 E = MBB->succ_end(); I != E; ++I)
6831 llvm_unreachable("Expecting a BB with two successors!");
6834 /// Return the load opcode for a given load size. If load size >= 8,
6835 /// neon opcode will be returned.
6836 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6838 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6839 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6841 return LdSize == 4 ? ARM::tLDRi
6842 : LdSize == 2 ? ARM::tLDRHi
6843 : LdSize == 1 ? ARM::tLDRBi : 0;
6845 return LdSize == 4 ? ARM::t2LDR_POST
6846 : LdSize == 2 ? ARM::t2LDRH_POST
6847 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6848 return LdSize == 4 ? ARM::LDR_POST_IMM
6849 : LdSize == 2 ? ARM::LDRH_POST
6850 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6853 /// Return the store opcode for a given store size. If store size >= 8,
6854 /// neon opcode will be returned.
6855 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6857 return StSize == 16 ? ARM::VST1q32wb_fixed
6858 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6860 return StSize == 4 ? ARM::tSTRi
6861 : StSize == 2 ? ARM::tSTRHi
6862 : StSize == 1 ? ARM::tSTRBi : 0;
6864 return StSize == 4 ? ARM::t2STR_POST
6865 : StSize == 2 ? ARM::t2STRH_POST
6866 : StSize == 1 ? ARM::t2STRB_POST : 0;
6867 return StSize == 4 ? ARM::STR_POST_IMM
6868 : StSize == 2 ? ARM::STRH_POST
6869 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6872 /// Emit a post-increment load operation with given size. The instructions
6873 /// will be added to BB at Pos.
6874 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6875 const TargetInstrInfo *TII, DebugLoc dl,
6876 unsigned LdSize, unsigned Data, unsigned AddrIn,
6877 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6878 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6879 assert(LdOpc != 0 && "Should have a load opcode");
6881 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6882 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6884 } else if (IsThumb1) {
6885 // load + update AddrIn
6886 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6887 .addReg(AddrIn).addImm(0));
6888 MachineInstrBuilder MIB =
6889 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6890 MIB = AddDefaultT1CC(MIB);
6891 MIB.addReg(AddrIn).addImm(LdSize);
6892 AddDefaultPred(MIB);
6893 } else if (IsThumb2) {
6894 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6895 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6898 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6899 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6900 .addReg(0).addImm(LdSize));
6904 /// Emit a post-increment store operation with given size. The instructions
6905 /// will be added to BB at Pos.
6906 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6907 const TargetInstrInfo *TII, DebugLoc dl,
6908 unsigned StSize, unsigned Data, unsigned AddrIn,
6909 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6910 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6911 assert(StOpc != 0 && "Should have a store opcode");
6913 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6914 .addReg(AddrIn).addImm(0).addReg(Data));
6915 } else if (IsThumb1) {
6916 // store + update AddrIn
6917 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6918 .addReg(AddrIn).addImm(0));
6919 MachineInstrBuilder MIB =
6920 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6921 MIB = AddDefaultT1CC(MIB);
6922 MIB.addReg(AddrIn).addImm(StSize);
6923 AddDefaultPred(MIB);
6924 } else if (IsThumb2) {
6925 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6926 .addReg(Data).addReg(AddrIn).addImm(StSize));
6928 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6929 .addReg(Data).addReg(AddrIn).addReg(0)
6935 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6936 MachineBasicBlock *BB) const {
6937 // This pseudo instruction has 3 operands: dst, src, size
6938 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6939 // Otherwise, we will generate unrolled scalar copies.
6940 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6941 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6942 MachineFunction::iterator It = BB;
6945 unsigned dest = MI->getOperand(0).getReg();
6946 unsigned src = MI->getOperand(1).getReg();
6947 unsigned SizeVal = MI->getOperand(2).getImm();
6948 unsigned Align = MI->getOperand(3).getImm();
6949 DebugLoc dl = MI->getDebugLoc();
6951 MachineFunction *MF = BB->getParent();
6952 MachineRegisterInfo &MRI = MF->getRegInfo();
6953 unsigned UnitSize = 0;
6954 const TargetRegisterClass *TRC = nullptr;
6955 const TargetRegisterClass *VecTRC = nullptr;
6957 bool IsThumb1 = Subtarget->isThumb1Only();
6958 bool IsThumb2 = Subtarget->isThumb2();
6962 } else if (Align & 2) {
6965 // Check whether we can use NEON instructions.
6966 if (!MF->getFunction()->getAttributes().
6967 hasAttribute(AttributeSet::FunctionIndex,
6968 Attribute::NoImplicitFloat) &&
6969 Subtarget->hasNEON()) {
6970 if ((Align % 16 == 0) && SizeVal >= 16)
6972 else if ((Align % 8 == 0) && SizeVal >= 8)
6975 // Can't use NEON instructions.
6980 // Select the correct opcode and register class for unit size load/store
6981 bool IsNeon = UnitSize >= 8;
6982 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6983 : (const TargetRegisterClass *)&ARM::GPRRegClass;
6985 VecTRC = UnitSize == 16
6986 ? (const TargetRegisterClass *)&ARM::DPairRegClass
6988 ? (const TargetRegisterClass *)&ARM::DPRRegClass
6991 unsigned BytesLeft = SizeVal % UnitSize;
6992 unsigned LoopSize = SizeVal - BytesLeft;
6994 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6995 // Use LDR and STR to copy.
6996 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6997 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6998 unsigned srcIn = src;
6999 unsigned destIn = dest;
7000 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7001 unsigned srcOut = MRI.createVirtualRegister(TRC);
7002 unsigned destOut = MRI.createVirtualRegister(TRC);
7003 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7004 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7005 IsThumb1, IsThumb2);
7006 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7007 IsThumb1, IsThumb2);
7012 // Handle the leftover bytes with LDRB and STRB.
7013 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7014 // [destOut] = STRB_POST(scratch, destIn, 1)
7015 for (unsigned i = 0; i < BytesLeft; i++) {
7016 unsigned srcOut = MRI.createVirtualRegister(TRC);
7017 unsigned destOut = MRI.createVirtualRegister(TRC);
7018 unsigned scratch = MRI.createVirtualRegister(TRC);
7019 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7020 IsThumb1, IsThumb2);
7021 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7022 IsThumb1, IsThumb2);
7026 MI->eraseFromParent(); // The instruction is gone now.
7030 // Expand the pseudo op to a loop.
7033 // movw varEnd, # --> with thumb2
7035 // ldrcp varEnd, idx --> without thumb2
7036 // fallthrough --> loopMBB
7038 // PHI varPhi, varEnd, varLoop
7039 // PHI srcPhi, src, srcLoop
7040 // PHI destPhi, dst, destLoop
7041 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7042 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7043 // subs varLoop, varPhi, #UnitSize
7045 // fallthrough --> exitMBB
7047 // epilogue to handle left-over bytes
7048 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7049 // [destOut] = STRB_POST(scratch, destLoop, 1)
7050 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7051 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7052 MF->insert(It, loopMBB);
7053 MF->insert(It, exitMBB);
7055 // Transfer the remainder of BB and its successor edges to exitMBB.
7056 exitMBB->splice(exitMBB->begin(), BB,
7057 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7058 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7060 // Load an immediate to varEnd.
7061 unsigned varEnd = MRI.createVirtualRegister(TRC);
7063 unsigned Vtmp = varEnd;
7064 if ((LoopSize & 0xFFFF0000) != 0)
7065 Vtmp = MRI.createVirtualRegister(TRC);
7066 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7067 .addImm(LoopSize & 0xFFFF));
7069 if ((LoopSize & 0xFFFF0000) != 0)
7070 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7071 .addReg(Vtmp).addImm(LoopSize >> 16));
7073 MachineConstantPool *ConstantPool = MF->getConstantPool();
7074 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7075 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7077 // MachineConstantPool wants an explicit alignment.
7078 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7080 Align = getDataLayout()->getTypeAllocSize(C->getType());
7081 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7084 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7085 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7087 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7088 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7090 BB->addSuccessor(loopMBB);
7092 // Generate the loop body:
7093 // varPhi = PHI(varLoop, varEnd)
7094 // srcPhi = PHI(srcLoop, src)
7095 // destPhi = PHI(destLoop, dst)
7096 MachineBasicBlock *entryBB = BB;
7098 unsigned varLoop = MRI.createVirtualRegister(TRC);
7099 unsigned varPhi = MRI.createVirtualRegister(TRC);
7100 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7101 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7102 unsigned destLoop = MRI.createVirtualRegister(TRC);
7103 unsigned destPhi = MRI.createVirtualRegister(TRC);
7105 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7106 .addReg(varLoop).addMBB(loopMBB)
7107 .addReg(varEnd).addMBB(entryBB);
7108 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7109 .addReg(srcLoop).addMBB(loopMBB)
7110 .addReg(src).addMBB(entryBB);
7111 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7112 .addReg(destLoop).addMBB(loopMBB)
7113 .addReg(dest).addMBB(entryBB);
7115 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7116 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7117 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7118 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7119 IsThumb1, IsThumb2);
7120 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7121 IsThumb1, IsThumb2);
7123 // Decrement loop variable by UnitSize.
7125 MachineInstrBuilder MIB =
7126 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7127 MIB = AddDefaultT1CC(MIB);
7128 MIB.addReg(varPhi).addImm(UnitSize);
7129 AddDefaultPred(MIB);
7131 MachineInstrBuilder MIB =
7132 BuildMI(*BB, BB->end(), dl,
7133 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7134 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7135 MIB->getOperand(5).setReg(ARM::CPSR);
7136 MIB->getOperand(5).setIsDef(true);
7138 BuildMI(*BB, BB->end(), dl,
7139 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7140 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7142 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7143 BB->addSuccessor(loopMBB);
7144 BB->addSuccessor(exitMBB);
7146 // Add epilogue to handle BytesLeft.
7148 MachineInstr *StartOfExit = exitMBB->begin();
7150 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7151 // [destOut] = STRB_POST(scratch, destLoop, 1)
7152 unsigned srcIn = srcLoop;
7153 unsigned destIn = destLoop;
7154 for (unsigned i = 0; i < BytesLeft; i++) {
7155 unsigned srcOut = MRI.createVirtualRegister(TRC);
7156 unsigned destOut = MRI.createVirtualRegister(TRC);
7157 unsigned scratch = MRI.createVirtualRegister(TRC);
7158 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7159 IsThumb1, IsThumb2);
7160 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7161 IsThumb1, IsThumb2);
7166 MI->eraseFromParent(); // The instruction is gone now.
7171 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7172 MachineBasicBlock *BB) const {
7173 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7174 DebugLoc dl = MI->getDebugLoc();
7175 bool isThumb2 = Subtarget->isThumb2();
7176 switch (MI->getOpcode()) {
7179 llvm_unreachable("Unexpected instr type to insert");
7181 // The Thumb2 pre-indexed stores have the same MI operands, they just
7182 // define them differently in the .td files from the isel patterns, so
7183 // they need pseudos.
7184 case ARM::t2STR_preidx:
7185 MI->setDesc(TII->get(ARM::t2STR_PRE));
7187 case ARM::t2STRB_preidx:
7188 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7190 case ARM::t2STRH_preidx:
7191 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7194 case ARM::STRi_preidx:
7195 case ARM::STRBi_preidx: {
7196 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7197 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7198 // Decode the offset.
7199 unsigned Offset = MI->getOperand(4).getImm();
7200 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7201 Offset = ARM_AM::getAM2Offset(Offset);
7205 MachineMemOperand *MMO = *MI->memoperands_begin();
7206 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7207 .addOperand(MI->getOperand(0)) // Rn_wb
7208 .addOperand(MI->getOperand(1)) // Rt
7209 .addOperand(MI->getOperand(2)) // Rn
7210 .addImm(Offset) // offset (skip GPR==zero_reg)
7211 .addOperand(MI->getOperand(5)) // pred
7212 .addOperand(MI->getOperand(6))
7213 .addMemOperand(MMO);
7214 MI->eraseFromParent();
7217 case ARM::STRr_preidx:
7218 case ARM::STRBr_preidx:
7219 case ARM::STRH_preidx: {
7221 switch (MI->getOpcode()) {
7222 default: llvm_unreachable("unexpected opcode!");
7223 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7224 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7225 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7227 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7228 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7229 MIB.addOperand(MI->getOperand(i));
7230 MI->eraseFromParent();
7234 case ARM::tMOVCCr_pseudo: {
7235 // To "insert" a SELECT_CC instruction, we actually have to insert the
7236 // diamond control-flow pattern. The incoming instruction knows the
7237 // destination vreg to set, the condition code register to branch on, the
7238 // true/false values to select between, and a branch opcode to use.
7239 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7240 MachineFunction::iterator It = BB;
7246 // cmpTY ccX, r1, r2
7248 // fallthrough --> copy0MBB
7249 MachineBasicBlock *thisMBB = BB;
7250 MachineFunction *F = BB->getParent();
7251 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7252 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7253 F->insert(It, copy0MBB);
7254 F->insert(It, sinkMBB);
7256 // Transfer the remainder of BB and its successor edges to sinkMBB.
7257 sinkMBB->splice(sinkMBB->begin(), BB,
7258 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7259 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7261 BB->addSuccessor(copy0MBB);
7262 BB->addSuccessor(sinkMBB);
7264 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7265 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7268 // %FalseValue = ...
7269 // # fallthrough to sinkMBB
7272 // Update machine-CFG edges
7273 BB->addSuccessor(sinkMBB);
7276 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7279 BuildMI(*BB, BB->begin(), dl,
7280 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7281 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7282 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7284 MI->eraseFromParent(); // The pseudo instruction is gone now.
7289 case ARM::BCCZi64: {
7290 // If there is an unconditional branch to the other successor, remove it.
7291 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7293 // Compare both parts that make up the double comparison separately for
7295 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7297 unsigned LHS1 = MI->getOperand(1).getReg();
7298 unsigned LHS2 = MI->getOperand(2).getReg();
7300 AddDefaultPred(BuildMI(BB, dl,
7301 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7302 .addReg(LHS1).addImm(0));
7303 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7304 .addReg(LHS2).addImm(0)
7305 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7307 unsigned RHS1 = MI->getOperand(3).getReg();
7308 unsigned RHS2 = MI->getOperand(4).getReg();
7309 AddDefaultPred(BuildMI(BB, dl,
7310 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7311 .addReg(LHS1).addReg(RHS1));
7312 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7313 .addReg(LHS2).addReg(RHS2)
7314 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7317 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7318 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7319 if (MI->getOperand(0).getImm() == ARMCC::NE)
7320 std::swap(destMBB, exitMBB);
7322 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7323 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7325 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7327 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7329 MI->eraseFromParent(); // The pseudo instruction is gone now.
7333 case ARM::Int_eh_sjlj_setjmp:
7334 case ARM::Int_eh_sjlj_setjmp_nofp:
7335 case ARM::tInt_eh_sjlj_setjmp:
7336 case ARM::t2Int_eh_sjlj_setjmp:
7337 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7338 EmitSjLjDispatchBlock(MI, BB);
7343 // To insert an ABS instruction, we have to insert the
7344 // diamond control-flow pattern. The incoming instruction knows the
7345 // source vreg to test against 0, the destination vreg to set,
7346 // the condition code register to branch on, the
7347 // true/false values to select between, and a branch opcode to use.
7352 // BCC (branch to SinkBB if V0 >= 0)
7353 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7354 // SinkBB: V1 = PHI(V2, V3)
7355 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7356 MachineFunction::iterator BBI = BB;
7358 MachineFunction *Fn = BB->getParent();
7359 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7360 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7361 Fn->insert(BBI, RSBBB);
7362 Fn->insert(BBI, SinkBB);
7364 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7365 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7366 bool isThumb2 = Subtarget->isThumb2();
7367 MachineRegisterInfo &MRI = Fn->getRegInfo();
7368 // In Thumb mode S must not be specified if source register is the SP or
7369 // PC and if destination register is the SP, so restrict register class
7370 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7371 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7372 (const TargetRegisterClass*)&ARM::GPRRegClass);
7374 // Transfer the remainder of BB and its successor edges to sinkMBB.
7375 SinkBB->splice(SinkBB->begin(), BB,
7376 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7377 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7379 BB->addSuccessor(RSBBB);
7380 BB->addSuccessor(SinkBB);
7382 // fall through to SinkMBB
7383 RSBBB->addSuccessor(SinkBB);
7385 // insert a cmp at the end of BB
7386 AddDefaultPred(BuildMI(BB, dl,
7387 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7388 .addReg(ABSSrcReg).addImm(0));
7390 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7392 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7393 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7395 // insert rsbri in RSBBB
7396 // Note: BCC and rsbri will be converted into predicated rsbmi
7397 // by if-conversion pass
7398 BuildMI(*RSBBB, RSBBB->begin(), dl,
7399 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7400 .addReg(ABSSrcReg, RegState::Kill)
7401 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7403 // insert PHI in SinkBB,
7404 // reuse ABSDstReg to not change uses of ABS instruction
7405 BuildMI(*SinkBB, SinkBB->begin(), dl,
7406 TII->get(ARM::PHI), ABSDstReg)
7407 .addReg(NewRsbDstReg).addMBB(RSBBB)
7408 .addReg(ABSSrcReg).addMBB(BB);
7410 // remove ABS instruction
7411 MI->eraseFromParent();
7413 // return last added BB
7416 case ARM::COPY_STRUCT_BYVAL_I32:
7418 return EmitStructByval(MI, BB);
7422 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7423 SDNode *Node) const {
7424 if (!MI->hasPostISelHook()) {
7425 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7426 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7430 const MCInstrDesc *MCID = &MI->getDesc();
7431 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7432 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7433 // operand is still set to noreg. If needed, set the optional operand's
7434 // register to CPSR, and remove the redundant implicit def.
7436 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7438 // Rename pseudo opcodes.
7439 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7441 const ARMBaseInstrInfo *TII =
7442 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7443 MCID = &TII->get(NewOpc);
7445 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7446 "converted opcode should be the same except for cc_out");
7450 // Add the optional cc_out operand
7451 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7453 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7455 // Any ARM instruction that sets the 's' bit should specify an optional
7456 // "cc_out" operand in the last operand position.
7457 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7458 assert(!NewOpc && "Optional cc_out operand required");
7461 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7462 // since we already have an optional CPSR def.
7463 bool definesCPSR = false;
7464 bool deadCPSR = false;
7465 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7467 const MachineOperand &MO = MI->getOperand(i);
7468 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7472 MI->RemoveOperand(i);
7477 assert(!NewOpc && "Optional cc_out operand required");
7480 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7482 assert(!MI->getOperand(ccOutIdx).getReg() &&
7483 "expect uninitialized optional cc_out operand");
7487 // If this instruction was defined with an optional CPSR def and its dag node
7488 // had a live implicit CPSR def, then activate the optional CPSR def.
7489 MachineOperand &MO = MI->getOperand(ccOutIdx);
7490 MO.setReg(ARM::CPSR);
7494 //===----------------------------------------------------------------------===//
7495 // ARM Optimization Hooks
7496 //===----------------------------------------------------------------------===//
7498 // Helper function that checks if N is a null or all ones constant.
7499 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7500 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7503 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7506 // Return true if N is conditionally 0 or all ones.
7507 // Detects these expressions where cc is an i1 value:
7509 // (select cc 0, y) [AllOnes=0]
7510 // (select cc y, 0) [AllOnes=0]
7511 // (zext cc) [AllOnes=0]
7512 // (sext cc) [AllOnes=0/1]
7513 // (select cc -1, y) [AllOnes=1]
7514 // (select cc y, -1) [AllOnes=1]
7516 // Invert is set when N is the null/all ones constant when CC is false.
7517 // OtherOp is set to the alternative value of N.
7518 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7519 SDValue &CC, bool &Invert,
7521 SelectionDAG &DAG) {
7522 switch (N->getOpcode()) {
7523 default: return false;
7525 CC = N->getOperand(0);
7526 SDValue N1 = N->getOperand(1);
7527 SDValue N2 = N->getOperand(2);
7528 if (isZeroOrAllOnes(N1, AllOnes)) {
7533 if (isZeroOrAllOnes(N2, AllOnes)) {
7540 case ISD::ZERO_EXTEND:
7541 // (zext cc) can never be the all ones value.
7545 case ISD::SIGN_EXTEND: {
7546 EVT VT = N->getValueType(0);
7547 CC = N->getOperand(0);
7548 if (CC.getValueType() != MVT::i1)
7552 // When looking for an AllOnes constant, N is an sext, and the 'other'
7554 OtherOp = DAG.getConstant(0, VT);
7555 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7556 // When looking for a 0 constant, N can be zext or sext.
7557 OtherOp = DAG.getConstant(1, VT);
7559 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7565 // Combine a constant select operand into its use:
7567 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7568 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7569 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7570 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7571 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7573 // The transform is rejected if the select doesn't have a constant operand that
7574 // is null, or all ones when AllOnes is set.
7576 // Also recognize sext/zext from i1:
7578 // (add (zext cc), x) -> (select cc (add x, 1), x)
7579 // (add (sext cc), x) -> (select cc (add x, -1), x)
7581 // These transformations eventually create predicated instructions.
7583 // @param N The node to transform.
7584 // @param Slct The N operand that is a select.
7585 // @param OtherOp The other N operand (x above).
7586 // @param DCI Context.
7587 // @param AllOnes Require the select constant to be all ones instead of null.
7588 // @returns The new node, or SDValue() on failure.
7590 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7591 TargetLowering::DAGCombinerInfo &DCI,
7592 bool AllOnes = false) {
7593 SelectionDAG &DAG = DCI.DAG;
7594 EVT VT = N->getValueType(0);
7595 SDValue NonConstantVal;
7598 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7599 NonConstantVal, DAG))
7602 // Slct is now know to be the desired identity constant when CC is true.
7603 SDValue TrueVal = OtherOp;
7604 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7605 OtherOp, NonConstantVal);
7606 // Unless SwapSelectOps says CC should be false.
7608 std::swap(TrueVal, FalseVal);
7610 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7611 CCOp, TrueVal, FalseVal);
7614 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7616 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7617 TargetLowering::DAGCombinerInfo &DCI) {
7618 SDValue N0 = N->getOperand(0);
7619 SDValue N1 = N->getOperand(1);
7620 if (N0.getNode()->hasOneUse()) {
7621 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7622 if (Result.getNode())
7625 if (N1.getNode()->hasOneUse()) {
7626 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7627 if (Result.getNode())
7633 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7634 // (only after legalization).
7635 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7636 TargetLowering::DAGCombinerInfo &DCI,
7637 const ARMSubtarget *Subtarget) {
7639 // Only perform optimization if after legalize, and if NEON is available. We
7640 // also expected both operands to be BUILD_VECTORs.
7641 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7642 || N0.getOpcode() != ISD::BUILD_VECTOR
7643 || N1.getOpcode() != ISD::BUILD_VECTOR)
7646 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7647 EVT VT = N->getValueType(0);
7648 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7651 // Check that the vector operands are of the right form.
7652 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7653 // operands, where N is the size of the formed vector.
7654 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7655 // index such that we have a pair wise add pattern.
7657 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7658 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7660 SDValue Vec = N0->getOperand(0)->getOperand(0);
7661 SDNode *V = Vec.getNode();
7662 unsigned nextIndex = 0;
7664 // For each operands to the ADD which are BUILD_VECTORs,
7665 // check to see if each of their operands are an EXTRACT_VECTOR with
7666 // the same vector and appropriate index.
7667 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7668 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7669 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7671 SDValue ExtVec0 = N0->getOperand(i);
7672 SDValue ExtVec1 = N1->getOperand(i);
7674 // First operand is the vector, verify its the same.
7675 if (V != ExtVec0->getOperand(0).getNode() ||
7676 V != ExtVec1->getOperand(0).getNode())
7679 // Second is the constant, verify its correct.
7680 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7681 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7683 // For the constant, we want to see all the even or all the odd.
7684 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7685 || C1->getZExtValue() != nextIndex+1)
7694 // Create VPADDL node.
7695 SelectionDAG &DAG = DCI.DAG;
7696 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7698 // Build operand list.
7699 SmallVector<SDValue, 8> Ops;
7700 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7701 TLI.getPointerTy()));
7703 // Input is the vector.
7706 // Get widened type and narrowed type.
7708 unsigned numElem = VT.getVectorNumElements();
7710 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7711 switch (inputLaneType.getSimpleVT().SimpleTy) {
7712 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7713 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7714 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7716 llvm_unreachable("Invalid vector element type for padd optimization.");
7719 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7720 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7721 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7724 static SDValue findMUL_LOHI(SDValue V) {
7725 if (V->getOpcode() == ISD::UMUL_LOHI ||
7726 V->getOpcode() == ISD::SMUL_LOHI)
7731 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7732 TargetLowering::DAGCombinerInfo &DCI,
7733 const ARMSubtarget *Subtarget) {
7735 if (Subtarget->isThumb1Only()) return SDValue();
7737 // Only perform the checks after legalize when the pattern is available.
7738 if (DCI.isBeforeLegalize()) return SDValue();
7740 // Look for multiply add opportunities.
7741 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7742 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7743 // a glue link from the first add to the second add.
7744 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7745 // a S/UMLAL instruction.
7748 // \ / \ [no multiline comment]
7754 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7755 SDValue AddcOp0 = AddcNode->getOperand(0);
7756 SDValue AddcOp1 = AddcNode->getOperand(1);
7758 // Check if the two operands are from the same mul_lohi node.
7759 if (AddcOp0.getNode() == AddcOp1.getNode())
7762 assert(AddcNode->getNumValues() == 2 &&
7763 AddcNode->getValueType(0) == MVT::i32 &&
7764 "Expect ADDC with two result values. First: i32");
7766 // Check that we have a glued ADDC node.
7767 if (AddcNode->getValueType(1) != MVT::Glue)
7770 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7771 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7772 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7773 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7774 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7777 // Look for the glued ADDE.
7778 SDNode* AddeNode = AddcNode->getGluedUser();
7782 // Make sure it is really an ADDE.
7783 if (AddeNode->getOpcode() != ISD::ADDE)
7786 assert(AddeNode->getNumOperands() == 3 &&
7787 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7788 "ADDE node has the wrong inputs");
7790 // Check for the triangle shape.
7791 SDValue AddeOp0 = AddeNode->getOperand(0);
7792 SDValue AddeOp1 = AddeNode->getOperand(1);
7794 // Make sure that the ADDE operands are not coming from the same node.
7795 if (AddeOp0.getNode() == AddeOp1.getNode())
7798 // Find the MUL_LOHI node walking up ADDE's operands.
7799 bool IsLeftOperandMUL = false;
7800 SDValue MULOp = findMUL_LOHI(AddeOp0);
7801 if (MULOp == SDValue())
7802 MULOp = findMUL_LOHI(AddeOp1);
7804 IsLeftOperandMUL = true;
7805 if (MULOp == SDValue())
7808 // Figure out the right opcode.
7809 unsigned Opc = MULOp->getOpcode();
7810 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7812 // Figure out the high and low input values to the MLAL node.
7813 SDValue* HiMul = &MULOp;
7814 SDValue* HiAdd = nullptr;
7815 SDValue* LoMul = nullptr;
7816 SDValue* LowAdd = nullptr;
7818 if (IsLeftOperandMUL)
7824 if (AddcOp0->getOpcode() == Opc) {
7828 if (AddcOp1->getOpcode() == Opc) {
7836 if (LoMul->getNode() != HiMul->getNode())
7839 // Create the merged node.
7840 SelectionDAG &DAG = DCI.DAG;
7842 // Build operand list.
7843 SmallVector<SDValue, 8> Ops;
7844 Ops.push_back(LoMul->getOperand(0));
7845 Ops.push_back(LoMul->getOperand(1));
7846 Ops.push_back(*LowAdd);
7847 Ops.push_back(*HiAdd);
7849 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7850 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7852 // Replace the ADDs' nodes uses by the MLA node's values.
7853 SDValue HiMLALResult(MLALNode.getNode(), 1);
7854 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7856 SDValue LoMLALResult(MLALNode.getNode(), 0);
7857 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7859 // Return original node to notify the driver to stop replacing.
7860 SDValue resNode(AddcNode, 0);
7864 /// PerformADDCCombine - Target-specific dag combine transform from
7865 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7866 static SDValue PerformADDCCombine(SDNode *N,
7867 TargetLowering::DAGCombinerInfo &DCI,
7868 const ARMSubtarget *Subtarget) {
7870 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7874 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7875 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7876 /// called with the default operands, and if that fails, with commuted
7878 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7879 TargetLowering::DAGCombinerInfo &DCI,
7880 const ARMSubtarget *Subtarget){
7882 // Attempt to create vpaddl for this add.
7883 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7884 if (Result.getNode())
7887 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7888 if (N0.getNode()->hasOneUse()) {
7889 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7890 if (Result.getNode()) return Result;
7895 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7897 static SDValue PerformADDCombine(SDNode *N,
7898 TargetLowering::DAGCombinerInfo &DCI,
7899 const ARMSubtarget *Subtarget) {
7900 SDValue N0 = N->getOperand(0);
7901 SDValue N1 = N->getOperand(1);
7903 // First try with the default operand order.
7904 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7905 if (Result.getNode())
7908 // If that didn't work, try again with the operands commuted.
7909 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7912 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7914 static SDValue PerformSUBCombine(SDNode *N,
7915 TargetLowering::DAGCombinerInfo &DCI) {
7916 SDValue N0 = N->getOperand(0);
7917 SDValue N1 = N->getOperand(1);
7919 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7920 if (N1.getNode()->hasOneUse()) {
7921 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7922 if (Result.getNode()) return Result;
7928 /// PerformVMULCombine
7929 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7930 /// special multiplier accumulator forwarding.
7936 // However, for (A + B) * (A + B),
7943 static SDValue PerformVMULCombine(SDNode *N,
7944 TargetLowering::DAGCombinerInfo &DCI,
7945 const ARMSubtarget *Subtarget) {
7946 if (!Subtarget->hasVMLxForwarding())
7949 SelectionDAG &DAG = DCI.DAG;
7950 SDValue N0 = N->getOperand(0);
7951 SDValue N1 = N->getOperand(1);
7952 unsigned Opcode = N0.getOpcode();
7953 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7954 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7955 Opcode = N1.getOpcode();
7956 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7957 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7965 EVT VT = N->getValueType(0);
7967 SDValue N00 = N0->getOperand(0);
7968 SDValue N01 = N0->getOperand(1);
7969 return DAG.getNode(Opcode, DL, VT,
7970 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7971 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7974 static SDValue PerformMULCombine(SDNode *N,
7975 TargetLowering::DAGCombinerInfo &DCI,
7976 const ARMSubtarget *Subtarget) {
7977 SelectionDAG &DAG = DCI.DAG;
7979 if (Subtarget->isThumb1Only())
7982 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7985 EVT VT = N->getValueType(0);
7986 if (VT.is64BitVector() || VT.is128BitVector())
7987 return PerformVMULCombine(N, DCI, Subtarget);
7991 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7995 int64_t MulAmt = C->getSExtValue();
7996 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7998 ShiftAmt = ShiftAmt & (32 - 1);
7999 SDValue V = N->getOperand(0);
8003 MulAmt >>= ShiftAmt;
8006 if (isPowerOf2_32(MulAmt - 1)) {
8007 // (mul x, 2^N + 1) => (add (shl x, N), x)
8008 Res = DAG.getNode(ISD::ADD, DL, VT,
8010 DAG.getNode(ISD::SHL, DL, VT,
8012 DAG.getConstant(Log2_32(MulAmt - 1),
8014 } else if (isPowerOf2_32(MulAmt + 1)) {
8015 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8016 Res = DAG.getNode(ISD::SUB, DL, VT,
8017 DAG.getNode(ISD::SHL, DL, VT,
8019 DAG.getConstant(Log2_32(MulAmt + 1),
8025 uint64_t MulAmtAbs = -MulAmt;
8026 if (isPowerOf2_32(MulAmtAbs + 1)) {
8027 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8028 Res = DAG.getNode(ISD::SUB, DL, VT,
8030 DAG.getNode(ISD::SHL, DL, VT,
8032 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8034 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8035 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8036 Res = DAG.getNode(ISD::ADD, DL, VT,
8038 DAG.getNode(ISD::SHL, DL, VT,
8040 DAG.getConstant(Log2_32(MulAmtAbs-1),
8042 Res = DAG.getNode(ISD::SUB, DL, VT,
8043 DAG.getConstant(0, MVT::i32),Res);
8050 Res = DAG.getNode(ISD::SHL, DL, VT,
8051 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8053 // Do not add new nodes to DAG combiner worklist.
8054 DCI.CombineTo(N, Res, false);
8058 static SDValue PerformANDCombine(SDNode *N,
8059 TargetLowering::DAGCombinerInfo &DCI,
8060 const ARMSubtarget *Subtarget) {
8062 // Attempt to use immediate-form VBIC
8063 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8065 EVT VT = N->getValueType(0);
8066 SelectionDAG &DAG = DCI.DAG;
8068 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8071 APInt SplatBits, SplatUndef;
8072 unsigned SplatBitSize;
8075 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8076 if (SplatBitSize <= 64) {
8078 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8079 SplatUndef.getZExtValue(), SplatBitSize,
8080 DAG, VbicVT, VT.is128BitVector(),
8082 if (Val.getNode()) {
8084 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8085 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8086 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8091 if (!Subtarget->isThumb1Only()) {
8092 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8093 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8094 if (Result.getNode())
8101 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8102 static SDValue PerformORCombine(SDNode *N,
8103 TargetLowering::DAGCombinerInfo &DCI,
8104 const ARMSubtarget *Subtarget) {
8105 // Attempt to use immediate-form VORR
8106 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8108 EVT VT = N->getValueType(0);
8109 SelectionDAG &DAG = DCI.DAG;
8111 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8114 APInt SplatBits, SplatUndef;
8115 unsigned SplatBitSize;
8117 if (BVN && Subtarget->hasNEON() &&
8118 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8119 if (SplatBitSize <= 64) {
8121 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8122 SplatUndef.getZExtValue(), SplatBitSize,
8123 DAG, VorrVT, VT.is128BitVector(),
8125 if (Val.getNode()) {
8127 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8128 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8129 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8134 if (!Subtarget->isThumb1Only()) {
8135 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8136 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8137 if (Result.getNode())
8141 // The code below optimizes (or (and X, Y), Z).
8142 // The AND operand needs to have a single user to make these optimizations
8144 SDValue N0 = N->getOperand(0);
8145 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8147 SDValue N1 = N->getOperand(1);
8149 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8150 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8151 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8153 unsigned SplatBitSize;
8156 APInt SplatBits0, SplatBits1;
8157 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8158 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8159 // Ensure that the second operand of both ands are constants
8160 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8161 HasAnyUndefs) && !HasAnyUndefs) {
8162 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8163 HasAnyUndefs) && !HasAnyUndefs) {
8164 // Ensure that the bit width of the constants are the same and that
8165 // the splat arguments are logical inverses as per the pattern we
8166 // are trying to simplify.
8167 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8168 SplatBits0 == ~SplatBits1) {
8169 // Canonicalize the vector type to make instruction selection
8171 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8172 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8176 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8182 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8185 // BFI is only available on V6T2+
8186 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8190 // 1) or (and A, mask), val => ARMbfi A, val, mask
8191 // iff (val & mask) == val
8193 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8194 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8195 // && mask == ~mask2
8196 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8197 // && ~mask == mask2
8198 // (i.e., copy a bitfield value into another bitfield of the same width)
8203 SDValue N00 = N0.getOperand(0);
8205 // The value and the mask need to be constants so we can verify this is
8206 // actually a bitfield set. If the mask is 0xffff, we can do better
8207 // via a movt instruction, so don't use BFI in that case.
8208 SDValue MaskOp = N0.getOperand(1);
8209 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8212 unsigned Mask = MaskC->getZExtValue();
8216 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8217 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8219 unsigned Val = N1C->getZExtValue();
8220 if ((Val & ~Mask) != Val)
8223 if (ARM::isBitFieldInvertedMask(Mask)) {
8224 Val >>= countTrailingZeros(~Mask);
8226 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8227 DAG.getConstant(Val, MVT::i32),
8228 DAG.getConstant(Mask, MVT::i32));
8230 // Do not add new nodes to DAG combiner worklist.
8231 DCI.CombineTo(N, Res, false);
8234 } else if (N1.getOpcode() == ISD::AND) {
8235 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8236 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8239 unsigned Mask2 = N11C->getZExtValue();
8241 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8243 if (ARM::isBitFieldInvertedMask(Mask) &&
8245 // The pack halfword instruction works better for masks that fit it,
8246 // so use that when it's available.
8247 if (Subtarget->hasT2ExtractPack() &&
8248 (Mask == 0xffff || Mask == 0xffff0000))
8251 unsigned amt = countTrailingZeros(Mask2);
8252 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8253 DAG.getConstant(amt, MVT::i32));
8254 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8255 DAG.getConstant(Mask, MVT::i32));
8256 // Do not add new nodes to DAG combiner worklist.
8257 DCI.CombineTo(N, Res, false);
8259 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8261 // The pack halfword instruction works better for masks that fit it,
8262 // so use that when it's available.
8263 if (Subtarget->hasT2ExtractPack() &&
8264 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8267 unsigned lsb = countTrailingZeros(Mask);
8268 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8269 DAG.getConstant(lsb, MVT::i32));
8270 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8271 DAG.getConstant(Mask2, MVT::i32));
8272 // Do not add new nodes to DAG combiner worklist.
8273 DCI.CombineTo(N, Res, false);
8278 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8279 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8280 ARM::isBitFieldInvertedMask(~Mask)) {
8281 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8282 // where lsb(mask) == #shamt and masked bits of B are known zero.
8283 SDValue ShAmt = N00.getOperand(1);
8284 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8285 unsigned LSB = countTrailingZeros(Mask);
8289 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8290 DAG.getConstant(~Mask, MVT::i32));
8292 // Do not add new nodes to DAG combiner worklist.
8293 DCI.CombineTo(N, Res, false);
8299 static SDValue PerformXORCombine(SDNode *N,
8300 TargetLowering::DAGCombinerInfo &DCI,
8301 const ARMSubtarget *Subtarget) {
8302 EVT VT = N->getValueType(0);
8303 SelectionDAG &DAG = DCI.DAG;
8305 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8308 if (!Subtarget->isThumb1Only()) {
8309 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8310 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8311 if (Result.getNode())
8318 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8319 /// the bits being cleared by the AND are not demanded by the BFI.
8320 static SDValue PerformBFICombine(SDNode *N,
8321 TargetLowering::DAGCombinerInfo &DCI) {
8322 SDValue N1 = N->getOperand(1);
8323 if (N1.getOpcode() == ISD::AND) {
8324 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8327 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8328 unsigned LSB = countTrailingZeros(~InvMask);
8329 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8330 unsigned Mask = (1 << Width)-1;
8331 unsigned Mask2 = N11C->getZExtValue();
8332 if ((Mask & (~Mask2)) == 0)
8333 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8334 N->getOperand(0), N1.getOperand(0),
8340 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8341 /// ARMISD::VMOVRRD.
8342 static SDValue PerformVMOVRRDCombine(SDNode *N,
8343 TargetLowering::DAGCombinerInfo &DCI) {
8344 // vmovrrd(vmovdrr x, y) -> x,y
8345 SDValue InDouble = N->getOperand(0);
8346 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8347 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8349 // vmovrrd(load f64) -> (load i32), (load i32)
8350 SDNode *InNode = InDouble.getNode();
8351 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8352 InNode->getValueType(0) == MVT::f64 &&
8353 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8354 !cast<LoadSDNode>(InNode)->isVolatile()) {
8355 // TODO: Should this be done for non-FrameIndex operands?
8356 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8358 SelectionDAG &DAG = DCI.DAG;
8360 SDValue BasePtr = LD->getBasePtr();
8361 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8362 LD->getPointerInfo(), LD->isVolatile(),
8363 LD->isNonTemporal(), LD->isInvariant(),
8364 LD->getAlignment());
8366 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8367 DAG.getConstant(4, MVT::i32));
8368 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8369 LD->getPointerInfo(), LD->isVolatile(),
8370 LD->isNonTemporal(), LD->isInvariant(),
8371 std::min(4U, LD->getAlignment() / 2));
8373 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8374 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8375 DCI.RemoveFromWorklist(LD);
8383 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8384 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8385 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8386 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8387 SDValue Op0 = N->getOperand(0);
8388 SDValue Op1 = N->getOperand(1);
8389 if (Op0.getOpcode() == ISD::BITCAST)
8390 Op0 = Op0.getOperand(0);
8391 if (Op1.getOpcode() == ISD::BITCAST)
8392 Op1 = Op1.getOperand(0);
8393 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8394 Op0.getNode() == Op1.getNode() &&
8395 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8396 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8397 N->getValueType(0), Op0.getOperand(0));
8401 /// PerformSTORECombine - Target-specific dag combine xforms for
8403 static SDValue PerformSTORECombine(SDNode *N,
8404 TargetLowering::DAGCombinerInfo &DCI) {
8405 StoreSDNode *St = cast<StoreSDNode>(N);
8406 if (St->isVolatile())
8409 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8410 // pack all of the elements in one place. Next, store to memory in fewer
8412 SDValue StVal = St->getValue();
8413 EVT VT = StVal.getValueType();
8414 if (St->isTruncatingStore() && VT.isVector()) {
8415 SelectionDAG &DAG = DCI.DAG;
8416 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8417 EVT StVT = St->getMemoryVT();
8418 unsigned NumElems = VT.getVectorNumElements();
8419 assert(StVT != VT && "Cannot truncate to the same type");
8420 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8421 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8423 // From, To sizes and ElemCount must be pow of two
8424 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8426 // We are going to use the original vector elt for storing.
8427 // Accumulated smaller vector elements must be a multiple of the store size.
8428 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8430 unsigned SizeRatio = FromEltSz / ToEltSz;
8431 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8433 // Create a type on which we perform the shuffle.
8434 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8435 NumElems*SizeRatio);
8436 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8439 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8440 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8441 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8443 // Can't shuffle using an illegal type.
8444 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8446 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8447 DAG.getUNDEF(WideVec.getValueType()),
8449 // At this point all of the data is stored at the bottom of the
8450 // register. We now need to save it to mem.
8452 // Find the largest store unit
8453 MVT StoreType = MVT::i8;
8454 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8455 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8456 MVT Tp = (MVT::SimpleValueType)tp;
8457 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8460 // Didn't find a legal store type.
8461 if (!TLI.isTypeLegal(StoreType))
8464 // Bitcast the original vector into a vector of store-size units
8465 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8466 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8467 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8468 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8469 SmallVector<SDValue, 8> Chains;
8470 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8471 TLI.getPointerTy());
8472 SDValue BasePtr = St->getBasePtr();
8474 // Perform one or more big stores into memory.
8475 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8476 for (unsigned I = 0; I < E; I++) {
8477 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8478 StoreType, ShuffWide,
8479 DAG.getIntPtrConstant(I));
8480 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8481 St->getPointerInfo(), St->isVolatile(),
8482 St->isNonTemporal(), St->getAlignment());
8483 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8485 Chains.push_back(Ch);
8487 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8490 if (!ISD::isNormalStore(St))
8493 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8494 // ARM stores of arguments in the same cache line.
8495 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8496 StVal.getNode()->hasOneUse()) {
8497 SelectionDAG &DAG = DCI.DAG;
8498 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8500 SDValue BasePtr = St->getBasePtr();
8501 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8502 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8503 BasePtr, St->getPointerInfo(), St->isVolatile(),
8504 St->isNonTemporal(), St->getAlignment());
8506 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8507 DAG.getConstant(4, MVT::i32));
8508 return DAG.getStore(NewST1.getValue(0), DL,
8509 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8510 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8511 St->isNonTemporal(),
8512 std::min(4U, St->getAlignment() / 2));
8515 if (StVal.getValueType() != MVT::i64 ||
8516 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8519 // Bitcast an i64 store extracted from a vector to f64.
8520 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8521 SelectionDAG &DAG = DCI.DAG;
8523 SDValue IntVec = StVal.getOperand(0);
8524 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8525 IntVec.getValueType().getVectorNumElements());
8526 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8527 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8528 Vec, StVal.getOperand(1));
8530 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8531 // Make the DAGCombiner fold the bitcasts.
8532 DCI.AddToWorklist(Vec.getNode());
8533 DCI.AddToWorklist(ExtElt.getNode());
8534 DCI.AddToWorklist(V.getNode());
8535 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8536 St->getPointerInfo(), St->isVolatile(),
8537 St->isNonTemporal(), St->getAlignment(),
8541 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8542 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8543 /// i64 vector to have f64 elements, since the value can then be loaded
8544 /// directly into a VFP register.
8545 static bool hasNormalLoadOperand(SDNode *N) {
8546 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8547 for (unsigned i = 0; i < NumElts; ++i) {
8548 SDNode *Elt = N->getOperand(i).getNode();
8549 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8555 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8556 /// ISD::BUILD_VECTOR.
8557 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8558 TargetLowering::DAGCombinerInfo &DCI){
8559 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8560 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8561 // into a pair of GPRs, which is fine when the value is used as a scalar,
8562 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8563 SelectionDAG &DAG = DCI.DAG;
8564 if (N->getNumOperands() == 2) {
8565 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8570 // Load i64 elements as f64 values so that type legalization does not split
8571 // them up into i32 values.
8572 EVT VT = N->getValueType(0);
8573 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8576 SmallVector<SDValue, 8> Ops;
8577 unsigned NumElts = VT.getVectorNumElements();
8578 for (unsigned i = 0; i < NumElts; ++i) {
8579 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8581 // Make the DAGCombiner fold the bitcast.
8582 DCI.AddToWorklist(V.getNode());
8584 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8585 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8586 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8589 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8591 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8592 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8593 // At that time, we may have inserted bitcasts from integer to float.
8594 // If these bitcasts have survived DAGCombine, change the lowering of this
8595 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8596 // force to use floating point types.
8598 // Make sure we can change the type of the vector.
8599 // This is possible iff:
8600 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8601 // 1.1. Vector is used only once.
8602 // 1.2. Use is a bit convert to an integer type.
8603 // 2. The size of its operands are 32-bits (64-bits are not legal).
8604 EVT VT = N->getValueType(0);
8605 EVT EltVT = VT.getVectorElementType();
8607 // Check 1.1. and 2.
8608 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8611 // By construction, the input type must be float.
8612 assert(EltVT == MVT::f32 && "Unexpected type!");
8615 SDNode *Use = *N->use_begin();
8616 if (Use->getOpcode() != ISD::BITCAST ||
8617 Use->getValueType(0).isFloatingPoint())
8620 // Check profitability.
8621 // Model is, if more than half of the relevant operands are bitcast from
8622 // i32, turn the build_vector into a sequence of insert_vector_elt.
8623 // Relevant operands are everything that is not statically
8624 // (i.e., at compile time) bitcasted.
8625 unsigned NumOfBitCastedElts = 0;
8626 unsigned NumElts = VT.getVectorNumElements();
8627 unsigned NumOfRelevantElts = NumElts;
8628 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8629 SDValue Elt = N->getOperand(Idx);
8630 if (Elt->getOpcode() == ISD::BITCAST) {
8631 // Assume only bit cast to i32 will go away.
8632 if (Elt->getOperand(0).getValueType() == MVT::i32)
8633 ++NumOfBitCastedElts;
8634 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8635 // Constants are statically casted, thus do not count them as
8636 // relevant operands.
8637 --NumOfRelevantElts;
8640 // Check if more than half of the elements require a non-free bitcast.
8641 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8644 SelectionDAG &DAG = DCI.DAG;
8645 // Create the new vector type.
8646 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8647 // Check if the type is legal.
8648 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8649 if (!TLI.isTypeLegal(VecVT))
8653 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8654 // => BITCAST INSERT_VECTOR_ELT
8655 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8657 SDValue Vec = DAG.getUNDEF(VecVT);
8659 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8660 SDValue V = N->getOperand(Idx);
8661 if (V.getOpcode() == ISD::UNDEF)
8663 if (V.getOpcode() == ISD::BITCAST &&
8664 V->getOperand(0).getValueType() == MVT::i32)
8665 // Fold obvious case.
8666 V = V.getOperand(0);
8668 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8669 // Make the DAGCombiner fold the bitcasts.
8670 DCI.AddToWorklist(V.getNode());
8672 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8673 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8675 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8676 // Make the DAGCombiner fold the bitcasts.
8677 DCI.AddToWorklist(Vec.getNode());
8681 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8682 /// ISD::INSERT_VECTOR_ELT.
8683 static SDValue PerformInsertEltCombine(SDNode *N,
8684 TargetLowering::DAGCombinerInfo &DCI) {
8685 // Bitcast an i64 load inserted into a vector to f64.
8686 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8687 EVT VT = N->getValueType(0);
8688 SDNode *Elt = N->getOperand(1).getNode();
8689 if (VT.getVectorElementType() != MVT::i64 ||
8690 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8693 SelectionDAG &DAG = DCI.DAG;
8695 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8696 VT.getVectorNumElements());
8697 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8698 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8699 // Make the DAGCombiner fold the bitcasts.
8700 DCI.AddToWorklist(Vec.getNode());
8701 DCI.AddToWorklist(V.getNode());
8702 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8703 Vec, V, N->getOperand(2));
8704 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8707 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8708 /// ISD::VECTOR_SHUFFLE.
8709 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8710 // The LLVM shufflevector instruction does not require the shuffle mask
8711 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8712 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8713 // operands do not match the mask length, they are extended by concatenating
8714 // them with undef vectors. That is probably the right thing for other
8715 // targets, but for NEON it is better to concatenate two double-register
8716 // size vector operands into a single quad-register size vector. Do that
8717 // transformation here:
8718 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8719 // shuffle(concat(v1, v2), undef)
8720 SDValue Op0 = N->getOperand(0);
8721 SDValue Op1 = N->getOperand(1);
8722 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8723 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8724 Op0.getNumOperands() != 2 ||
8725 Op1.getNumOperands() != 2)
8727 SDValue Concat0Op1 = Op0.getOperand(1);
8728 SDValue Concat1Op1 = Op1.getOperand(1);
8729 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8730 Concat1Op1.getOpcode() != ISD::UNDEF)
8732 // Skip the transformation if any of the types are illegal.
8733 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8734 EVT VT = N->getValueType(0);
8735 if (!TLI.isTypeLegal(VT) ||
8736 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8737 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8740 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8741 Op0.getOperand(0), Op1.getOperand(0));
8742 // Translate the shuffle mask.
8743 SmallVector<int, 16> NewMask;
8744 unsigned NumElts = VT.getVectorNumElements();
8745 unsigned HalfElts = NumElts/2;
8746 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8747 for (unsigned n = 0; n < NumElts; ++n) {
8748 int MaskElt = SVN->getMaskElt(n);
8750 if (MaskElt < (int)HalfElts)
8752 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8753 NewElt = HalfElts + MaskElt - NumElts;
8754 NewMask.push_back(NewElt);
8756 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8757 DAG.getUNDEF(VT), NewMask.data());
8760 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8761 /// NEON load/store intrinsics to merge base address updates.
8762 static SDValue CombineBaseUpdate(SDNode *N,
8763 TargetLowering::DAGCombinerInfo &DCI) {
8764 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8767 SelectionDAG &DAG = DCI.DAG;
8768 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8769 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8770 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8771 SDValue Addr = N->getOperand(AddrOpIdx);
8773 // Search for a use of the address operand that is an increment.
8774 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8775 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8777 if (User->getOpcode() != ISD::ADD ||
8778 UI.getUse().getResNo() != Addr.getResNo())
8781 // Check that the add is independent of the load/store. Otherwise, folding
8782 // it would create a cycle.
8783 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8786 // Find the new opcode for the updating load/store.
8788 bool isLaneOp = false;
8789 unsigned NewOpc = 0;
8790 unsigned NumVecs = 0;
8792 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8794 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8795 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8797 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8799 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8801 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8803 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8804 NumVecs = 2; isLaneOp = true; break;
8805 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8806 NumVecs = 3; isLaneOp = true; break;
8807 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8808 NumVecs = 4; isLaneOp = true; break;
8809 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8810 NumVecs = 1; isLoad = false; break;
8811 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8812 NumVecs = 2; isLoad = false; break;
8813 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8814 NumVecs = 3; isLoad = false; break;
8815 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8816 NumVecs = 4; isLoad = false; break;
8817 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8818 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8819 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8820 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8821 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8822 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8826 switch (N->getOpcode()) {
8827 default: llvm_unreachable("unexpected opcode for Neon base update");
8828 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8829 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8830 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8834 // Find the size of memory referenced by the load/store.
8837 VecTy = N->getValueType(0);
8839 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8840 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8842 NumBytes /= VecTy.getVectorNumElements();
8844 // If the increment is a constant, it must match the memory ref size.
8845 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8846 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8847 uint64_t IncVal = CInc->getZExtValue();
8848 if (IncVal != NumBytes)
8850 } else if (NumBytes >= 3 * 16) {
8851 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8852 // separate instructions that make it harder to use a non-constant update.
8856 // Create the new updating load/store node.
8858 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8860 for (n = 0; n < NumResultVecs; ++n)
8862 Tys[n++] = MVT::i32;
8863 Tys[n] = MVT::Other;
8864 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8865 SmallVector<SDValue, 8> Ops;
8866 Ops.push_back(N->getOperand(0)); // incoming chain
8867 Ops.push_back(N->getOperand(AddrOpIdx));
8869 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8870 Ops.push_back(N->getOperand(i));
8872 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8873 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8874 Ops, MemInt->getMemoryVT(),
8875 MemInt->getMemOperand());
8878 std::vector<SDValue> NewResults;
8879 for (unsigned i = 0; i < NumResultVecs; ++i) {
8880 NewResults.push_back(SDValue(UpdN.getNode(), i));
8882 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8883 DCI.CombineTo(N, NewResults);
8884 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8891 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8892 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8893 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8895 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8896 SelectionDAG &DAG = DCI.DAG;
8897 EVT VT = N->getValueType(0);
8898 // vldN-dup instructions only support 64-bit vectors for N > 1.
8899 if (!VT.is64BitVector())
8902 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8903 SDNode *VLD = N->getOperand(0).getNode();
8904 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8906 unsigned NumVecs = 0;
8907 unsigned NewOpc = 0;
8908 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8909 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8911 NewOpc = ARMISD::VLD2DUP;
8912 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8914 NewOpc = ARMISD::VLD3DUP;
8915 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8917 NewOpc = ARMISD::VLD4DUP;
8922 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8923 // numbers match the load.
8924 unsigned VLDLaneNo =
8925 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8926 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8928 // Ignore uses of the chain result.
8929 if (UI.getUse().getResNo() == NumVecs)
8932 if (User->getOpcode() != ARMISD::VDUPLANE ||
8933 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8937 // Create the vldN-dup node.
8940 for (n = 0; n < NumVecs; ++n)
8942 Tys[n] = MVT::Other;
8943 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8944 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8945 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8946 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8947 Ops, VLDMemInt->getMemoryVT(),
8948 VLDMemInt->getMemOperand());
8951 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8953 unsigned ResNo = UI.getUse().getResNo();
8954 // Ignore uses of the chain result.
8955 if (ResNo == NumVecs)
8958 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8961 // Now the vldN-lane intrinsic is dead except for its chain result.
8962 // Update uses of the chain.
8963 std::vector<SDValue> VLDDupResults;
8964 for (unsigned n = 0; n < NumVecs; ++n)
8965 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8966 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8967 DCI.CombineTo(VLD, VLDDupResults);
8972 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8973 /// ARMISD::VDUPLANE.
8974 static SDValue PerformVDUPLANECombine(SDNode *N,
8975 TargetLowering::DAGCombinerInfo &DCI) {
8976 SDValue Op = N->getOperand(0);
8978 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8979 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8980 if (CombineVLDDUP(N, DCI))
8981 return SDValue(N, 0);
8983 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8984 // redundant. Ignore bit_converts for now; element sizes are checked below.
8985 while (Op.getOpcode() == ISD::BITCAST)
8986 Op = Op.getOperand(0);
8987 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8990 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8991 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8992 // The canonical VMOV for a zero vector uses a 32-bit element size.
8993 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8995 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8997 EVT VT = N->getValueType(0);
8998 if (EltSize > VT.getVectorElementType().getSizeInBits())
9001 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9004 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9005 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9006 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9010 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9012 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9017 APFloat APF = C->getValueAPF();
9018 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9019 != APFloat::opOK || !isExact)
9022 c0 = (I == 0) ? cN : c0;
9023 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9030 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9031 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9032 /// when the VMUL has a constant operand that is a power of 2.
9034 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9035 /// vmul.f32 d16, d17, d16
9036 /// vcvt.s32.f32 d16, d16
9038 /// vcvt.s32.f32 d16, d16, #3
9039 static SDValue PerformVCVTCombine(SDNode *N,
9040 TargetLowering::DAGCombinerInfo &DCI,
9041 const ARMSubtarget *Subtarget) {
9042 SelectionDAG &DAG = DCI.DAG;
9043 SDValue Op = N->getOperand(0);
9045 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9046 Op.getOpcode() != ISD::FMUL)
9050 SDValue N0 = Op->getOperand(0);
9051 SDValue ConstVec = Op->getOperand(1);
9052 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9054 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9055 !isConstVecPow2(ConstVec, isSigned, C))
9058 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9059 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9060 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9061 // These instructions only exist converting from f32 to i32. We can handle
9062 // smaller integers by generating an extra truncate, but larger ones would
9067 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9068 Intrinsic::arm_neon_vcvtfp2fxu;
9069 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9070 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9071 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9072 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9073 DAG.getConstant(Log2_64(C), MVT::i32));
9075 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9076 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9081 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9082 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9083 /// when the VDIV has a constant operand that is a power of 2.
9085 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9086 /// vcvt.f32.s32 d16, d16
9087 /// vdiv.f32 d16, d17, d16
9089 /// vcvt.f32.s32 d16, d16, #3
9090 static SDValue PerformVDIVCombine(SDNode *N,
9091 TargetLowering::DAGCombinerInfo &DCI,
9092 const ARMSubtarget *Subtarget) {
9093 SelectionDAG &DAG = DCI.DAG;
9094 SDValue Op = N->getOperand(0);
9095 unsigned OpOpcode = Op.getNode()->getOpcode();
9097 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9098 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9102 SDValue ConstVec = N->getOperand(1);
9103 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9105 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9106 !isConstVecPow2(ConstVec, isSigned, C))
9109 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9110 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9111 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9112 // These instructions only exist converting from i32 to f32. We can handle
9113 // smaller integers by generating an extra extend, but larger ones would
9118 SDValue ConvInput = Op.getOperand(0);
9119 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9120 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9121 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9122 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9125 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9126 Intrinsic::arm_neon_vcvtfxu2fp;
9127 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9129 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9130 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9133 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9134 /// operand of a vector shift operation, where all the elements of the
9135 /// build_vector must have the same constant integer value.
9136 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9137 // Ignore bit_converts.
9138 while (Op.getOpcode() == ISD::BITCAST)
9139 Op = Op.getOperand(0);
9140 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9141 APInt SplatBits, SplatUndef;
9142 unsigned SplatBitSize;
9144 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9145 HasAnyUndefs, ElementBits) ||
9146 SplatBitSize > ElementBits)
9148 Cnt = SplatBits.getSExtValue();
9152 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9153 /// operand of a vector shift left operation. That value must be in the range:
9154 /// 0 <= Value < ElementBits for a left shift; or
9155 /// 0 <= Value <= ElementBits for a long left shift.
9156 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9157 assert(VT.isVector() && "vector shift count is not a vector type");
9158 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9159 if (! getVShiftImm(Op, ElementBits, Cnt))
9161 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9164 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9165 /// operand of a vector shift right operation. For a shift opcode, the value
9166 /// is positive, but for an intrinsic the value count must be negative. The
9167 /// absolute value must be in the range:
9168 /// 1 <= |Value| <= ElementBits for a right shift; or
9169 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9170 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9172 assert(VT.isVector() && "vector shift count is not a vector type");
9173 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9174 if (! getVShiftImm(Op, ElementBits, Cnt))
9178 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9181 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9182 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9183 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9186 // Don't do anything for most intrinsics.
9189 // Vector shifts: check for immediate versions and lower them.
9190 // Note: This is done during DAG combining instead of DAG legalizing because
9191 // the build_vectors for 64-bit vector element shift counts are generally
9192 // not legal, and it is hard to see their values after they get legalized to
9193 // loads from a constant pool.
9194 case Intrinsic::arm_neon_vshifts:
9195 case Intrinsic::arm_neon_vshiftu:
9196 case Intrinsic::arm_neon_vrshifts:
9197 case Intrinsic::arm_neon_vrshiftu:
9198 case Intrinsic::arm_neon_vrshiftn:
9199 case Intrinsic::arm_neon_vqshifts:
9200 case Intrinsic::arm_neon_vqshiftu:
9201 case Intrinsic::arm_neon_vqshiftsu:
9202 case Intrinsic::arm_neon_vqshiftns:
9203 case Intrinsic::arm_neon_vqshiftnu:
9204 case Intrinsic::arm_neon_vqshiftnsu:
9205 case Intrinsic::arm_neon_vqrshiftns:
9206 case Intrinsic::arm_neon_vqrshiftnu:
9207 case Intrinsic::arm_neon_vqrshiftnsu: {
9208 EVT VT = N->getOperand(1).getValueType();
9210 unsigned VShiftOpc = 0;
9213 case Intrinsic::arm_neon_vshifts:
9214 case Intrinsic::arm_neon_vshiftu:
9215 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9216 VShiftOpc = ARMISD::VSHL;
9219 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9220 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9221 ARMISD::VSHRs : ARMISD::VSHRu);
9226 case Intrinsic::arm_neon_vrshifts:
9227 case Intrinsic::arm_neon_vrshiftu:
9228 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9232 case Intrinsic::arm_neon_vqshifts:
9233 case Intrinsic::arm_neon_vqshiftu:
9234 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9238 case Intrinsic::arm_neon_vqshiftsu:
9239 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9241 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9243 case Intrinsic::arm_neon_vrshiftn:
9244 case Intrinsic::arm_neon_vqshiftns:
9245 case Intrinsic::arm_neon_vqshiftnu:
9246 case Intrinsic::arm_neon_vqshiftnsu:
9247 case Intrinsic::arm_neon_vqrshiftns:
9248 case Intrinsic::arm_neon_vqrshiftnu:
9249 case Intrinsic::arm_neon_vqrshiftnsu:
9250 // Narrowing shifts require an immediate right shift.
9251 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9253 llvm_unreachable("invalid shift count for narrowing vector shift "
9257 llvm_unreachable("unhandled vector shift");
9261 case Intrinsic::arm_neon_vshifts:
9262 case Intrinsic::arm_neon_vshiftu:
9263 // Opcode already set above.
9265 case Intrinsic::arm_neon_vrshifts:
9266 VShiftOpc = ARMISD::VRSHRs; break;
9267 case Intrinsic::arm_neon_vrshiftu:
9268 VShiftOpc = ARMISD::VRSHRu; break;
9269 case Intrinsic::arm_neon_vrshiftn:
9270 VShiftOpc = ARMISD::VRSHRN; break;
9271 case Intrinsic::arm_neon_vqshifts:
9272 VShiftOpc = ARMISD::VQSHLs; break;
9273 case Intrinsic::arm_neon_vqshiftu:
9274 VShiftOpc = ARMISD::VQSHLu; break;
9275 case Intrinsic::arm_neon_vqshiftsu:
9276 VShiftOpc = ARMISD::VQSHLsu; break;
9277 case Intrinsic::arm_neon_vqshiftns:
9278 VShiftOpc = ARMISD::VQSHRNs; break;
9279 case Intrinsic::arm_neon_vqshiftnu:
9280 VShiftOpc = ARMISD::VQSHRNu; break;
9281 case Intrinsic::arm_neon_vqshiftnsu:
9282 VShiftOpc = ARMISD::VQSHRNsu; break;
9283 case Intrinsic::arm_neon_vqrshiftns:
9284 VShiftOpc = ARMISD::VQRSHRNs; break;
9285 case Intrinsic::arm_neon_vqrshiftnu:
9286 VShiftOpc = ARMISD::VQRSHRNu; break;
9287 case Intrinsic::arm_neon_vqrshiftnsu:
9288 VShiftOpc = ARMISD::VQRSHRNsu; break;
9291 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9292 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9295 case Intrinsic::arm_neon_vshiftins: {
9296 EVT VT = N->getOperand(1).getValueType();
9298 unsigned VShiftOpc = 0;
9300 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9301 VShiftOpc = ARMISD::VSLI;
9302 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9303 VShiftOpc = ARMISD::VSRI;
9305 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9308 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9309 N->getOperand(1), N->getOperand(2),
9310 DAG.getConstant(Cnt, MVT::i32));
9313 case Intrinsic::arm_neon_vqrshifts:
9314 case Intrinsic::arm_neon_vqrshiftu:
9315 // No immediate versions of these to check for.
9322 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9323 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9324 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9325 /// vector element shift counts are generally not legal, and it is hard to see
9326 /// their values after they get legalized to loads from a constant pool.
9327 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9328 const ARMSubtarget *ST) {
9329 EVT VT = N->getValueType(0);
9330 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9331 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9332 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9333 SDValue N1 = N->getOperand(1);
9334 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9335 SDValue N0 = N->getOperand(0);
9336 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9337 DAG.MaskedValueIsZero(N0.getOperand(0),
9338 APInt::getHighBitsSet(32, 16)))
9339 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9343 // Nothing to be done for scalar shifts.
9344 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9345 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9348 assert(ST->hasNEON() && "unexpected vector shift");
9351 switch (N->getOpcode()) {
9352 default: llvm_unreachable("unexpected shift opcode");
9355 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9356 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9357 DAG.getConstant(Cnt, MVT::i32));
9362 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9363 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9364 ARMISD::VSHRs : ARMISD::VSHRu);
9365 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9366 DAG.getConstant(Cnt, MVT::i32));
9372 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9373 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9374 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9375 const ARMSubtarget *ST) {
9376 SDValue N0 = N->getOperand(0);
9378 // Check for sign- and zero-extensions of vector extract operations of 8-
9379 // and 16-bit vector elements. NEON supports these directly. They are
9380 // handled during DAG combining because type legalization will promote them
9381 // to 32-bit types and it is messy to recognize the operations after that.
9382 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9383 SDValue Vec = N0.getOperand(0);
9384 SDValue Lane = N0.getOperand(1);
9385 EVT VT = N->getValueType(0);
9386 EVT EltVT = N0.getValueType();
9387 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9389 if (VT == MVT::i32 &&
9390 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9391 TLI.isTypeLegal(Vec.getValueType()) &&
9392 isa<ConstantSDNode>(Lane)) {
9395 switch (N->getOpcode()) {
9396 default: llvm_unreachable("unexpected opcode");
9397 case ISD::SIGN_EXTEND:
9398 Opc = ARMISD::VGETLANEs;
9400 case ISD::ZERO_EXTEND:
9401 case ISD::ANY_EXTEND:
9402 Opc = ARMISD::VGETLANEu;
9405 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9412 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9413 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9414 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9415 const ARMSubtarget *ST) {
9416 // If the target supports NEON, try to use vmax/vmin instructions for f32
9417 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9418 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9419 // a NaN; only do the transformation when it matches that behavior.
9421 // For now only do this when using NEON for FP operations; if using VFP, it
9422 // is not obvious that the benefit outweighs the cost of switching to the
9424 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9425 N->getValueType(0) != MVT::f32)
9428 SDValue CondLHS = N->getOperand(0);
9429 SDValue CondRHS = N->getOperand(1);
9430 SDValue LHS = N->getOperand(2);
9431 SDValue RHS = N->getOperand(3);
9432 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9434 unsigned Opcode = 0;
9436 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9437 IsReversed = false; // x CC y ? x : y
9438 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9439 IsReversed = true ; // x CC y ? y : x
9453 // If LHS is NaN, an ordered comparison will be false and the result will
9454 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9455 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9456 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9457 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9459 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9460 // will return -0, so vmin can only be used for unsafe math or if one of
9461 // the operands is known to be nonzero.
9462 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9463 !DAG.getTarget().Options.UnsafeFPMath &&
9464 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9466 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9475 // If LHS is NaN, an ordered comparison will be false and the result will
9476 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9477 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9478 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9479 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9481 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9482 // will return +0, so vmax can only be used for unsafe math or if one of
9483 // the operands is known to be nonzero.
9484 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9485 !DAG.getTarget().Options.UnsafeFPMath &&
9486 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9488 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9494 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9497 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9499 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9500 SDValue Cmp = N->getOperand(4);
9501 if (Cmp.getOpcode() != ARMISD::CMPZ)
9502 // Only looking at EQ and NE cases.
9505 EVT VT = N->getValueType(0);
9507 SDValue LHS = Cmp.getOperand(0);
9508 SDValue RHS = Cmp.getOperand(1);
9509 SDValue FalseVal = N->getOperand(0);
9510 SDValue TrueVal = N->getOperand(1);
9511 SDValue ARMcc = N->getOperand(2);
9512 ARMCC::CondCodes CC =
9513 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9531 /// FIXME: Turn this into a target neutral optimization?
9533 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9534 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9535 N->getOperand(3), Cmp);
9536 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9538 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9539 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9540 N->getOperand(3), NewCmp);
9543 if (Res.getNode()) {
9544 APInt KnownZero, KnownOne;
9545 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9546 // Capture demanded bits information that would be otherwise lost.
9547 if (KnownZero == 0xfffffffe)
9548 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9549 DAG.getValueType(MVT::i1));
9550 else if (KnownZero == 0xffffff00)
9551 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9552 DAG.getValueType(MVT::i8));
9553 else if (KnownZero == 0xffff0000)
9554 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9555 DAG.getValueType(MVT::i16));
9561 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9562 DAGCombinerInfo &DCI) const {
9563 switch (N->getOpcode()) {
9565 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9566 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9567 case ISD::SUB: return PerformSUBCombine(N, DCI);
9568 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9569 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9570 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9571 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9572 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9573 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9574 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9575 case ISD::STORE: return PerformSTORECombine(N, DCI);
9576 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9577 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9578 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9579 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9580 case ISD::FP_TO_SINT:
9581 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9582 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9583 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9586 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9587 case ISD::SIGN_EXTEND:
9588 case ISD::ZERO_EXTEND:
9589 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9590 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9591 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9592 case ARMISD::VLD2DUP:
9593 case ARMISD::VLD3DUP:
9594 case ARMISD::VLD4DUP:
9595 return CombineBaseUpdate(N, DCI);
9596 case ARMISD::BUILD_VECTOR:
9597 return PerformARMBUILD_VECTORCombine(N, DCI);
9598 case ISD::INTRINSIC_VOID:
9599 case ISD::INTRINSIC_W_CHAIN:
9600 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9601 case Intrinsic::arm_neon_vld1:
9602 case Intrinsic::arm_neon_vld2:
9603 case Intrinsic::arm_neon_vld3:
9604 case Intrinsic::arm_neon_vld4:
9605 case Intrinsic::arm_neon_vld2lane:
9606 case Intrinsic::arm_neon_vld3lane:
9607 case Intrinsic::arm_neon_vld4lane:
9608 case Intrinsic::arm_neon_vst1:
9609 case Intrinsic::arm_neon_vst2:
9610 case Intrinsic::arm_neon_vst3:
9611 case Intrinsic::arm_neon_vst4:
9612 case Intrinsic::arm_neon_vst2lane:
9613 case Intrinsic::arm_neon_vst3lane:
9614 case Intrinsic::arm_neon_vst4lane:
9615 return CombineBaseUpdate(N, DCI);
9623 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9625 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9628 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9630 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9631 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9633 switch (VT.getSimpleVT().SimpleTy) {
9639 // Unaligned access can use (for example) LRDB, LRDH, LDR
9640 if (AllowsUnaligned) {
9642 *Fast = Subtarget->hasV7Ops();
9649 // For any little-endian targets with neon, we can support unaligned ld/st
9650 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9651 // A big-endian target may also explicitly support unaligned accesses
9652 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9662 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9663 unsigned AlignCheck) {
9664 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9665 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9668 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9669 unsigned DstAlign, unsigned SrcAlign,
9670 bool IsMemset, bool ZeroMemset,
9672 MachineFunction &MF) const {
9673 const Function *F = MF.getFunction();
9675 // See if we can use NEON instructions for this...
9676 if ((!IsMemset || ZeroMemset) &&
9677 Subtarget->hasNEON() &&
9678 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9679 Attribute::NoImplicitFloat)) {
9682 (memOpAlign(SrcAlign, DstAlign, 16) ||
9683 (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9685 } else if (Size >= 8 &&
9686 (memOpAlign(SrcAlign, DstAlign, 8) ||
9687 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9692 // Lowering to i32/i16 if the size permits.
9698 // Let the target-independent logic figure it out.
9702 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9703 if (Val.getOpcode() != ISD::LOAD)
9706 EVT VT1 = Val.getValueType();
9707 if (!VT1.isSimple() || !VT1.isInteger() ||
9708 !VT2.isSimple() || !VT2.isInteger())
9711 switch (VT1.getSimpleVT().SimpleTy) {
9716 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9723 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9724 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9727 if (!isTypeLegal(EVT::getEVT(Ty1)))
9730 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9732 // Assuming the caller doesn't have a zeroext or signext return parameter,
9733 // truncation all the way down to i1 is valid.
9738 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9743 switch (VT.getSimpleVT().SimpleTy) {
9744 default: return false;
9759 if ((V & (Scale - 1)) != 0)
9762 return V == (V & ((1LL << 5) - 1));
9765 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9766 const ARMSubtarget *Subtarget) {
9773 switch (VT.getSimpleVT().SimpleTy) {
9774 default: return false;
9779 // + imm12 or - imm8
9781 return V == (V & ((1LL << 8) - 1));
9782 return V == (V & ((1LL << 12) - 1));
9785 // Same as ARM mode. FIXME: NEON?
9786 if (!Subtarget->hasVFP2())
9791 return V == (V & ((1LL << 8) - 1));
9795 /// isLegalAddressImmediate - Return true if the integer value can be used
9796 /// as the offset of the target addressing mode for load / store of the
9798 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9799 const ARMSubtarget *Subtarget) {
9806 if (Subtarget->isThumb1Only())
9807 return isLegalT1AddressImmediate(V, VT);
9808 else if (Subtarget->isThumb2())
9809 return isLegalT2AddressImmediate(V, VT, Subtarget);
9814 switch (VT.getSimpleVT().SimpleTy) {
9815 default: return false;
9820 return V == (V & ((1LL << 12) - 1));
9823 return V == (V & ((1LL << 8) - 1));
9826 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9831 return V == (V & ((1LL << 8) - 1));
9835 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9837 int Scale = AM.Scale;
9841 switch (VT.getSimpleVT().SimpleTy) {
9842 default: return false;
9851 return Scale == 2 || Scale == 4 || Scale == 8;
9854 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9858 // Note, we allow "void" uses (basically, uses that aren't loads or
9859 // stores), because arm allows folding a scale into many arithmetic
9860 // operations. This should be made more precise and revisited later.
9862 // Allow r << imm, but the imm has to be a multiple of two.
9863 if (Scale & 1) return false;
9864 return isPowerOf2_32(Scale);
9868 /// isLegalAddressingMode - Return true if the addressing mode represented
9869 /// by AM is legal for this target, for a load/store of the specified type.
9870 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9872 EVT VT = getValueType(Ty, true);
9873 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9876 // Can never fold addr of global into load/store.
9881 case 0: // no scale reg, must be "r+i" or "r", or "i".
9884 if (Subtarget->isThumb1Only())
9888 // ARM doesn't support any R+R*scale+imm addr modes.
9895 if (Subtarget->isThumb2())
9896 return isLegalT2ScaledAddressingMode(AM, VT);
9898 int Scale = AM.Scale;
9899 switch (VT.getSimpleVT().SimpleTy) {
9900 default: return false;
9904 if (Scale < 0) Scale = -Scale;
9908 return isPowerOf2_32(Scale & ~1);
9912 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9917 // Note, we allow "void" uses (basically, uses that aren't loads or
9918 // stores), because arm allows folding a scale into many arithmetic
9919 // operations. This should be made more precise and revisited later.
9921 // Allow r << imm, but the imm has to be a multiple of two.
9922 if (Scale & 1) return false;
9923 return isPowerOf2_32(Scale);
9929 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9930 /// icmp immediate, that is the target has icmp instructions which can compare
9931 /// a register against the immediate without having to materialize the
9932 /// immediate into a register.
9933 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9934 // Thumb2 and ARM modes can use cmn for negative immediates.
9935 if (!Subtarget->isThumb())
9936 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9937 if (Subtarget->isThumb2())
9938 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9939 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9940 return Imm >= 0 && Imm <= 255;
9943 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9944 /// *or sub* immediate, that is the target has add or sub instructions which can
9945 /// add a register with the immediate without having to materialize the
9946 /// immediate into a register.
9947 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9948 // Same encoding for add/sub, just flip the sign.
9949 int64_t AbsImm = llvm::abs64(Imm);
9950 if (!Subtarget->isThumb())
9951 return ARM_AM::getSOImmVal(AbsImm) != -1;
9952 if (Subtarget->isThumb2())
9953 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9954 // Thumb1 only has 8-bit unsigned immediate.
9955 return AbsImm >= 0 && AbsImm <= 255;
9958 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9959 bool isSEXTLoad, SDValue &Base,
9960 SDValue &Offset, bool &isInc,
9961 SelectionDAG &DAG) {
9962 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9965 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9967 Base = Ptr->getOperand(0);
9968 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9969 int RHSC = (int)RHS->getZExtValue();
9970 if (RHSC < 0 && RHSC > -256) {
9971 assert(Ptr->getOpcode() == ISD::ADD);
9973 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9977 isInc = (Ptr->getOpcode() == ISD::ADD);
9978 Offset = Ptr->getOperand(1);
9980 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9982 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9983 int RHSC = (int)RHS->getZExtValue();
9984 if (RHSC < 0 && RHSC > -0x1000) {
9985 assert(Ptr->getOpcode() == ISD::ADD);
9987 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9988 Base = Ptr->getOperand(0);
9993 if (Ptr->getOpcode() == ISD::ADD) {
9995 ARM_AM::ShiftOpc ShOpcVal=
9996 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9997 if (ShOpcVal != ARM_AM::no_shift) {
9998 Base = Ptr->getOperand(1);
9999 Offset = Ptr->getOperand(0);
10001 Base = Ptr->getOperand(0);
10002 Offset = Ptr->getOperand(1);
10007 isInc = (Ptr->getOpcode() == ISD::ADD);
10008 Base = Ptr->getOperand(0);
10009 Offset = Ptr->getOperand(1);
10013 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10017 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10018 bool isSEXTLoad, SDValue &Base,
10019 SDValue &Offset, bool &isInc,
10020 SelectionDAG &DAG) {
10021 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10024 Base = Ptr->getOperand(0);
10025 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10026 int RHSC = (int)RHS->getZExtValue();
10027 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10028 assert(Ptr->getOpcode() == ISD::ADD);
10030 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10032 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10033 isInc = Ptr->getOpcode() == ISD::ADD;
10034 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10042 /// getPreIndexedAddressParts - returns true by value, base pointer and
10043 /// offset pointer and addressing mode by reference if the node's address
10044 /// can be legally represented as pre-indexed load / store address.
10046 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10048 ISD::MemIndexedMode &AM,
10049 SelectionDAG &DAG) const {
10050 if (Subtarget->isThumb1Only())
10055 bool isSEXTLoad = false;
10056 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10057 Ptr = LD->getBasePtr();
10058 VT = LD->getMemoryVT();
10059 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10060 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10061 Ptr = ST->getBasePtr();
10062 VT = ST->getMemoryVT();
10067 bool isLegal = false;
10068 if (Subtarget->isThumb2())
10069 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10070 Offset, isInc, DAG);
10072 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10073 Offset, isInc, DAG);
10077 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10081 /// getPostIndexedAddressParts - returns true by value, base pointer and
10082 /// offset pointer and addressing mode by reference if this node can be
10083 /// combined with a load / store to form a post-indexed load / store.
10084 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10087 ISD::MemIndexedMode &AM,
10088 SelectionDAG &DAG) const {
10089 if (Subtarget->isThumb1Only())
10094 bool isSEXTLoad = false;
10095 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10096 VT = LD->getMemoryVT();
10097 Ptr = LD->getBasePtr();
10098 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10099 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10100 VT = ST->getMemoryVT();
10101 Ptr = ST->getBasePtr();
10106 bool isLegal = false;
10107 if (Subtarget->isThumb2())
10108 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10111 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10117 // Swap base ptr and offset to catch more post-index load / store when
10118 // it's legal. In Thumb2 mode, offset must be an immediate.
10119 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10120 !Subtarget->isThumb2())
10121 std::swap(Base, Offset);
10123 // Post-indexed load / store update the base pointer.
10128 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10132 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10135 const SelectionDAG &DAG,
10136 unsigned Depth) const {
10137 unsigned BitWidth = KnownOne.getBitWidth();
10138 KnownZero = KnownOne = APInt(BitWidth, 0);
10139 switch (Op.getOpcode()) {
10145 // These nodes' second result is a boolean
10146 if (Op.getResNo() == 0)
10148 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10150 case ARMISD::CMOV: {
10151 // Bits are known zero/one if known on the LHS and RHS.
10152 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10153 if (KnownZero == 0 && KnownOne == 0) return;
10155 APInt KnownZeroRHS, KnownOneRHS;
10156 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10157 KnownZero &= KnownZeroRHS;
10158 KnownOne &= KnownOneRHS;
10161 case ISD::INTRINSIC_W_CHAIN: {
10162 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10163 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10166 case Intrinsic::arm_ldaex:
10167 case Intrinsic::arm_ldrex: {
10168 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10169 unsigned MemBits = VT.getScalarType().getSizeInBits();
10170 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10178 //===----------------------------------------------------------------------===//
10179 // ARM Inline Assembly Support
10180 //===----------------------------------------------------------------------===//
10182 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10183 // Looking for "rev" which is V6+.
10184 if (!Subtarget->hasV6Ops())
10187 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10188 std::string AsmStr = IA->getAsmString();
10189 SmallVector<StringRef, 4> AsmPieces;
10190 SplitString(AsmStr, AsmPieces, ";\n");
10192 switch (AsmPieces.size()) {
10193 default: return false;
10195 AsmStr = AsmPieces[0];
10197 SplitString(AsmStr, AsmPieces, " \t,");
10200 if (AsmPieces.size() == 3 &&
10201 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10202 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10203 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10204 if (Ty && Ty->getBitWidth() == 32)
10205 return IntrinsicLowering::LowerToByteSwap(CI);
10213 /// getConstraintType - Given a constraint letter, return the type of
10214 /// constraint it is for this target.
10215 ARMTargetLowering::ConstraintType
10216 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10217 if (Constraint.size() == 1) {
10218 switch (Constraint[0]) {
10220 case 'l': return C_RegisterClass;
10221 case 'w': return C_RegisterClass;
10222 case 'h': return C_RegisterClass;
10223 case 'x': return C_RegisterClass;
10224 case 't': return C_RegisterClass;
10225 case 'j': return C_Other; // Constant for movw.
10226 // An address with a single base register. Due to the way we
10227 // currently handle addresses it is the same as an 'r' memory constraint.
10228 case 'Q': return C_Memory;
10230 } else if (Constraint.size() == 2) {
10231 switch (Constraint[0]) {
10233 // All 'U+' constraints are addresses.
10234 case 'U': return C_Memory;
10237 return TargetLowering::getConstraintType(Constraint);
10240 /// Examine constraint type and operand type and determine a weight value.
10241 /// This object must already have been set up with the operand type
10242 /// and the current alternative constraint selected.
10243 TargetLowering::ConstraintWeight
10244 ARMTargetLowering::getSingleConstraintMatchWeight(
10245 AsmOperandInfo &info, const char *constraint) const {
10246 ConstraintWeight weight = CW_Invalid;
10247 Value *CallOperandVal = info.CallOperandVal;
10248 // If we don't have a value, we can't do a match,
10249 // but allow it at the lowest weight.
10250 if (!CallOperandVal)
10252 Type *type = CallOperandVal->getType();
10253 // Look at the constraint type.
10254 switch (*constraint) {
10256 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10259 if (type->isIntegerTy()) {
10260 if (Subtarget->isThumb())
10261 weight = CW_SpecificReg;
10263 weight = CW_Register;
10267 if (type->isFloatingPointTy())
10268 weight = CW_Register;
10274 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10276 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10278 if (Constraint.size() == 1) {
10279 // GCC ARM Constraint Letters
10280 switch (Constraint[0]) {
10281 case 'l': // Low regs or general regs.
10282 if (Subtarget->isThumb())
10283 return RCPair(0U, &ARM::tGPRRegClass);
10284 return RCPair(0U, &ARM::GPRRegClass);
10285 case 'h': // High regs or no regs.
10286 if (Subtarget->isThumb())
10287 return RCPair(0U, &ARM::hGPRRegClass);
10290 return RCPair(0U, &ARM::GPRRegClass);
10292 if (VT == MVT::Other)
10294 if (VT == MVT::f32)
10295 return RCPair(0U, &ARM::SPRRegClass);
10296 if (VT.getSizeInBits() == 64)
10297 return RCPair(0U, &ARM::DPRRegClass);
10298 if (VT.getSizeInBits() == 128)
10299 return RCPair(0U, &ARM::QPRRegClass);
10302 if (VT == MVT::Other)
10304 if (VT == MVT::f32)
10305 return RCPair(0U, &ARM::SPR_8RegClass);
10306 if (VT.getSizeInBits() == 64)
10307 return RCPair(0U, &ARM::DPR_8RegClass);
10308 if (VT.getSizeInBits() == 128)
10309 return RCPair(0U, &ARM::QPR_8RegClass);
10312 if (VT == MVT::f32)
10313 return RCPair(0U, &ARM::SPRRegClass);
10317 if (StringRef("{cc}").equals_lower(Constraint))
10318 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10320 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10323 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10324 /// vector. If it is invalid, don't add anything to Ops.
10325 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10326 std::string &Constraint,
10327 std::vector<SDValue>&Ops,
10328 SelectionDAG &DAG) const {
10331 // Currently only support length 1 constraints.
10332 if (Constraint.length() != 1) return;
10334 char ConstraintLetter = Constraint[0];
10335 switch (ConstraintLetter) {
10338 case 'I': case 'J': case 'K': case 'L':
10339 case 'M': case 'N': case 'O':
10340 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10344 int64_t CVal64 = C->getSExtValue();
10345 int CVal = (int) CVal64;
10346 // None of these constraints allow values larger than 32 bits. Check
10347 // that the value fits in an int.
10348 if (CVal != CVal64)
10351 switch (ConstraintLetter) {
10353 // Constant suitable for movw, must be between 0 and
10355 if (Subtarget->hasV6T2Ops())
10356 if (CVal >= 0 && CVal <= 65535)
10360 if (Subtarget->isThumb1Only()) {
10361 // This must be a constant between 0 and 255, for ADD
10363 if (CVal >= 0 && CVal <= 255)
10365 } else if (Subtarget->isThumb2()) {
10366 // A constant that can be used as an immediate value in a
10367 // data-processing instruction.
10368 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10371 // A constant that can be used as an immediate value in a
10372 // data-processing instruction.
10373 if (ARM_AM::getSOImmVal(CVal) != -1)
10379 if (Subtarget->isThumb()) { // FIXME thumb2
10380 // This must be a constant between -255 and -1, for negated ADD
10381 // immediates. This can be used in GCC with an "n" modifier that
10382 // prints the negated value, for use with SUB instructions. It is
10383 // not useful otherwise but is implemented for compatibility.
10384 if (CVal >= -255 && CVal <= -1)
10387 // This must be a constant between -4095 and 4095. It is not clear
10388 // what this constraint is intended for. Implemented for
10389 // compatibility with GCC.
10390 if (CVal >= -4095 && CVal <= 4095)
10396 if (Subtarget->isThumb1Only()) {
10397 // A 32-bit value where only one byte has a nonzero value. Exclude
10398 // zero to match GCC. This constraint is used by GCC internally for
10399 // constants that can be loaded with a move/shift combination.
10400 // It is not useful otherwise but is implemented for compatibility.
10401 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10403 } else if (Subtarget->isThumb2()) {
10404 // A constant whose bitwise inverse can be used as an immediate
10405 // value in a data-processing instruction. This can be used in GCC
10406 // with a "B" modifier that prints the inverted value, for use with
10407 // BIC and MVN instructions. It is not useful otherwise but is
10408 // implemented for compatibility.
10409 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10412 // A constant whose bitwise inverse can be used as an immediate
10413 // value in a data-processing instruction. This can be used in GCC
10414 // with a "B" modifier that prints the inverted value, for use with
10415 // BIC and MVN instructions. It is not useful otherwise but is
10416 // implemented for compatibility.
10417 if (ARM_AM::getSOImmVal(~CVal) != -1)
10423 if (Subtarget->isThumb1Only()) {
10424 // This must be a constant between -7 and 7,
10425 // for 3-operand ADD/SUB immediate instructions.
10426 if (CVal >= -7 && CVal < 7)
10428 } else if (Subtarget->isThumb2()) {
10429 // A constant whose negation can be used as an immediate value in a
10430 // data-processing instruction. This can be used in GCC with an "n"
10431 // modifier that prints the negated value, for use with SUB
10432 // instructions. It is not useful otherwise but is implemented for
10434 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10437 // A constant whose negation can be used as an immediate value in a
10438 // data-processing instruction. This can be used in GCC with an "n"
10439 // modifier that prints the negated value, for use with SUB
10440 // instructions. It is not useful otherwise but is implemented for
10442 if (ARM_AM::getSOImmVal(-CVal) != -1)
10448 if (Subtarget->isThumb()) { // FIXME thumb2
10449 // This must be a multiple of 4 between 0 and 1020, for
10450 // ADD sp + immediate.
10451 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10454 // A power of two or a constant between 0 and 32. This is used in
10455 // GCC for the shift amount on shifted register operands, but it is
10456 // useful in general for any shift amounts.
10457 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10463 if (Subtarget->isThumb()) { // FIXME thumb2
10464 // This must be a constant between 0 and 31, for shift amounts.
10465 if (CVal >= 0 && CVal <= 31)
10471 if (Subtarget->isThumb()) { // FIXME thumb2
10472 // This must be a multiple of 4 between -508 and 508, for
10473 // ADD/SUB sp = sp + immediate.
10474 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10479 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10483 if (Result.getNode()) {
10484 Ops.push_back(Result);
10487 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10490 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10491 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10492 unsigned Opcode = Op->getOpcode();
10493 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10494 "Invalid opcode for Div/Rem lowering");
10495 bool isSigned = (Opcode == ISD::SDIVREM);
10496 EVT VT = Op->getValueType(0);
10497 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10500 switch (VT.getSimpleVT().SimpleTy) {
10501 default: llvm_unreachable("Unexpected request for libcall!");
10502 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10503 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10504 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10505 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10508 SDValue InChain = DAG.getEntryNode();
10510 TargetLowering::ArgListTy Args;
10511 TargetLowering::ArgListEntry Entry;
10512 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10513 EVT ArgVT = Op->getOperand(i).getValueType();
10514 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10515 Entry.Node = Op->getOperand(i);
10517 Entry.isSExt = isSigned;
10518 Entry.isZExt = !isSigned;
10519 Args.push_back(Entry);
10522 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10525 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10529 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10530 0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10531 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10532 Callee, Args, DAG, dl);
10533 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10535 return CallInfo.first;
10539 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10540 // The ARM target isn't yet aware of offsets.
10544 bool ARM::isBitFieldInvertedMask(unsigned v) {
10545 if (v == 0xffffffff)
10548 // there can be 1's on either or both "outsides", all the "inside"
10549 // bits must be 0's
10550 unsigned TO = CountTrailingOnes_32(v);
10551 unsigned LO = CountLeadingOnes_32(v);
10552 v = (v >> TO) << TO;
10553 v = (v << LO) >> LO;
10557 /// isFPImmLegal - Returns true if the target can instruction select the
10558 /// specified FP immediate natively. If false, the legalizer will
10559 /// materialize the FP immediate as a load from a constant pool.
10560 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10561 if (!Subtarget->hasVFP3())
10563 if (VT == MVT::f32)
10564 return ARM_AM::getFP32Imm(Imm) != -1;
10565 if (VT == MVT::f64)
10566 return ARM_AM::getFP64Imm(Imm) != -1;
10570 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10571 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10572 /// specified in the intrinsic calls.
10573 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10575 unsigned Intrinsic) const {
10576 switch (Intrinsic) {
10577 case Intrinsic::arm_neon_vld1:
10578 case Intrinsic::arm_neon_vld2:
10579 case Intrinsic::arm_neon_vld3:
10580 case Intrinsic::arm_neon_vld4:
10581 case Intrinsic::arm_neon_vld2lane:
10582 case Intrinsic::arm_neon_vld3lane:
10583 case Intrinsic::arm_neon_vld4lane: {
10584 Info.opc = ISD::INTRINSIC_W_CHAIN;
10585 // Conservatively set memVT to the entire set of vectors loaded.
10586 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10587 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10588 Info.ptrVal = I.getArgOperand(0);
10590 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10591 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10592 Info.vol = false; // volatile loads with NEON intrinsics not supported
10593 Info.readMem = true;
10594 Info.writeMem = false;
10597 case Intrinsic::arm_neon_vst1:
10598 case Intrinsic::arm_neon_vst2:
10599 case Intrinsic::arm_neon_vst3:
10600 case Intrinsic::arm_neon_vst4:
10601 case Intrinsic::arm_neon_vst2lane:
10602 case Intrinsic::arm_neon_vst3lane:
10603 case Intrinsic::arm_neon_vst4lane: {
10604 Info.opc = ISD::INTRINSIC_VOID;
10605 // Conservatively set memVT to the entire set of vectors stored.
10606 unsigned NumElts = 0;
10607 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10608 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10609 if (!ArgTy->isVectorTy())
10611 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10613 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10614 Info.ptrVal = I.getArgOperand(0);
10616 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10617 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10618 Info.vol = false; // volatile stores with NEON intrinsics not supported
10619 Info.readMem = false;
10620 Info.writeMem = true;
10623 case Intrinsic::arm_ldaex:
10624 case Intrinsic::arm_ldrex: {
10625 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10626 Info.opc = ISD::INTRINSIC_W_CHAIN;
10627 Info.memVT = MVT::getVT(PtrTy->getElementType());
10628 Info.ptrVal = I.getArgOperand(0);
10630 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10632 Info.readMem = true;
10633 Info.writeMem = false;
10636 case Intrinsic::arm_stlex:
10637 case Intrinsic::arm_strex: {
10638 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10639 Info.opc = ISD::INTRINSIC_W_CHAIN;
10640 Info.memVT = MVT::getVT(PtrTy->getElementType());
10641 Info.ptrVal = I.getArgOperand(1);
10643 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10645 Info.readMem = false;
10646 Info.writeMem = true;
10649 case Intrinsic::arm_stlexd:
10650 case Intrinsic::arm_strexd: {
10651 Info.opc = ISD::INTRINSIC_W_CHAIN;
10652 Info.memVT = MVT::i64;
10653 Info.ptrVal = I.getArgOperand(2);
10657 Info.readMem = false;
10658 Info.writeMem = true;
10661 case Intrinsic::arm_ldaexd:
10662 case Intrinsic::arm_ldrexd: {
10663 Info.opc = ISD::INTRINSIC_W_CHAIN;
10664 Info.memVT = MVT::i64;
10665 Info.ptrVal = I.getArgOperand(0);
10669 Info.readMem = true;
10670 Info.writeMem = false;
10680 /// \brief Returns true if it is beneficial to convert a load of a constant
10681 /// to just the constant itself.
10682 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10684 assert(Ty->isIntegerTy());
10686 unsigned Bits = Ty->getPrimitiveSizeInBits();
10687 if (Bits == 0 || Bits > 32)
10692 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10693 // Loads and stores less than 64-bits are already atomic; ones above that
10694 // are doomed anyway, so defer to the default libcall and blame the OS when
10695 // things go wrong:
10696 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10697 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10698 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10699 return LI->getType()->getPrimitiveSizeInBits() == 64;
10701 // For the real atomic operations, we have ldrex/strex up to 64 bits.
10702 return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10705 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10706 AtomicOrdering Ord) const {
10707 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10708 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10710 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10712 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10713 // intrinsic must return {i32, i32} and we have to recombine them into a
10714 // single i64 here.
10715 if (ValTy->getPrimitiveSizeInBits() == 64) {
10716 Intrinsic::ID Int =
10717 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10718 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10720 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10721 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10723 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10724 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10725 if (!Subtarget->isLittle())
10726 std::swap (Lo, Hi);
10727 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10728 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10729 return Builder.CreateOr(
10730 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10733 Type *Tys[] = { Addr->getType() };
10734 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10735 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10737 return Builder.CreateTruncOrBitCast(
10738 Builder.CreateCall(Ldrex, Addr),
10739 cast<PointerType>(Addr->getType())->getElementType());
10742 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10744 AtomicOrdering Ord) const {
10745 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10747 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10749 // Since the intrinsics must have legal type, the i64 intrinsics take two
10750 // parameters: "i32, i32". We must marshal Val into the appropriate form
10751 // before the call.
10752 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10753 Intrinsic::ID Int =
10754 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10755 Function *Strex = Intrinsic::getDeclaration(M, Int);
10756 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10758 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10759 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10760 if (!Subtarget->isLittle())
10761 std::swap (Lo, Hi);
10762 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10763 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10766 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10767 Type *Tys[] = { Addr->getType() };
10768 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10770 return Builder.CreateCall2(
10771 Strex, Builder.CreateZExtOrBitCast(
10772 Val, Strex->getFunctionType()->getParamType(0)),
10784 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10785 uint64_t &Members) {
10786 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10787 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10788 uint64_t SubMembers = 0;
10789 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10791 Members += SubMembers;
10793 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10794 uint64_t SubMembers = 0;
10795 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10797 Members += SubMembers * AT->getNumElements();
10798 } else if (Ty->isFloatTy()) {
10799 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10803 } else if (Ty->isDoubleTy()) {
10804 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10808 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10815 return VT->getBitWidth() == 64;
10817 return VT->getBitWidth() == 128;
10819 switch (VT->getBitWidth()) {
10832 return (Members > 0 && Members <= 4);
10835 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10836 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10837 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10838 if (getEffectiveCallingConv(CallConv, isVarArg) ==
10839 CallingConv::ARM_AAPCS_VFP) {
10840 HABaseType Base = HA_UNKNOWN;
10841 uint64_t Members = 0;
10842 bool result = isHomogeneousAggregate(Ty, Base, Members);
10843 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");