1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CallingConv.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Constants.h"
39 #include "llvm/Function.h"
40 #include "llvm/GlobalValue.h"
41 #include "llvm/Instruction.h"
42 #include "llvm/Instructions.h"
43 #include "llvm/Intrinsics.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Type.h"
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57 // This option should go away when tail calls fully work.
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65 cl::desc("Generate calls via indirect call instructions"),
69 ARMInterworking("arm-interworking", cl::Hidden,
70 cl::desc("Enable / disable ARM interworking (for debugging only)"),
74 class ARMCCState : public CCState {
76 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77 const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78 LLVMContext &C, ParmContext PC)
79 : CCState(CC, isVarArg, MF, TM, locs, C) {
80 assert(((PC == Call) || (PC == Prologue)) &&
81 "ARMCCState users must specify whether their context is call"
82 "or prologue generation.");
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90 ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94 MVT PromotedBitwiseVT) {
95 if (VT != PromotedLdStVT) {
96 setOperationAction(ISD::LOAD, VT, Promote);
97 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
99 setOperationAction(ISD::STORE, VT, Promote);
100 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
103 MVT ElemTy = VT.getVectorElementType();
104 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105 setOperationAction(ISD::SETCC, VT, Custom);
106 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108 if (ElemTy == MVT::i32) {
109 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
114 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
119 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
120 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
121 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
122 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123 setOperationAction(ISD::SELECT, VT, Expand);
124 setOperationAction(ISD::SELECT_CC, VT, Expand);
125 setOperationAction(ISD::VSELECT, VT, Expand);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127 if (VT.isInteger()) {
128 setOperationAction(ISD::SHL, VT, Custom);
129 setOperationAction(ISD::SRA, VT, Custom);
130 setOperationAction(ISD::SRL, VT, Custom);
133 // Promote all bit-wise operations.
134 if (VT.isInteger() && VT != PromotedBitwiseVT) {
135 setOperationAction(ISD::AND, VT, Promote);
136 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137 setOperationAction(ISD::OR, VT, Promote);
138 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
139 setOperationAction(ISD::XOR, VT, Promote);
140 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
143 // Neon does not support vector divide/remainder operations.
144 setOperationAction(ISD::SDIV, VT, Expand);
145 setOperationAction(ISD::UDIV, VT, Expand);
146 setOperationAction(ISD::FDIV, VT, Expand);
147 setOperationAction(ISD::SREM, VT, Expand);
148 setOperationAction(ISD::UREM, VT, Expand);
149 setOperationAction(ISD::FREM, VT, Expand);
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153 addRegisterClass(VT, &ARM::DPRRegClass);
154 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::QPRRegClass);
159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164 return new TargetLoweringObjectFileMachO();
166 return new ARMElfTargetObjectFile();
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170 : TargetLowering(TM, createTLOF(TM)) {
171 Subtarget = &TM.getSubtarget<ARMSubtarget>();
172 RegInfo = TM.getRegisterInfo();
173 Itins = TM.getInstrItineraryData();
175 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
177 if (Subtarget->isTargetDarwin()) {
178 // Uses VFP for Thumb libfuncs if available.
179 if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180 // Single-precision floating-point arithmetic.
181 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
186 // Double-precision floating-point arithmetic.
187 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
192 // Single-precision comparisons.
193 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
200 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
202 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
209 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
211 // Double-precision comparisons.
212 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
219 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
221 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
228 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
230 // Floating-point to integer conversions.
231 // i64 conversions are done via library routines even when generating VFP
232 // instructions, so use the same ones.
233 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
238 // Conversions between floating types.
239 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
242 // Integer to floating-point conversions.
243 // i64 conversions are done via library routines even when generating VFP
244 // instructions, so use the same ones.
245 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246 // e.g., __floatunsidf vs. __floatunssidfvfp.
247 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
254 // These libcalls are not available in 32-bit.
255 setLibcallName(RTLIB::SHL_I128, 0);
256 setLibcallName(RTLIB::SRL_I128, 0);
257 setLibcallName(RTLIB::SRA_I128, 0);
259 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260 // Double-precision floating-point arithmetic helper functions
261 // RTABI chapter 4.1.2, Table 2
262 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
271 // Double-precision floating-point comparison helper functions
272 // RTABI chapter 4.1.2, Table 3
273 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
286 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
287 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
288 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
289 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
298 // Single-precision floating-point arithmetic helper functions
299 // RTABI chapter 4.1.2, Table 4
300 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
309 // Single-precision floating-point comparison helper functions
310 // RTABI chapter 4.1.2, Table 5
311 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
324 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
325 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
326 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
327 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
336 // Floating-point to integer conversions.
337 // RTABI chapter 4.1.2, Table 6
338 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
355 // Conversions between floating types.
356 // RTABI chapter 4.1.2, Table 7
357 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
359 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
362 // Integer to floating-point conversions.
363 // RTABI chapter 4.1.2, Table 8
364 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
381 // Long long helper functions
382 // RTABI chapter 4.2, Table 9
383 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
384 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
394 // Integer division functions
395 // RTABI chapter 4.3.1
396 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
397 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
401 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
414 // RTABI chapter 4.3.4
415 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
416 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
418 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
423 // Use divmod compiler-rt calls for iOS 5.0 and later.
424 if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
430 if (Subtarget->isThumb1Only())
431 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
433 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435 !Subtarget->isThumb1Only()) {
436 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437 if (!Subtarget->isFPOnlySP())
438 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
440 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
443 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447 setTruncStoreAction((MVT::SimpleValueType)VT,
448 (MVT::SimpleValueType)InnerVT, Expand);
449 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
454 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
456 if (Subtarget->hasNEON()) {
457 addDRTypeForNEON(MVT::v2f32);
458 addDRTypeForNEON(MVT::v8i8);
459 addDRTypeForNEON(MVT::v4i16);
460 addDRTypeForNEON(MVT::v2i32);
461 addDRTypeForNEON(MVT::v1i64);
463 addQRTypeForNEON(MVT::v4f32);
464 addQRTypeForNEON(MVT::v2f64);
465 addQRTypeForNEON(MVT::v16i8);
466 addQRTypeForNEON(MVT::v8i16);
467 addQRTypeForNEON(MVT::v4i32);
468 addQRTypeForNEON(MVT::v2i64);
470 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471 // neither Neon nor VFP support any arithmetic operations on it.
472 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473 // supported for v4f32.
474 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477 // FIXME: Code duplication: FDIV and FREM are expanded always, see
478 // ARMTargetLowering::addTypeForNEON method for details.
479 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481 // FIXME: Create unittest.
482 // In another words, find a way when "copysign" appears in DAG with vector
484 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485 // FIXME: Code duplication: SETCC has custom operation action, see
486 // ARMTargetLowering::addTypeForNEON method for details.
487 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488 // FIXME: Create unittest for FNEG and for FABS.
489 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
508 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
509 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
510 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
511 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
512 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
513 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
514 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
515 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
516 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
517 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
518 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
519 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
520 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
521 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
522 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
524 // Neon does not support some operations on v1i64 and v2i64 types.
525 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
526 // Custom handling for some quad-vector types to detect VMULL.
527 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
528 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
529 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
530 // Custom handling for some vector types to avoid expensive expansions
531 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
532 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
533 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
534 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
535 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
536 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
537 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
538 // a destination type that is wider than the source, and nor does
539 // it have a FP_TO_[SU]INT instruction with a narrower destination than
541 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
542 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
543 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
544 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
546 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
547 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
549 // NEON does not have single instruction CTPOP for vectors with element
550 // types wider than 8-bits. However, custom lowering can leverage the
551 // v8i8/v16i8 vcnt instruction.
552 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
553 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
554 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
555 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
557 setTargetDAGCombine(ISD::INTRINSIC_VOID);
558 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
559 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
560 setTargetDAGCombine(ISD::SHL);
561 setTargetDAGCombine(ISD::SRL);
562 setTargetDAGCombine(ISD::SRA);
563 setTargetDAGCombine(ISD::SIGN_EXTEND);
564 setTargetDAGCombine(ISD::ZERO_EXTEND);
565 setTargetDAGCombine(ISD::ANY_EXTEND);
566 setTargetDAGCombine(ISD::SELECT_CC);
567 setTargetDAGCombine(ISD::BUILD_VECTOR);
568 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
569 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
570 setTargetDAGCombine(ISD::STORE);
571 setTargetDAGCombine(ISD::FP_TO_SINT);
572 setTargetDAGCombine(ISD::FP_TO_UINT);
573 setTargetDAGCombine(ISD::FDIV);
575 // It is legal to extload from v4i8 to v4i16 or v4i32.
576 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
577 MVT::v4i16, MVT::v2i16,
579 for (unsigned i = 0; i < 6; ++i) {
580 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
581 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
582 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
586 // ARM and Thumb2 support UMLAL/SMLAL.
587 if (!Subtarget->isThumb1Only())
588 setTargetDAGCombine(ISD::ADDC);
591 computeRegisterProperties();
593 // ARM does not have f32 extending load.
594 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
596 // ARM does not have i1 sign extending load.
597 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
599 // ARM supports all 4 flavors of integer indexed load / store.
600 if (!Subtarget->isThumb1Only()) {
601 for (unsigned im = (unsigned)ISD::PRE_INC;
602 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
603 setIndexedLoadAction(im, MVT::i1, Legal);
604 setIndexedLoadAction(im, MVT::i8, Legal);
605 setIndexedLoadAction(im, MVT::i16, Legal);
606 setIndexedLoadAction(im, MVT::i32, Legal);
607 setIndexedStoreAction(im, MVT::i1, Legal);
608 setIndexedStoreAction(im, MVT::i8, Legal);
609 setIndexedStoreAction(im, MVT::i16, Legal);
610 setIndexedStoreAction(im, MVT::i32, Legal);
614 // i64 operation support.
615 setOperationAction(ISD::MUL, MVT::i64, Expand);
616 setOperationAction(ISD::MULHU, MVT::i32, Expand);
617 if (Subtarget->isThumb1Only()) {
618 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
619 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
621 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
622 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
623 setOperationAction(ISD::MULHS, MVT::i32, Expand);
625 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
626 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
627 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
628 setOperationAction(ISD::SRL, MVT::i64, Custom);
629 setOperationAction(ISD::SRA, MVT::i64, Custom);
631 if (!Subtarget->isThumb1Only()) {
632 // FIXME: We should do this for Thumb1 as well.
633 setOperationAction(ISD::ADDC, MVT::i32, Custom);
634 setOperationAction(ISD::ADDE, MVT::i32, Custom);
635 setOperationAction(ISD::SUBC, MVT::i32, Custom);
636 setOperationAction(ISD::SUBE, MVT::i32, Custom);
639 // ARM does not have ROTL.
640 setOperationAction(ISD::ROTL, MVT::i32, Expand);
641 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
642 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
643 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
644 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
646 // These just redirect to CTTZ and CTLZ on ARM.
647 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
648 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
650 // Only ARMv6 has BSWAP.
651 if (!Subtarget->hasV6Ops())
652 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
654 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
655 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
656 // These are expanded into libcalls if the cpu doesn't have HW divider.
657 setOperationAction(ISD::SDIV, MVT::i32, Expand);
658 setOperationAction(ISD::UDIV, MVT::i32, Expand);
660 setOperationAction(ISD::SREM, MVT::i32, Expand);
661 setOperationAction(ISD::UREM, MVT::i32, Expand);
662 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
663 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
665 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
666 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
667 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
668 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
669 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
671 setOperationAction(ISD::TRAP, MVT::Other, Legal);
673 // Use the default implementation.
674 setOperationAction(ISD::VASTART, MVT::Other, Custom);
675 setOperationAction(ISD::VAARG, MVT::Other, Expand);
676 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
677 setOperationAction(ISD::VAEND, MVT::Other, Expand);
678 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
679 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
681 if (!Subtarget->isTargetDarwin()) {
682 // Non-Darwin platforms may return values in these registers via the
683 // personality function.
684 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
685 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
686 setExceptionPointerRegister(ARM::R0);
687 setExceptionSelectorRegister(ARM::R1);
690 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
691 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
692 // the default expansion.
693 // FIXME: This should be checking for v6k, not just v6.
694 if (Subtarget->hasDataBarrier() ||
695 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
696 // membarrier needs custom lowering; the rest are legal and handled
698 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
699 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
700 // Custom lowering for 64-bit ops
701 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
702 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
703 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
704 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
705 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
706 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
707 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
708 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
709 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
710 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
711 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
712 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
713 setInsertFencesForAtomic(true);
715 // Set them all for expansion, which will force libcalls.
716 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
717 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
718 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
719 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
720 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
721 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
722 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
723 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
724 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
725 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
726 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
727 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
728 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
729 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
730 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
731 // Unordered/Monotonic case.
732 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
733 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
734 // Since the libcalls include locking, fold in the fences
735 setShouldFoldAtomicFences(true);
738 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
740 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
741 if (!Subtarget->hasV6Ops()) {
742 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
743 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
745 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
747 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
748 !Subtarget->isThumb1Only()) {
749 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
750 // iff target supports vfp2.
751 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
752 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
755 // We want to custom lower some of our intrinsics.
756 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
757 if (Subtarget->isTargetDarwin()) {
758 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
759 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
760 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
763 setOperationAction(ISD::SETCC, MVT::i32, Expand);
764 setOperationAction(ISD::SETCC, MVT::f32, Expand);
765 setOperationAction(ISD::SETCC, MVT::f64, Expand);
766 setOperationAction(ISD::SELECT, MVT::i32, Custom);
767 setOperationAction(ISD::SELECT, MVT::f32, Custom);
768 setOperationAction(ISD::SELECT, MVT::f64, Custom);
769 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
770 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
771 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
773 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
774 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
775 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
776 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
777 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
779 // We don't support sin/cos/fmod/copysign/pow
780 setOperationAction(ISD::FSIN, MVT::f64, Expand);
781 setOperationAction(ISD::FSIN, MVT::f32, Expand);
782 setOperationAction(ISD::FCOS, MVT::f32, Expand);
783 setOperationAction(ISD::FCOS, MVT::f64, Expand);
784 setOperationAction(ISD::FREM, MVT::f64, Expand);
785 setOperationAction(ISD::FREM, MVT::f32, Expand);
786 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
787 !Subtarget->isThumb1Only()) {
788 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
789 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
791 setOperationAction(ISD::FPOW, MVT::f64, Expand);
792 setOperationAction(ISD::FPOW, MVT::f32, Expand);
794 if (!Subtarget->hasVFP4()) {
795 setOperationAction(ISD::FMA, MVT::f64, Expand);
796 setOperationAction(ISD::FMA, MVT::f32, Expand);
799 // Various VFP goodness
800 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
801 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
802 if (Subtarget->hasVFP2()) {
803 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
804 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
805 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
806 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
808 // Special handling for half-precision FP.
809 if (!Subtarget->hasFP16()) {
810 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
811 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
815 // We have target-specific dag combine patterns for the following nodes:
816 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
817 setTargetDAGCombine(ISD::ADD);
818 setTargetDAGCombine(ISD::SUB);
819 setTargetDAGCombine(ISD::MUL);
820 setTargetDAGCombine(ISD::AND);
821 setTargetDAGCombine(ISD::OR);
822 setTargetDAGCombine(ISD::XOR);
824 if (Subtarget->hasV6Ops())
825 setTargetDAGCombine(ISD::SRL);
827 setStackPointerRegisterToSaveRestore(ARM::SP);
829 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
830 !Subtarget->hasVFP2())
831 setSchedulingPreference(Sched::RegPressure);
833 setSchedulingPreference(Sched::Hybrid);
835 //// temporary - rewrite interface to use type
836 maxStoresPerMemset = 8;
837 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
838 maxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
839 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
840 maxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
841 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
843 // On ARM arguments smaller than 4 bytes are extended, so all arguments
844 // are at least 4 bytes aligned.
845 setMinStackArgumentAlignment(4);
847 benefitFromCodePlacementOpt = true;
849 // Prefer likely predicted branches to selects on out-of-order cores.
850 predictableSelectIsExpensive = Subtarget->isLikeA9();
852 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
855 // FIXME: It might make sense to define the representative register class as the
856 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
857 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
858 // SPR's representative would be DPR_VFP2. This should work well if register
859 // pressure tracking were modified such that a register use would increment the
860 // pressure of the register class's representative and all of it's super
861 // classes' representatives transitively. We have not implemented this because
862 // of the difficulty prior to coalescing of modeling operand register classes
863 // due to the common occurrence of cross class copies and subregister insertions
865 std::pair<const TargetRegisterClass*, uint8_t>
866 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
867 const TargetRegisterClass *RRC = 0;
869 switch (VT.SimpleTy) {
871 return TargetLowering::findRepresentativeClass(VT);
872 // Use DPR as representative register class for all floating point
873 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
874 // the cost is 1 for both f32 and f64.
875 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
876 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
877 RRC = &ARM::DPRRegClass;
878 // When NEON is used for SP, only half of the register file is available
879 // because operations that define both SP and DP results will be constrained
880 // to the VFP2 class (D0-D15). We currently model this constraint prior to
881 // coalescing by double-counting the SP regs. See the FIXME above.
882 if (Subtarget->useNEONForSinglePrecisionFP())
885 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
886 case MVT::v4f32: case MVT::v2f64:
887 RRC = &ARM::DPRRegClass;
891 RRC = &ARM::DPRRegClass;
895 RRC = &ARM::DPRRegClass;
899 return std::make_pair(RRC, Cost);
902 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
905 case ARMISD::Wrapper: return "ARMISD::Wrapper";
906 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
907 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
908 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
909 case ARMISD::CALL: return "ARMISD::CALL";
910 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
911 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
912 case ARMISD::tCALL: return "ARMISD::tCALL";
913 case ARMISD::BRCOND: return "ARMISD::BRCOND";
914 case ARMISD::BR_JT: return "ARMISD::BR_JT";
915 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
916 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
917 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
918 case ARMISD::CMP: return "ARMISD::CMP";
919 case ARMISD::CMN: return "ARMISD::CMN";
920 case ARMISD::CMPZ: return "ARMISD::CMPZ";
921 case ARMISD::CMPFP: return "ARMISD::CMPFP";
922 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
923 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
924 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
926 case ARMISD::CMOV: return "ARMISD::CMOV";
928 case ARMISD::RBIT: return "ARMISD::RBIT";
930 case ARMISD::FTOSI: return "ARMISD::FTOSI";
931 case ARMISD::FTOUI: return "ARMISD::FTOUI";
932 case ARMISD::SITOF: return "ARMISD::SITOF";
933 case ARMISD::UITOF: return "ARMISD::UITOF";
935 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
936 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
937 case ARMISD::RRX: return "ARMISD::RRX";
939 case ARMISD::ADDC: return "ARMISD::ADDC";
940 case ARMISD::ADDE: return "ARMISD::ADDE";
941 case ARMISD::SUBC: return "ARMISD::SUBC";
942 case ARMISD::SUBE: return "ARMISD::SUBE";
944 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
945 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
947 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
948 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
950 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
952 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
954 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
956 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
957 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
959 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
961 case ARMISD::VCEQ: return "ARMISD::VCEQ";
962 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
963 case ARMISD::VCGE: return "ARMISD::VCGE";
964 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
965 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
966 case ARMISD::VCGEU: return "ARMISD::VCGEU";
967 case ARMISD::VCGT: return "ARMISD::VCGT";
968 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
969 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
970 case ARMISD::VCGTU: return "ARMISD::VCGTU";
971 case ARMISD::VTST: return "ARMISD::VTST";
973 case ARMISD::VSHL: return "ARMISD::VSHL";
974 case ARMISD::VSHRs: return "ARMISD::VSHRs";
975 case ARMISD::VSHRu: return "ARMISD::VSHRu";
976 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
977 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
978 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
979 case ARMISD::VSHRN: return "ARMISD::VSHRN";
980 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
981 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
982 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
983 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
984 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
985 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
986 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
987 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
988 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
989 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
990 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
991 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
992 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
993 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
994 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
995 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
996 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
997 case ARMISD::VDUP: return "ARMISD::VDUP";
998 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
999 case ARMISD::VEXT: return "ARMISD::VEXT";
1000 case ARMISD::VREV64: return "ARMISD::VREV64";
1001 case ARMISD::VREV32: return "ARMISD::VREV32";
1002 case ARMISD::VREV16: return "ARMISD::VREV16";
1003 case ARMISD::VZIP: return "ARMISD::VZIP";
1004 case ARMISD::VUZP: return "ARMISD::VUZP";
1005 case ARMISD::VTRN: return "ARMISD::VTRN";
1006 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1007 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1008 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1009 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1010 case ARMISD::VADDLs: return "ARMISD::VADDLs";
1011 case ARMISD::VADDLu: return "ARMISD::VADDLu";
1012 case ARMISD::VSUBLs: return "ARMISD::VSUBLs";
1013 case ARMISD::VSUBLu: return "ARMISD::VSUBLu";
1014 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1015 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1016 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1017 case ARMISD::FMAX: return "ARMISD::FMAX";
1018 case ARMISD::FMIN: return "ARMISD::FMIN";
1019 case ARMISD::BFI: return "ARMISD::BFI";
1020 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1021 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1022 case ARMISD::VBSL: return "ARMISD::VBSL";
1023 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1024 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1025 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1026 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1027 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1028 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1029 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1030 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1031 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1032 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1033 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1034 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1035 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1036 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1037 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1038 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1039 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1040 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1041 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1042 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1046 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1047 if (!VT.isVector()) return getPointerTy();
1048 return VT.changeVectorElementTypeToInteger();
1051 /// getRegClassFor - Return the register class that should be used for the
1052 /// specified value type.
1053 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1054 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1055 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1056 // load / store 4 to 8 consecutive D registers.
1057 if (Subtarget->hasNEON()) {
1058 if (VT == MVT::v4i64)
1059 return &ARM::QQPRRegClass;
1060 if (VT == MVT::v8i64)
1061 return &ARM::QQQQPRRegClass;
1063 return TargetLowering::getRegClassFor(VT);
1066 // Create a fast isel object.
1068 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1069 const TargetLibraryInfo *libInfo) const {
1070 return ARM::createFastISel(funcInfo, libInfo);
1073 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1074 /// be used for loads / stores from the global.
1075 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1076 return (Subtarget->isThumb1Only() ? 127 : 4095);
1079 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1080 unsigned NumVals = N->getNumValues();
1082 return Sched::RegPressure;
1084 for (unsigned i = 0; i != NumVals; ++i) {
1085 EVT VT = N->getValueType(i);
1086 if (VT == MVT::Glue || VT == MVT::Other)
1088 if (VT.isFloatingPoint() || VT.isVector())
1092 if (!N->isMachineOpcode())
1093 return Sched::RegPressure;
1095 // Load are scheduled for latency even if there instruction itinerary
1096 // is not available.
1097 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1098 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1100 if (MCID.getNumDefs() == 0)
1101 return Sched::RegPressure;
1102 if (!Itins->isEmpty() &&
1103 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1106 return Sched::RegPressure;
1109 //===----------------------------------------------------------------------===//
1111 //===----------------------------------------------------------------------===//
1113 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1114 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1116 default: llvm_unreachable("Unknown condition code!");
1117 case ISD::SETNE: return ARMCC::NE;
1118 case ISD::SETEQ: return ARMCC::EQ;
1119 case ISD::SETGT: return ARMCC::GT;
1120 case ISD::SETGE: return ARMCC::GE;
1121 case ISD::SETLT: return ARMCC::LT;
1122 case ISD::SETLE: return ARMCC::LE;
1123 case ISD::SETUGT: return ARMCC::HI;
1124 case ISD::SETUGE: return ARMCC::HS;
1125 case ISD::SETULT: return ARMCC::LO;
1126 case ISD::SETULE: return ARMCC::LS;
1130 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1131 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1132 ARMCC::CondCodes &CondCode2) {
1133 CondCode2 = ARMCC::AL;
1135 default: llvm_unreachable("Unknown FP condition!");
1137 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1139 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1141 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1142 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1143 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1144 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1145 case ISD::SETO: CondCode = ARMCC::VC; break;
1146 case ISD::SETUO: CondCode = ARMCC::VS; break;
1147 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1148 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1149 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1151 case ISD::SETULT: CondCode = ARMCC::LT; break;
1153 case ISD::SETULE: CondCode = ARMCC::LE; break;
1155 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1159 //===----------------------------------------------------------------------===//
1160 // Calling Convention Implementation
1161 //===----------------------------------------------------------------------===//
1163 #include "ARMGenCallingConv.inc"
1165 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1166 /// given CallingConvention value.
1167 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1169 bool isVarArg) const {
1172 llvm_unreachable("Unsupported calling convention");
1173 case CallingConv::Fast:
1174 if (Subtarget->hasVFP2() && !isVarArg) {
1175 if (!Subtarget->isAAPCS_ABI())
1176 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1177 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1178 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1181 case CallingConv::C: {
1182 // Use target triple & subtarget features to do actual dispatch.
1183 if (!Subtarget->isAAPCS_ABI())
1184 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1185 else if (Subtarget->hasVFP2() &&
1186 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1188 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1189 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1191 case CallingConv::ARM_AAPCS_VFP:
1193 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1195 case CallingConv::ARM_AAPCS:
1196 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1197 case CallingConv::ARM_APCS:
1198 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1199 case CallingConv::GHC:
1200 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1204 /// LowerCallResult - Lower the result values of a call into the
1205 /// appropriate copies out of appropriate physical registers.
1207 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1208 CallingConv::ID CallConv, bool isVarArg,
1209 const SmallVectorImpl<ISD::InputArg> &Ins,
1210 DebugLoc dl, SelectionDAG &DAG,
1211 SmallVectorImpl<SDValue> &InVals) const {
1213 // Assign locations to each value returned by this call.
1214 SmallVector<CCValAssign, 16> RVLocs;
1215 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1216 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1217 CCInfo.AnalyzeCallResult(Ins,
1218 CCAssignFnForNode(CallConv, /* Return*/ true,
1221 // Copy all of the result registers out of their specified physreg.
1222 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1223 CCValAssign VA = RVLocs[i];
1226 if (VA.needsCustom()) {
1227 // Handle f64 or half of a v2f64.
1228 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1230 Chain = Lo.getValue(1);
1231 InFlag = Lo.getValue(2);
1232 VA = RVLocs[++i]; // skip ahead to next loc
1233 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1235 Chain = Hi.getValue(1);
1236 InFlag = Hi.getValue(2);
1237 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1239 if (VA.getLocVT() == MVT::v2f64) {
1240 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1241 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1242 DAG.getConstant(0, MVT::i32));
1244 VA = RVLocs[++i]; // skip ahead to next loc
1245 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1246 Chain = Lo.getValue(1);
1247 InFlag = Lo.getValue(2);
1248 VA = RVLocs[++i]; // skip ahead to next loc
1249 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1250 Chain = Hi.getValue(1);
1251 InFlag = Hi.getValue(2);
1252 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1253 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1254 DAG.getConstant(1, MVT::i32));
1257 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1259 Chain = Val.getValue(1);
1260 InFlag = Val.getValue(2);
1263 switch (VA.getLocInfo()) {
1264 default: llvm_unreachable("Unknown loc info!");
1265 case CCValAssign::Full: break;
1266 case CCValAssign::BCvt:
1267 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1271 InVals.push_back(Val);
1277 /// LowerMemOpCallTo - Store the argument to the stack.
1279 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1280 SDValue StackPtr, SDValue Arg,
1281 DebugLoc dl, SelectionDAG &DAG,
1282 const CCValAssign &VA,
1283 ISD::ArgFlagsTy Flags) const {
1284 unsigned LocMemOffset = VA.getLocMemOffset();
1285 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1286 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1287 return DAG.getStore(Chain, dl, Arg, PtrOff,
1288 MachinePointerInfo::getStack(LocMemOffset),
1292 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1293 SDValue Chain, SDValue &Arg,
1294 RegsToPassVector &RegsToPass,
1295 CCValAssign &VA, CCValAssign &NextVA,
1297 SmallVector<SDValue, 8> &MemOpChains,
1298 ISD::ArgFlagsTy Flags) const {
1300 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1301 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1302 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1304 if (NextVA.isRegLoc())
1305 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1307 assert(NextVA.isMemLoc());
1308 if (StackPtr.getNode() == 0)
1309 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1311 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1317 /// LowerCall - Lowering a call into a callseq_start <-
1318 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1321 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1322 SmallVectorImpl<SDValue> &InVals) const {
1323 SelectionDAG &DAG = CLI.DAG;
1324 DebugLoc &dl = CLI.DL;
1325 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1326 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1327 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1328 SDValue Chain = CLI.Chain;
1329 SDValue Callee = CLI.Callee;
1330 bool &isTailCall = CLI.IsTailCall;
1331 CallingConv::ID CallConv = CLI.CallConv;
1332 bool doesNotRet = CLI.DoesNotReturn;
1333 bool isVarArg = CLI.IsVarArg;
1335 MachineFunction &MF = DAG.getMachineFunction();
1336 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1337 bool IsSibCall = false;
1338 // Disable tail calls if they're not supported.
1339 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1342 // Check if it's really possible to do a tail call.
1343 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1344 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1345 Outs, OutVals, Ins, DAG);
1346 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1347 // detected sibcalls.
1354 // Analyze operands of the call, assigning locations to each operand.
1355 SmallVector<CCValAssign, 16> ArgLocs;
1356 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1357 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1358 CCInfo.AnalyzeCallOperands(Outs,
1359 CCAssignFnForNode(CallConv, /* Return*/ false,
1362 // Get a count of how many bytes are to be pushed on the stack.
1363 unsigned NumBytes = CCInfo.getNextStackOffset();
1365 // For tail calls, memory operands are available in our caller's stack.
1369 // Adjust the stack pointer for the new arguments...
1370 // These operations are automatically eliminated by the prolog/epilog pass
1372 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1374 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1376 RegsToPassVector RegsToPass;
1377 SmallVector<SDValue, 8> MemOpChains;
1379 // Walk the register/memloc assignments, inserting copies/loads. In the case
1380 // of tail call optimization, arguments are handled later.
1381 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1383 ++i, ++realArgIdx) {
1384 CCValAssign &VA = ArgLocs[i];
1385 SDValue Arg = OutVals[realArgIdx];
1386 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1387 bool isByVal = Flags.isByVal();
1389 // Promote the value if needed.
1390 switch (VA.getLocInfo()) {
1391 default: llvm_unreachable("Unknown loc info!");
1392 case CCValAssign::Full: break;
1393 case CCValAssign::SExt:
1394 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1396 case CCValAssign::ZExt:
1397 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1399 case CCValAssign::AExt:
1400 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1402 case CCValAssign::BCvt:
1403 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1407 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1408 if (VA.needsCustom()) {
1409 if (VA.getLocVT() == MVT::v2f64) {
1410 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1411 DAG.getConstant(0, MVT::i32));
1412 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1413 DAG.getConstant(1, MVT::i32));
1415 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1416 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1418 VA = ArgLocs[++i]; // skip ahead to next loc
1419 if (VA.isRegLoc()) {
1420 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1421 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1423 assert(VA.isMemLoc());
1425 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1426 dl, DAG, VA, Flags));
1429 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1430 StackPtr, MemOpChains, Flags);
1432 } else if (VA.isRegLoc()) {
1433 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1434 } else if (isByVal) {
1435 assert(VA.isMemLoc());
1436 unsigned offset = 0;
1438 // True if this byval aggregate will be split between registers
1440 if (CCInfo.isFirstByValRegValid()) {
1441 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1443 for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1444 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1445 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1446 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1447 MachinePointerInfo(),
1448 false, false, false, 0);
1449 MemOpChains.push_back(Load.getValue(1));
1450 RegsToPass.push_back(std::make_pair(j, Load));
1452 offset = ARM::R4 - CCInfo.getFirstByValReg();
1453 CCInfo.clearFirstByValReg();
1456 if (Flags.getByValSize() - 4*offset > 0) {
1457 unsigned LocMemOffset = VA.getLocMemOffset();
1458 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1459 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1461 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1462 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1463 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1465 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1467 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1468 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1469 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1470 Ops, array_lengthof(Ops)));
1472 } else if (!IsSibCall) {
1473 assert(VA.isMemLoc());
1475 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1476 dl, DAG, VA, Flags));
1480 if (!MemOpChains.empty())
1481 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1482 &MemOpChains[0], MemOpChains.size());
1484 // Build a sequence of copy-to-reg nodes chained together with token chain
1485 // and flag operands which copy the outgoing args into the appropriate regs.
1487 // Tail call byval lowering might overwrite argument registers so in case of
1488 // tail call optimization the copies to registers are lowered later.
1490 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1491 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1492 RegsToPass[i].second, InFlag);
1493 InFlag = Chain.getValue(1);
1496 // For tail calls lower the arguments to the 'real' stack slot.
1498 // Force all the incoming stack arguments to be loaded from the stack
1499 // before any new outgoing arguments are stored to the stack, because the
1500 // outgoing stack slots may alias the incoming argument stack slots, and
1501 // the alias isn't otherwise explicit. This is slightly more conservative
1502 // than necessary, because it means that each store effectively depends
1503 // on every argument instead of just those arguments it would clobber.
1505 // Do not flag preceding copytoreg stuff together with the following stuff.
1507 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1508 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1509 RegsToPass[i].second, InFlag);
1510 InFlag = Chain.getValue(1);
1515 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1516 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1517 // node so that legalize doesn't hack it.
1518 bool isDirect = false;
1519 bool isARMFunc = false;
1520 bool isLocalARMFunc = false;
1521 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1523 if (EnableARMLongCalls) {
1524 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1525 && "long-calls with non-static relocation model!");
1526 // Handle a global address or an external symbol. If it's not one of
1527 // those, the target's already in a register, so we don't need to do
1529 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1530 const GlobalValue *GV = G->getGlobal();
1531 // Create a constant pool entry for the callee address
1532 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1533 ARMConstantPoolValue *CPV =
1534 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1536 // Get the address of the callee into a register
1537 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1538 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1539 Callee = DAG.getLoad(getPointerTy(), dl,
1540 DAG.getEntryNode(), CPAddr,
1541 MachinePointerInfo::getConstantPool(),
1542 false, false, false, 0);
1543 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1544 const char *Sym = S->getSymbol();
1546 // Create a constant pool entry for the callee address
1547 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1548 ARMConstantPoolValue *CPV =
1549 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1550 ARMPCLabelIndex, 0);
1551 // Get the address of the callee into a register
1552 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1553 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1554 Callee = DAG.getLoad(getPointerTy(), dl,
1555 DAG.getEntryNode(), CPAddr,
1556 MachinePointerInfo::getConstantPool(),
1557 false, false, false, 0);
1559 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1560 const GlobalValue *GV = G->getGlobal();
1562 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1563 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1564 getTargetMachine().getRelocationModel() != Reloc::Static;
1565 isARMFunc = !Subtarget->isThumb() || isStub;
1566 // ARM call to a local ARM function is predicable.
1567 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1568 // tBX takes a register source operand.
1569 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1570 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1571 ARMConstantPoolValue *CPV =
1572 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1573 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1574 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1575 Callee = DAG.getLoad(getPointerTy(), dl,
1576 DAG.getEntryNode(), CPAddr,
1577 MachinePointerInfo::getConstantPool(),
1578 false, false, false, 0);
1579 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1580 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1581 getPointerTy(), Callee, PICLabel);
1583 // On ELF targets for PIC code, direct calls should go through the PLT
1584 unsigned OpFlags = 0;
1585 if (Subtarget->isTargetELF() &&
1586 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1587 OpFlags = ARMII::MO_PLT;
1588 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1590 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1592 bool isStub = Subtarget->isTargetDarwin() &&
1593 getTargetMachine().getRelocationModel() != Reloc::Static;
1594 isARMFunc = !Subtarget->isThumb() || isStub;
1595 // tBX takes a register source operand.
1596 const char *Sym = S->getSymbol();
1597 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1598 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1599 ARMConstantPoolValue *CPV =
1600 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1601 ARMPCLabelIndex, 4);
1602 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1603 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1604 Callee = DAG.getLoad(getPointerTy(), dl,
1605 DAG.getEntryNode(), CPAddr,
1606 MachinePointerInfo::getConstantPool(),
1607 false, false, false, 0);
1608 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1609 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1610 getPointerTy(), Callee, PICLabel);
1612 unsigned OpFlags = 0;
1613 // On ELF targets for PIC code, direct calls should go through the PLT
1614 if (Subtarget->isTargetELF() &&
1615 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1616 OpFlags = ARMII::MO_PLT;
1617 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1621 // FIXME: handle tail calls differently.
1623 bool HasMinSizeAttr = MF.getFunction()->getFnAttributes().
1624 hasAttribute(Attribute::MinSize);
1625 if (Subtarget->isThumb()) {
1626 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1627 CallOpc = ARMISD::CALL_NOLINK;
1629 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1631 if (!isDirect && !Subtarget->hasV5TOps())
1632 CallOpc = ARMISD::CALL_NOLINK;
1633 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1634 // Emit regular call when code size is the priority
1636 // "mov lr, pc; b _foo" to avoid confusing the RSP
1637 CallOpc = ARMISD::CALL_NOLINK;
1639 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1642 std::vector<SDValue> Ops;
1643 Ops.push_back(Chain);
1644 Ops.push_back(Callee);
1646 // Add argument registers to the end of the list so that they are known live
1648 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1649 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1650 RegsToPass[i].second.getValueType()));
1652 // Add a register mask operand representing the call-preserved registers.
1653 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1654 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1655 assert(Mask && "Missing call preserved mask for calling convention");
1656 Ops.push_back(DAG.getRegisterMask(Mask));
1658 if (InFlag.getNode())
1659 Ops.push_back(InFlag);
1661 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1663 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1665 // Returns a chain and a flag for retval copy to use.
1666 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1667 InFlag = Chain.getValue(1);
1669 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1670 DAG.getIntPtrConstant(0, true), InFlag);
1672 InFlag = Chain.getValue(1);
1674 // Handle result values, copying them out of physregs into vregs that we
1676 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1680 /// HandleByVal - Every parameter *after* a byval parameter is passed
1681 /// on the stack. Remember the next parameter register to allocate,
1682 /// and then confiscate the rest of the parameter registers to insure
1685 ARMTargetLowering::HandleByVal(
1686 CCState *State, unsigned &size, unsigned Align) const {
1687 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1688 assert((State->getCallOrPrologue() == Prologue ||
1689 State->getCallOrPrologue() == Call) &&
1690 "unhandled ParmContext");
1691 if ((!State->isFirstByValRegValid()) &&
1692 (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1693 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1694 unsigned AlignInRegs = Align / 4;
1695 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1696 for (unsigned i = 0; i < Waste; ++i)
1697 reg = State->AllocateReg(GPRArgRegs, 4);
1700 State->setFirstByValReg(reg);
1701 // At a call site, a byval parameter that is split between
1702 // registers and memory needs its size truncated here. In a
1703 // function prologue, such byval parameters are reassembled in
1704 // memory, and are not truncated.
1705 if (State->getCallOrPrologue() == Call) {
1706 unsigned excess = 4 * (ARM::R4 - reg);
1707 assert(size >= excess && "expected larger existing stack allocation");
1712 // Confiscate any remaining parameter registers to preclude their
1713 // assignment to subsequent parameters.
1714 while (State->AllocateReg(GPRArgRegs, 4))
1718 /// MatchingStackOffset - Return true if the given stack call argument is
1719 /// already available in the same position (relatively) of the caller's
1720 /// incoming argument stack.
1722 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1723 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1724 const TargetInstrInfo *TII) {
1725 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1727 if (Arg.getOpcode() == ISD::CopyFromReg) {
1728 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1729 if (!TargetRegisterInfo::isVirtualRegister(VR))
1731 MachineInstr *Def = MRI->getVRegDef(VR);
1734 if (!Flags.isByVal()) {
1735 if (!TII->isLoadFromStackSlot(Def, FI))
1740 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1741 if (Flags.isByVal())
1742 // ByVal argument is passed in as a pointer but it's now being
1743 // dereferenced. e.g.
1744 // define @foo(%struct.X* %A) {
1745 // tail call @bar(%struct.X* byval %A)
1748 SDValue Ptr = Ld->getBasePtr();
1749 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1752 FI = FINode->getIndex();
1756 assert(FI != INT_MAX);
1757 if (!MFI->isFixedObjectIndex(FI))
1759 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1762 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1763 /// for tail call optimization. Targets which want to do tail call
1764 /// optimization should implement this function.
1766 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1767 CallingConv::ID CalleeCC,
1769 bool isCalleeStructRet,
1770 bool isCallerStructRet,
1771 const SmallVectorImpl<ISD::OutputArg> &Outs,
1772 const SmallVectorImpl<SDValue> &OutVals,
1773 const SmallVectorImpl<ISD::InputArg> &Ins,
1774 SelectionDAG& DAG) const {
1775 const Function *CallerF = DAG.getMachineFunction().getFunction();
1776 CallingConv::ID CallerCC = CallerF->getCallingConv();
1777 bool CCMatch = CallerCC == CalleeCC;
1779 // Look for obvious safe cases to perform tail call optimization that do not
1780 // require ABI changes. This is what gcc calls sibcall.
1782 // Do not sibcall optimize vararg calls unless the call site is not passing
1784 if (isVarArg && !Outs.empty())
1787 // Also avoid sibcall optimization if either caller or callee uses struct
1788 // return semantics.
1789 if (isCalleeStructRet || isCallerStructRet)
1792 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1793 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1794 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1795 // support in the assembler and linker to be used. This would need to be
1796 // fixed to fully support tail calls in Thumb1.
1798 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1799 // LR. This means if we need to reload LR, it takes an extra instructions,
1800 // which outweighs the value of the tail call; but here we don't know yet
1801 // whether LR is going to be used. Probably the right approach is to
1802 // generate the tail call here and turn it back into CALL/RET in
1803 // emitEpilogue if LR is used.
1805 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1806 // but we need to make sure there are enough registers; the only valid
1807 // registers are the 4 used for parameters. We don't currently do this
1809 if (Subtarget->isThumb1Only())
1812 // If the calling conventions do not match, then we'd better make sure the
1813 // results are returned in the same way as what the caller expects.
1815 SmallVector<CCValAssign, 16> RVLocs1;
1816 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1817 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1818 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1820 SmallVector<CCValAssign, 16> RVLocs2;
1821 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1822 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1823 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1825 if (RVLocs1.size() != RVLocs2.size())
1827 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1828 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1830 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1832 if (RVLocs1[i].isRegLoc()) {
1833 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1836 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1842 // If Caller's vararg or byval argument has been split between registers and
1843 // stack, do not perform tail call, since part of the argument is in caller's
1845 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1846 getInfo<ARMFunctionInfo>();
1847 if (AFI_Caller->getVarArgsRegSaveSize())
1850 // If the callee takes no arguments then go on to check the results of the
1852 if (!Outs.empty()) {
1853 // Check if stack adjustment is needed. For now, do not do this if any
1854 // argument is passed on the stack.
1855 SmallVector<CCValAssign, 16> ArgLocs;
1856 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1857 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1858 CCInfo.AnalyzeCallOperands(Outs,
1859 CCAssignFnForNode(CalleeCC, false, isVarArg));
1860 if (CCInfo.getNextStackOffset()) {
1861 MachineFunction &MF = DAG.getMachineFunction();
1863 // Check if the arguments are already laid out in the right way as
1864 // the caller's fixed stack objects.
1865 MachineFrameInfo *MFI = MF.getFrameInfo();
1866 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1867 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1868 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1870 ++i, ++realArgIdx) {
1871 CCValAssign &VA = ArgLocs[i];
1872 EVT RegVT = VA.getLocVT();
1873 SDValue Arg = OutVals[realArgIdx];
1874 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1875 if (VA.getLocInfo() == CCValAssign::Indirect)
1877 if (VA.needsCustom()) {
1878 // f64 and vector types are split into multiple registers or
1879 // register/stack-slot combinations. The types will not match
1880 // the registers; give up on memory f64 refs until we figure
1881 // out what to do about this.
1884 if (!ArgLocs[++i].isRegLoc())
1886 if (RegVT == MVT::v2f64) {
1887 if (!ArgLocs[++i].isRegLoc())
1889 if (!ArgLocs[++i].isRegLoc())
1892 } else if (!VA.isRegLoc()) {
1893 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1905 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1906 MachineFunction &MF, bool isVarArg,
1907 const SmallVectorImpl<ISD::OutputArg> &Outs,
1908 LLVMContext &Context) const {
1909 SmallVector<CCValAssign, 16> RVLocs;
1910 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1911 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
1916 ARMTargetLowering::LowerReturn(SDValue Chain,
1917 CallingConv::ID CallConv, bool isVarArg,
1918 const SmallVectorImpl<ISD::OutputArg> &Outs,
1919 const SmallVectorImpl<SDValue> &OutVals,
1920 DebugLoc dl, SelectionDAG &DAG) const {
1922 // CCValAssign - represent the assignment of the return value to a location.
1923 SmallVector<CCValAssign, 16> RVLocs;
1925 // CCState - Info about the registers and stack slots.
1926 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1927 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1929 // Analyze outgoing return values.
1930 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1933 // If this is the first return lowered for this function, add
1934 // the regs to the liveout set for the function.
1935 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1936 for (unsigned i = 0; i != RVLocs.size(); ++i)
1937 if (RVLocs[i].isRegLoc())
1938 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1943 // Copy the result values into the output registers.
1944 for (unsigned i = 0, realRVLocIdx = 0;
1946 ++i, ++realRVLocIdx) {
1947 CCValAssign &VA = RVLocs[i];
1948 assert(VA.isRegLoc() && "Can only return in registers!");
1950 SDValue Arg = OutVals[realRVLocIdx];
1952 switch (VA.getLocInfo()) {
1953 default: llvm_unreachable("Unknown loc info!");
1954 case CCValAssign::Full: break;
1955 case CCValAssign::BCvt:
1956 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1960 if (VA.needsCustom()) {
1961 if (VA.getLocVT() == MVT::v2f64) {
1962 // Extract the first half and return it in two registers.
1963 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1964 DAG.getConstant(0, MVT::i32));
1965 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1966 DAG.getVTList(MVT::i32, MVT::i32), Half);
1968 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1969 Flag = Chain.getValue(1);
1970 VA = RVLocs[++i]; // skip ahead to next loc
1971 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1972 HalfGPRs.getValue(1), Flag);
1973 Flag = Chain.getValue(1);
1974 VA = RVLocs[++i]; // skip ahead to next loc
1976 // Extract the 2nd half and fall through to handle it as an f64 value.
1977 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1978 DAG.getConstant(1, MVT::i32));
1980 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1982 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1983 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1984 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1985 Flag = Chain.getValue(1);
1986 VA = RVLocs[++i]; // skip ahead to next loc
1987 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1990 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1992 // Guarantee that all emitted copies are
1993 // stuck together, avoiding something bad.
1994 Flag = Chain.getValue(1);
1999 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
2001 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
2006 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2007 if (N->getNumValues() != 1)
2009 if (!N->hasNUsesOfValue(1, 0))
2012 SDValue TCChain = Chain;
2013 SDNode *Copy = *N->use_begin();
2014 if (Copy->getOpcode() == ISD::CopyToReg) {
2015 // If the copy has a glue operand, we conservatively assume it isn't safe to
2016 // perform a tail call.
2017 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2019 TCChain = Copy->getOperand(0);
2020 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2021 SDNode *VMov = Copy;
2022 // f64 returned in a pair of GPRs.
2023 SmallPtrSet<SDNode*, 2> Copies;
2024 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2026 if (UI->getOpcode() != ISD::CopyToReg)
2030 if (Copies.size() > 2)
2033 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2035 SDValue UseChain = UI->getOperand(0);
2036 if (Copies.count(UseChain.getNode()))
2043 } else if (Copy->getOpcode() == ISD::BITCAST) {
2044 // f32 returned in a single GPR.
2045 if (!Copy->hasOneUse())
2047 Copy = *Copy->use_begin();
2048 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2050 Chain = Copy->getOperand(0);
2055 bool HasRet = false;
2056 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2058 if (UI->getOpcode() != ARMISD::RET_FLAG)
2070 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2071 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2074 if (!CI->isTailCall())
2077 return !Subtarget->isThumb1Only();
2080 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2081 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2082 // one of the above mentioned nodes. It has to be wrapped because otherwise
2083 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2084 // be used to form addressing mode. These wrapped nodes will be selected
2086 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2087 EVT PtrVT = Op.getValueType();
2088 // FIXME there is no actual debug info here
2089 DebugLoc dl = Op.getDebugLoc();
2090 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2092 if (CP->isMachineConstantPoolEntry())
2093 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2094 CP->getAlignment());
2096 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2097 CP->getAlignment());
2098 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2101 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2102 return MachineJumpTableInfo::EK_Inline;
2105 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2106 SelectionDAG &DAG) const {
2107 MachineFunction &MF = DAG.getMachineFunction();
2108 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2109 unsigned ARMPCLabelIndex = 0;
2110 DebugLoc DL = Op.getDebugLoc();
2111 EVT PtrVT = getPointerTy();
2112 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2113 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2115 if (RelocM == Reloc::Static) {
2116 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2118 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2119 ARMPCLabelIndex = AFI->createPICLabelUId();
2120 ARMConstantPoolValue *CPV =
2121 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2122 ARMCP::CPBlockAddress, PCAdj);
2123 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2125 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2126 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2127 MachinePointerInfo::getConstantPool(),
2128 false, false, false, 0);
2129 if (RelocM == Reloc::Static)
2131 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2132 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2135 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2137 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2138 SelectionDAG &DAG) const {
2139 DebugLoc dl = GA->getDebugLoc();
2140 EVT PtrVT = getPointerTy();
2141 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2142 MachineFunction &MF = DAG.getMachineFunction();
2143 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2144 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2145 ARMConstantPoolValue *CPV =
2146 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2147 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2148 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2149 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2150 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2151 MachinePointerInfo::getConstantPool(),
2152 false, false, false, 0);
2153 SDValue Chain = Argument.getValue(1);
2155 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2156 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2158 // call __tls_get_addr.
2161 Entry.Node = Argument;
2162 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2163 Args.push_back(Entry);
2164 // FIXME: is there useful debug info available here?
2165 TargetLowering::CallLoweringInfo CLI(Chain,
2166 (Type *) Type::getInt32Ty(*DAG.getContext()),
2167 false, false, false, false,
2168 0, CallingConv::C, /*isTailCall=*/false,
2169 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2170 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2171 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2172 return CallResult.first;
2175 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2176 // "local exec" model.
2178 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2180 TLSModel::Model model) const {
2181 const GlobalValue *GV = GA->getGlobal();
2182 DebugLoc dl = GA->getDebugLoc();
2184 SDValue Chain = DAG.getEntryNode();
2185 EVT PtrVT = getPointerTy();
2186 // Get the Thread Pointer
2187 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2189 if (model == TLSModel::InitialExec) {
2190 MachineFunction &MF = DAG.getMachineFunction();
2191 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2192 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2193 // Initial exec model.
2194 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2195 ARMConstantPoolValue *CPV =
2196 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2197 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2199 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2200 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2201 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2202 MachinePointerInfo::getConstantPool(),
2203 false, false, false, 0);
2204 Chain = Offset.getValue(1);
2206 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2207 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2209 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2210 MachinePointerInfo::getConstantPool(),
2211 false, false, false, 0);
2214 assert(model == TLSModel::LocalExec);
2215 ARMConstantPoolValue *CPV =
2216 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2217 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2218 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2219 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2220 MachinePointerInfo::getConstantPool(),
2221 false, false, false, 0);
2224 // The address of the thread local variable is the add of the thread
2225 // pointer with the offset of the variable.
2226 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2230 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2231 // TODO: implement the "local dynamic" model
2232 assert(Subtarget->isTargetELF() &&
2233 "TLS not implemented for non-ELF targets");
2234 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2236 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2239 case TLSModel::GeneralDynamic:
2240 case TLSModel::LocalDynamic:
2241 return LowerToTLSGeneralDynamicModel(GA, DAG);
2242 case TLSModel::InitialExec:
2243 case TLSModel::LocalExec:
2244 return LowerToTLSExecModels(GA, DAG, model);
2246 llvm_unreachable("bogus TLS model");
2249 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2250 SelectionDAG &DAG) const {
2251 EVT PtrVT = getPointerTy();
2252 DebugLoc dl = Op.getDebugLoc();
2253 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2254 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2255 if (RelocM == Reloc::PIC_) {
2256 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2257 ARMConstantPoolValue *CPV =
2258 ARMConstantPoolConstant::Create(GV,
2259 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2260 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2261 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2262 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2264 MachinePointerInfo::getConstantPool(),
2265 false, false, false, 0);
2266 SDValue Chain = Result.getValue(1);
2267 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2268 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2270 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2271 MachinePointerInfo::getGOT(),
2272 false, false, false, 0);
2276 // If we have T2 ops, we can materialize the address directly via movt/movw
2277 // pair. This is always cheaper.
2278 if (Subtarget->useMovt()) {
2280 // FIXME: Once remat is capable of dealing with instructions with register
2281 // operands, expand this into two nodes.
2282 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2283 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2285 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2286 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2287 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2288 MachinePointerInfo::getConstantPool(),
2289 false, false, false, 0);
2293 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2294 SelectionDAG &DAG) const {
2295 EVT PtrVT = getPointerTy();
2296 DebugLoc dl = Op.getDebugLoc();
2297 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2298 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2299 MachineFunction &MF = DAG.getMachineFunction();
2300 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2302 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2303 // update ARMFastISel::ARMMaterializeGV.
2304 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2306 // FIXME: Once remat is capable of dealing with instructions with register
2307 // operands, expand this into two nodes.
2308 if (RelocM == Reloc::Static)
2309 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2310 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2312 unsigned Wrapper = (RelocM == Reloc::PIC_)
2313 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2314 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2315 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2316 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2317 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2318 MachinePointerInfo::getGOT(),
2319 false, false, false, 0);
2323 unsigned ARMPCLabelIndex = 0;
2325 if (RelocM == Reloc::Static) {
2326 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2328 ARMPCLabelIndex = AFI->createPICLabelUId();
2329 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2330 ARMConstantPoolValue *CPV =
2331 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2333 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2335 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2337 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2338 MachinePointerInfo::getConstantPool(),
2339 false, false, false, 0);
2340 SDValue Chain = Result.getValue(1);
2342 if (RelocM == Reloc::PIC_) {
2343 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2344 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2347 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2348 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2349 false, false, false, 0);
2354 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2355 SelectionDAG &DAG) const {
2356 assert(Subtarget->isTargetELF() &&
2357 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2358 MachineFunction &MF = DAG.getMachineFunction();
2359 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2360 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2361 EVT PtrVT = getPointerTy();
2362 DebugLoc dl = Op.getDebugLoc();
2363 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2364 ARMConstantPoolValue *CPV =
2365 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2366 ARMPCLabelIndex, PCAdj);
2367 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2368 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2369 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2370 MachinePointerInfo::getConstantPool(),
2371 false, false, false, 0);
2372 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2373 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2377 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2378 DebugLoc dl = Op.getDebugLoc();
2379 SDValue Val = DAG.getConstant(0, MVT::i32);
2380 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2381 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2382 Op.getOperand(1), Val);
2386 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2387 DebugLoc dl = Op.getDebugLoc();
2388 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2389 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2393 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2394 const ARMSubtarget *Subtarget) const {
2395 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2396 DebugLoc dl = Op.getDebugLoc();
2398 default: return SDValue(); // Don't custom lower most intrinsics.
2399 case Intrinsic::arm_thread_pointer: {
2400 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2401 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2403 case Intrinsic::eh_sjlj_lsda: {
2404 MachineFunction &MF = DAG.getMachineFunction();
2405 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2406 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2407 EVT PtrVT = getPointerTy();
2408 DebugLoc dl = Op.getDebugLoc();
2409 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2411 unsigned PCAdj = (RelocM != Reloc::PIC_)
2412 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2413 ARMConstantPoolValue *CPV =
2414 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2415 ARMCP::CPLSDA, PCAdj);
2416 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2417 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2419 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2420 MachinePointerInfo::getConstantPool(),
2421 false, false, false, 0);
2423 if (RelocM == Reloc::PIC_) {
2424 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2425 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2429 case Intrinsic::arm_neon_vmulls:
2430 case Intrinsic::arm_neon_vmullu: {
2431 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2432 ? ARMISD::VMULLs : ARMISD::VMULLu;
2433 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2434 Op.getOperand(1), Op.getOperand(2));
2436 case Intrinsic::arm_neon_vaddls:
2437 case Intrinsic::arm_neon_vaddlu: {
2438 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vaddls)
2439 ? ARMISD::VADDLs : ARMISD::VADDLu;
2440 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2441 Op.getOperand(1), Op.getOperand(2));
2443 case Intrinsic::arm_neon_vsubls:
2444 case Intrinsic::arm_neon_vsublu: {
2445 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vsubls)
2446 ? ARMISD::VSUBLs: ARMISD::VSUBLu;
2447 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2448 Op.getOperand(1), Op.getOperand(2));
2453 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2454 const ARMSubtarget *Subtarget) {
2455 DebugLoc dl = Op.getDebugLoc();
2456 if (!Subtarget->hasDataBarrier()) {
2457 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2458 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2460 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2461 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2462 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2463 DAG.getConstant(0, MVT::i32));
2466 SDValue Op5 = Op.getOperand(5);
2467 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2468 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2469 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2470 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2472 ARM_MB::MemBOpt DMBOpt;
2473 if (isDeviceBarrier)
2474 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2476 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2477 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2478 DAG.getConstant(DMBOpt, MVT::i32));
2482 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2483 const ARMSubtarget *Subtarget) {
2484 // FIXME: handle "fence singlethread" more efficiently.
2485 DebugLoc dl = Op.getDebugLoc();
2486 if (!Subtarget->hasDataBarrier()) {
2487 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2488 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2490 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2491 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2492 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2493 DAG.getConstant(0, MVT::i32));
2496 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2497 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2500 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2501 const ARMSubtarget *Subtarget) {
2502 // ARM pre v5TE and Thumb1 does not have preload instructions.
2503 if (!(Subtarget->isThumb2() ||
2504 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2505 // Just preserve the chain.
2506 return Op.getOperand(0);
2508 DebugLoc dl = Op.getDebugLoc();
2509 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2511 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2512 // ARMv7 with MP extension has PLDW.
2513 return Op.getOperand(0);
2515 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2516 if (Subtarget->isThumb()) {
2518 isRead = ~isRead & 1;
2519 isData = ~isData & 1;
2522 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2523 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2524 DAG.getConstant(isData, MVT::i32));
2527 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2528 MachineFunction &MF = DAG.getMachineFunction();
2529 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2531 // vastart just stores the address of the VarArgsFrameIndex slot into the
2532 // memory location argument.
2533 DebugLoc dl = Op.getDebugLoc();
2534 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2535 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2536 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2537 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2538 MachinePointerInfo(SV), false, false, 0);
2542 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2543 SDValue &Root, SelectionDAG &DAG,
2544 DebugLoc dl) const {
2545 MachineFunction &MF = DAG.getMachineFunction();
2546 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2548 const TargetRegisterClass *RC;
2549 if (AFI->isThumb1OnlyFunction())
2550 RC = &ARM::tGPRRegClass;
2552 RC = &ARM::GPRRegClass;
2554 // Transform the arguments stored in physical registers into virtual ones.
2555 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2556 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2559 if (NextVA.isMemLoc()) {
2560 MachineFrameInfo *MFI = MF.getFrameInfo();
2561 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2563 // Create load node to retrieve arguments from the stack.
2564 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2565 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2566 MachinePointerInfo::getFixedStack(FI),
2567 false, false, false, 0);
2569 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2570 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2573 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2577 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2578 unsigned &VARegSize, unsigned &VARegSaveSize)
2581 if (CCInfo.isFirstByValRegValid())
2582 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2584 unsigned int firstUnalloced;
2585 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2586 sizeof(GPRArgRegs) /
2587 sizeof(GPRArgRegs[0]));
2588 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2591 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2592 VARegSize = NumGPRs * 4;
2593 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2596 // The remaining GPRs hold either the beginning of variable-argument
2597 // data, or the beginning of an aggregate passed by value (usuall
2598 // byval). Either way, we allocate stack slots adjacent to the data
2599 // provided by our caller, and store the unallocated registers there.
2600 // If this is a variadic function, the va_list pointer will begin with
2601 // these values; otherwise, this reassembles a (byval) structure that
2602 // was split between registers and memory.
2604 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2605 DebugLoc dl, SDValue &Chain,
2606 const Value *OrigArg,
2607 unsigned OffsetFromOrigArg,
2609 bool ForceMutable) const {
2610 MachineFunction &MF = DAG.getMachineFunction();
2611 MachineFrameInfo *MFI = MF.getFrameInfo();
2612 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2613 unsigned firstRegToSaveIndex;
2614 if (CCInfo.isFirstByValRegValid())
2615 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2617 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2618 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2621 unsigned VARegSize, VARegSaveSize;
2622 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2623 if (VARegSaveSize) {
2624 // If this function is vararg, store any remaining integer argument regs
2625 // to their spots on the stack so that they may be loaded by deferencing
2626 // the result of va_next.
2627 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2628 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2629 ArgOffset + VARegSaveSize
2632 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2635 SmallVector<SDValue, 4> MemOps;
2636 for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2637 const TargetRegisterClass *RC;
2638 if (AFI->isThumb1OnlyFunction())
2639 RC = &ARM::tGPRRegClass;
2641 RC = &ARM::GPRRegClass;
2643 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2644 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2646 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2647 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2649 MemOps.push_back(Store);
2650 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2651 DAG.getConstant(4, getPointerTy()));
2653 if (!MemOps.empty())
2654 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2655 &MemOps[0], MemOps.size());
2657 // This will point to the next argument passed via stack.
2658 AFI->setVarArgsFrameIndex(
2659 MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2663 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2664 CallingConv::ID CallConv, bool isVarArg,
2665 const SmallVectorImpl<ISD::InputArg>
2667 DebugLoc dl, SelectionDAG &DAG,
2668 SmallVectorImpl<SDValue> &InVals)
2670 MachineFunction &MF = DAG.getMachineFunction();
2671 MachineFrameInfo *MFI = MF.getFrameInfo();
2673 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2675 // Assign locations to all of the incoming arguments.
2676 SmallVector<CCValAssign, 16> ArgLocs;
2677 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2678 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2679 CCInfo.AnalyzeFormalArguments(Ins,
2680 CCAssignFnForNode(CallConv, /* Return*/ false,
2683 SmallVector<SDValue, 16> ArgValues;
2684 int lastInsIndex = -1;
2686 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2687 unsigned CurArgIdx = 0;
2688 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2689 CCValAssign &VA = ArgLocs[i];
2690 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2691 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2692 // Arguments stored in registers.
2693 if (VA.isRegLoc()) {
2694 EVT RegVT = VA.getLocVT();
2696 if (VA.needsCustom()) {
2697 // f64 and vector types are split up into multiple registers or
2698 // combinations of registers and stack slots.
2699 if (VA.getLocVT() == MVT::v2f64) {
2700 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2702 VA = ArgLocs[++i]; // skip ahead to next loc
2704 if (VA.isMemLoc()) {
2705 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2706 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2707 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2708 MachinePointerInfo::getFixedStack(FI),
2709 false, false, false, 0);
2711 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2714 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2715 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2716 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2717 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2718 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2720 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2723 const TargetRegisterClass *RC;
2725 if (RegVT == MVT::f32)
2726 RC = &ARM::SPRRegClass;
2727 else if (RegVT == MVT::f64)
2728 RC = &ARM::DPRRegClass;
2729 else if (RegVT == MVT::v2f64)
2730 RC = &ARM::QPRRegClass;
2731 else if (RegVT == MVT::i32)
2732 RC = AFI->isThumb1OnlyFunction() ?
2733 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2734 (const TargetRegisterClass*)&ARM::GPRRegClass;
2736 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2738 // Transform the arguments in physical registers into virtual ones.
2739 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2740 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2743 // If this is an 8 or 16-bit value, it is really passed promoted
2744 // to 32 bits. Insert an assert[sz]ext to capture this, then
2745 // truncate to the right size.
2746 switch (VA.getLocInfo()) {
2747 default: llvm_unreachable("Unknown loc info!");
2748 case CCValAssign::Full: break;
2749 case CCValAssign::BCvt:
2750 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2752 case CCValAssign::SExt:
2753 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2754 DAG.getValueType(VA.getValVT()));
2755 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2757 case CCValAssign::ZExt:
2758 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2759 DAG.getValueType(VA.getValVT()));
2760 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2764 InVals.push_back(ArgValue);
2766 } else { // VA.isRegLoc()
2769 assert(VA.isMemLoc());
2770 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2772 int index = ArgLocs[i].getValNo();
2774 // Some Ins[] entries become multiple ArgLoc[] entries.
2775 // Process them only once.
2776 if (index != lastInsIndex)
2778 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2779 // FIXME: For now, all byval parameter objects are marked mutable.
2780 // This can be changed with more analysis.
2781 // In case of tail call optimization mark all arguments mutable.
2782 // Since they could be overwritten by lowering of arguments in case of
2784 if (Flags.isByVal()) {
2785 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2786 if (!AFI->getVarArgsFrameIndex()) {
2787 VarArgStyleRegisters(CCInfo, DAG,
2788 dl, Chain, CurOrigArg,
2789 Ins[VA.getValNo()].PartOffset,
2790 VA.getLocMemOffset(),
2791 true /*force mutable frames*/);
2792 int VAFrameIndex = AFI->getVarArgsFrameIndex();
2793 InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2795 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2796 VA.getLocMemOffset(), false);
2797 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2800 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2801 VA.getLocMemOffset(), true);
2803 // Create load nodes to retrieve arguments from the stack.
2804 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2805 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2806 MachinePointerInfo::getFixedStack(FI),
2807 false, false, false, 0));
2809 lastInsIndex = index;
2816 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2817 CCInfo.getNextStackOffset());
2822 /// isFloatingPointZero - Return true if this is +0.0.
2823 static bool isFloatingPointZero(SDValue Op) {
2824 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2825 return CFP->getValueAPF().isPosZero();
2826 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2827 // Maybe this has already been legalized into the constant pool?
2828 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2829 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2830 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2831 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2832 return CFP->getValueAPF().isPosZero();
2838 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2839 /// the given operands.
2841 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2842 SDValue &ARMcc, SelectionDAG &DAG,
2843 DebugLoc dl) const {
2844 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2845 unsigned C = RHSC->getZExtValue();
2846 if (!isLegalICmpImmediate(C)) {
2847 // Constant does not fit, try adjusting it by one?
2852 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2853 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2854 RHS = DAG.getConstant(C-1, MVT::i32);
2859 if (C != 0 && isLegalICmpImmediate(C-1)) {
2860 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2861 RHS = DAG.getConstant(C-1, MVT::i32);
2866 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2867 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2868 RHS = DAG.getConstant(C+1, MVT::i32);
2873 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2874 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2875 RHS = DAG.getConstant(C+1, MVT::i32);
2882 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2883 ARMISD::NodeType CompareType;
2886 CompareType = ARMISD::CMP;
2891 CompareType = ARMISD::CMPZ;
2894 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2895 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2898 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2900 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2901 DebugLoc dl) const {
2903 if (!isFloatingPointZero(RHS))
2904 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2906 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2907 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2910 /// duplicateCmp - Glue values can have only one use, so this function
2911 /// duplicates a comparison node.
2913 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2914 unsigned Opc = Cmp.getOpcode();
2915 DebugLoc DL = Cmp.getDebugLoc();
2916 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2917 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2919 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2920 Cmp = Cmp.getOperand(0);
2921 Opc = Cmp.getOpcode();
2922 if (Opc == ARMISD::CMPFP)
2923 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2925 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2926 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2928 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2931 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2932 SDValue Cond = Op.getOperand(0);
2933 SDValue SelectTrue = Op.getOperand(1);
2934 SDValue SelectFalse = Op.getOperand(2);
2935 DebugLoc dl = Op.getDebugLoc();
2939 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2940 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2942 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2943 const ConstantSDNode *CMOVTrue =
2944 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2945 const ConstantSDNode *CMOVFalse =
2946 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2948 if (CMOVTrue && CMOVFalse) {
2949 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2950 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2954 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2956 False = SelectFalse;
2957 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2962 if (True.getNode() && False.getNode()) {
2963 EVT VT = Op.getValueType();
2964 SDValue ARMcc = Cond.getOperand(2);
2965 SDValue CCR = Cond.getOperand(3);
2966 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2967 assert(True.getValueType() == VT);
2968 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2973 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2974 // undefined bits before doing a full-word comparison with zero.
2975 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2976 DAG.getConstant(1, Cond.getValueType()));
2978 return DAG.getSelectCC(dl, Cond,
2979 DAG.getConstant(0, Cond.getValueType()),
2980 SelectTrue, SelectFalse, ISD::SETNE);
2983 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2984 EVT VT = Op.getValueType();
2985 SDValue LHS = Op.getOperand(0);
2986 SDValue RHS = Op.getOperand(1);
2987 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2988 SDValue TrueVal = Op.getOperand(2);
2989 SDValue FalseVal = Op.getOperand(3);
2990 DebugLoc dl = Op.getDebugLoc();
2992 if (LHS.getValueType() == MVT::i32) {
2994 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2995 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2996 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2999 ARMCC::CondCodes CondCode, CondCode2;
3000 FPCCToARMCC(CC, CondCode, CondCode2);
3002 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3003 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3004 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3005 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3007 if (CondCode2 != ARMCC::AL) {
3008 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3009 // FIXME: Needs another CMP because flag can have but one use.
3010 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3011 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3012 Result, TrueVal, ARMcc2, CCR, Cmp2);
3017 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3018 /// to morph to an integer compare sequence.
3019 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3020 const ARMSubtarget *Subtarget) {
3021 SDNode *N = Op.getNode();
3022 if (!N->hasOneUse())
3023 // Otherwise it requires moving the value from fp to integer registers.
3025 if (!N->getNumValues())
3027 EVT VT = Op.getValueType();
3028 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3029 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3030 // vmrs are very slow, e.g. cortex-a8.
3033 if (isFloatingPointZero(Op)) {
3037 return ISD::isNormalLoad(N);
3040 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3041 if (isFloatingPointZero(Op))
3042 return DAG.getConstant(0, MVT::i32);
3044 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3045 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3046 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3047 Ld->isVolatile(), Ld->isNonTemporal(),
3048 Ld->isInvariant(), Ld->getAlignment());
3050 llvm_unreachable("Unknown VFP cmp argument!");
3053 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3054 SDValue &RetVal1, SDValue &RetVal2) {
3055 if (isFloatingPointZero(Op)) {
3056 RetVal1 = DAG.getConstant(0, MVT::i32);
3057 RetVal2 = DAG.getConstant(0, MVT::i32);
3061 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3062 SDValue Ptr = Ld->getBasePtr();
3063 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3064 Ld->getChain(), Ptr,
3065 Ld->getPointerInfo(),
3066 Ld->isVolatile(), Ld->isNonTemporal(),
3067 Ld->isInvariant(), Ld->getAlignment());
3069 EVT PtrType = Ptr.getValueType();
3070 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3071 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3072 PtrType, Ptr, DAG.getConstant(4, PtrType));
3073 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3074 Ld->getChain(), NewPtr,
3075 Ld->getPointerInfo().getWithOffset(4),
3076 Ld->isVolatile(), Ld->isNonTemporal(),
3077 Ld->isInvariant(), NewAlign);
3081 llvm_unreachable("Unknown VFP cmp argument!");
3084 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3085 /// f32 and even f64 comparisons to integer ones.
3087 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3088 SDValue Chain = Op.getOperand(0);
3089 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3090 SDValue LHS = Op.getOperand(2);
3091 SDValue RHS = Op.getOperand(3);
3092 SDValue Dest = Op.getOperand(4);
3093 DebugLoc dl = Op.getDebugLoc();
3095 bool LHSSeenZero = false;
3096 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3097 bool RHSSeenZero = false;
3098 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3099 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3100 // If unsafe fp math optimization is enabled and there are no other uses of
3101 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3102 // to an integer comparison.
3103 if (CC == ISD::SETOEQ)
3105 else if (CC == ISD::SETUNE)
3108 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3110 if (LHS.getValueType() == MVT::f32) {
3111 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3112 bitcastf32Toi32(LHS, DAG), Mask);
3113 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3114 bitcastf32Toi32(RHS, DAG), Mask);
3115 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3116 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3117 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3118 Chain, Dest, ARMcc, CCR, Cmp);
3123 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3124 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3125 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3126 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3127 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3128 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3129 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3130 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3131 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3137 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3138 SDValue Chain = Op.getOperand(0);
3139 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3140 SDValue LHS = Op.getOperand(2);
3141 SDValue RHS = Op.getOperand(3);
3142 SDValue Dest = Op.getOperand(4);
3143 DebugLoc dl = Op.getDebugLoc();
3145 if (LHS.getValueType() == MVT::i32) {
3147 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3148 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3149 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3150 Chain, Dest, ARMcc, CCR, Cmp);
3153 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3155 if (getTargetMachine().Options.UnsafeFPMath &&
3156 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3157 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3158 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3159 if (Result.getNode())
3163 ARMCC::CondCodes CondCode, CondCode2;
3164 FPCCToARMCC(CC, CondCode, CondCode2);
3166 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3167 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3168 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3169 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3170 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3171 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3172 if (CondCode2 != ARMCC::AL) {
3173 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3174 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3175 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3180 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3181 SDValue Chain = Op.getOperand(0);
3182 SDValue Table = Op.getOperand(1);
3183 SDValue Index = Op.getOperand(2);
3184 DebugLoc dl = Op.getDebugLoc();
3186 EVT PTy = getPointerTy();
3187 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3188 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3189 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3190 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3191 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3192 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3193 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3194 if (Subtarget->isThumb2()) {
3195 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3196 // which does another jump to the destination. This also makes it easier
3197 // to translate it to TBB / TBH later.
3198 // FIXME: This might not work if the function is extremely large.
3199 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3200 Addr, Op.getOperand(2), JTI, UId);
3202 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3203 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3204 MachinePointerInfo::getJumpTable(),
3205 false, false, false, 0);
3206 Chain = Addr.getValue(1);
3207 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3208 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3210 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3211 MachinePointerInfo::getJumpTable(),
3212 false, false, false, 0);
3213 Chain = Addr.getValue(1);
3214 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3218 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3219 EVT VT = Op.getValueType();
3220 DebugLoc dl = Op.getDebugLoc();
3222 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3223 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3225 return DAG.UnrollVectorOp(Op.getNode());
3228 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3229 "Invalid type for custom lowering!");
3230 if (VT != MVT::v4i16)
3231 return DAG.UnrollVectorOp(Op.getNode());
3233 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3234 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3237 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3238 EVT VT = Op.getValueType();
3240 return LowerVectorFP_TO_INT(Op, DAG);
3242 DebugLoc dl = Op.getDebugLoc();
3245 switch (Op.getOpcode()) {
3246 default: llvm_unreachable("Invalid opcode!");
3247 case ISD::FP_TO_SINT:
3248 Opc = ARMISD::FTOSI;
3250 case ISD::FP_TO_UINT:
3251 Opc = ARMISD::FTOUI;
3254 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3255 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3258 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3259 EVT VT = Op.getValueType();
3260 DebugLoc dl = Op.getDebugLoc();
3262 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3263 if (VT.getVectorElementType() == MVT::f32)
3265 return DAG.UnrollVectorOp(Op.getNode());
3268 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3269 "Invalid type for custom lowering!");
3270 if (VT != MVT::v4f32)
3271 return DAG.UnrollVectorOp(Op.getNode());
3275 switch (Op.getOpcode()) {
3276 default: llvm_unreachable("Invalid opcode!");
3277 case ISD::SINT_TO_FP:
3278 CastOpc = ISD::SIGN_EXTEND;
3279 Opc = ISD::SINT_TO_FP;
3281 case ISD::UINT_TO_FP:
3282 CastOpc = ISD::ZERO_EXTEND;
3283 Opc = ISD::UINT_TO_FP;
3287 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3288 return DAG.getNode(Opc, dl, VT, Op);
3291 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3292 EVT VT = Op.getValueType();
3294 return LowerVectorINT_TO_FP(Op, DAG);
3296 DebugLoc dl = Op.getDebugLoc();
3299 switch (Op.getOpcode()) {
3300 default: llvm_unreachable("Invalid opcode!");
3301 case ISD::SINT_TO_FP:
3302 Opc = ARMISD::SITOF;
3304 case ISD::UINT_TO_FP:
3305 Opc = ARMISD::UITOF;
3309 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3310 return DAG.getNode(Opc, dl, VT, Op);
3313 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3314 // Implement fcopysign with a fabs and a conditional fneg.
3315 SDValue Tmp0 = Op.getOperand(0);
3316 SDValue Tmp1 = Op.getOperand(1);
3317 DebugLoc dl = Op.getDebugLoc();
3318 EVT VT = Op.getValueType();
3319 EVT SrcVT = Tmp1.getValueType();
3320 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3321 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3322 bool UseNEON = !InGPR && Subtarget->hasNEON();
3325 // Use VBSL to copy the sign bit.
3326 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3327 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3328 DAG.getTargetConstant(EncodedVal, MVT::i32));
3329 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3331 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3332 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3333 DAG.getConstant(32, MVT::i32));
3334 else /*if (VT == MVT::f32)*/
3335 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3336 if (SrcVT == MVT::f32) {
3337 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3339 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3340 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3341 DAG.getConstant(32, MVT::i32));
3342 } else if (VT == MVT::f32)
3343 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3344 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3345 DAG.getConstant(32, MVT::i32));
3346 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3347 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3349 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3351 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3352 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3353 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3355 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3356 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3357 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3358 if (VT == MVT::f32) {
3359 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3360 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3361 DAG.getConstant(0, MVT::i32));
3363 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3369 // Bitcast operand 1 to i32.
3370 if (SrcVT == MVT::f64)
3371 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3372 &Tmp1, 1).getValue(1);
3373 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3375 // Or in the signbit with integer operations.
3376 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3377 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3378 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3379 if (VT == MVT::f32) {
3380 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3381 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3382 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3383 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3386 // f64: Or the high part with signbit and then combine two parts.
3387 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3389 SDValue Lo = Tmp0.getValue(0);
3390 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3391 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3392 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3395 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3396 MachineFunction &MF = DAG.getMachineFunction();
3397 MachineFrameInfo *MFI = MF.getFrameInfo();
3398 MFI->setReturnAddressIsTaken(true);
3400 EVT VT = Op.getValueType();
3401 DebugLoc dl = Op.getDebugLoc();
3402 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3404 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3405 SDValue Offset = DAG.getConstant(4, MVT::i32);
3406 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3407 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3408 MachinePointerInfo(), false, false, false, 0);
3411 // Return LR, which contains the return address. Mark it an implicit live-in.
3412 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3413 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3416 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3417 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3418 MFI->setFrameAddressIsTaken(true);
3420 EVT VT = Op.getValueType();
3421 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3422 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3423 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3424 ? ARM::R7 : ARM::R11;
3425 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3427 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3428 MachinePointerInfo(),
3429 false, false, false, 0);
3433 /// ExpandBITCAST - If the target supports VFP, this function is called to
3434 /// expand a bit convert where either the source or destination type is i64 to
3435 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3436 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3437 /// vectors), since the legalizer won't know what to do with that.
3438 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3439 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3440 DebugLoc dl = N->getDebugLoc();
3441 SDValue Op = N->getOperand(0);
3443 // This function is only supposed to be called for i64 types, either as the
3444 // source or destination of the bit convert.
3445 EVT SrcVT = Op.getValueType();
3446 EVT DstVT = N->getValueType(0);
3447 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3448 "ExpandBITCAST called for non-i64 type");
3450 // Turn i64->f64 into VMOVDRR.
3451 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3452 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3453 DAG.getConstant(0, MVT::i32));
3454 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3455 DAG.getConstant(1, MVT::i32));
3456 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3457 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3460 // Turn f64->i64 into VMOVRRD.
3461 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3462 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3463 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3464 // Merge the pieces into a single i64 value.
3465 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3471 /// getZeroVector - Returns a vector of specified type with all zero elements.
3472 /// Zero vectors are used to represent vector negation and in those cases
3473 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3474 /// not support i64 elements, so sometimes the zero vectors will need to be
3475 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3477 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3478 assert(VT.isVector() && "Expected a vector type");
3479 // The canonical modified immediate encoding of a zero vector is....0!
3480 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3481 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3482 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3483 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3486 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3487 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3488 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3489 SelectionDAG &DAG) const {
3490 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3491 EVT VT = Op.getValueType();
3492 unsigned VTBits = VT.getSizeInBits();
3493 DebugLoc dl = Op.getDebugLoc();
3494 SDValue ShOpLo = Op.getOperand(0);
3495 SDValue ShOpHi = Op.getOperand(1);
3496 SDValue ShAmt = Op.getOperand(2);
3498 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3500 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3502 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3503 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3504 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3505 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3506 DAG.getConstant(VTBits, MVT::i32));
3507 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3508 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3509 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3511 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3512 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3514 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3515 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3518 SDValue Ops[2] = { Lo, Hi };
3519 return DAG.getMergeValues(Ops, 2, dl);
3522 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3523 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3524 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3525 SelectionDAG &DAG) const {
3526 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3527 EVT VT = Op.getValueType();
3528 unsigned VTBits = VT.getSizeInBits();
3529 DebugLoc dl = Op.getDebugLoc();
3530 SDValue ShOpLo = Op.getOperand(0);
3531 SDValue ShOpHi = Op.getOperand(1);
3532 SDValue ShAmt = Op.getOperand(2);
3535 assert(Op.getOpcode() == ISD::SHL_PARTS);
3536 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3537 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3538 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3539 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3540 DAG.getConstant(VTBits, MVT::i32));
3541 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3542 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3544 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3545 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3546 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3548 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3549 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3552 SDValue Ops[2] = { Lo, Hi };
3553 return DAG.getMergeValues(Ops, 2, dl);
3556 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3557 SelectionDAG &DAG) const {
3558 // The rounding mode is in bits 23:22 of the FPSCR.
3559 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3560 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3561 // so that the shift + and get folded into a bitfield extract.
3562 DebugLoc dl = Op.getDebugLoc();
3563 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3564 DAG.getConstant(Intrinsic::arm_get_fpscr,
3566 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3567 DAG.getConstant(1U << 22, MVT::i32));
3568 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3569 DAG.getConstant(22, MVT::i32));
3570 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3571 DAG.getConstant(3, MVT::i32));
3574 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3575 const ARMSubtarget *ST) {
3576 EVT VT = N->getValueType(0);
3577 DebugLoc dl = N->getDebugLoc();
3579 if (!ST->hasV6T2Ops())
3582 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3583 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3586 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3587 /// for each 16-bit element from operand, repeated. The basic idea is to
3588 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3590 /// Trace for v4i16:
3591 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3592 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3593 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3594 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3595 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3596 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3597 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3598 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3599 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3600 EVT VT = N->getValueType(0);
3601 DebugLoc DL = N->getDebugLoc();
3603 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3604 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3605 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3606 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3607 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3608 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3611 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3612 /// bit-count for each 16-bit element from the operand. We need slightly
3613 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3614 /// 64/128-bit registers.
3616 /// Trace for v4i16:
3617 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3618 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3619 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3620 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3621 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3622 EVT VT = N->getValueType(0);
3623 DebugLoc DL = N->getDebugLoc();
3625 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3626 if (VT.is64BitVector()) {
3627 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3628 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3629 DAG.getIntPtrConstant(0));
3631 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3632 BitCounts, DAG.getIntPtrConstant(0));
3633 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3637 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3638 /// bit-count for each 32-bit element from the operand. The idea here is
3639 /// to split the vector into 16-bit elements, leverage the 16-bit count
3640 /// routine, and then combine the results.
3642 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3643 /// input = [v0 v1 ] (vi: 32-bit elements)
3644 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3645 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3646 /// vrev: N0 = [k1 k0 k3 k2 ]
3648 /// N1 =+[k1 k0 k3 k2 ]
3650 /// N2 =+[k1 k3 k0 k2 ]
3652 /// Extended =+[k1 k3 k0 k2 ]
3654 /// Extracted=+[k1 k3 ]
3656 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3657 EVT VT = N->getValueType(0);
3658 DebugLoc DL = N->getDebugLoc();
3660 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3662 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3663 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3664 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3665 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3666 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3668 if (VT.is64BitVector()) {
3669 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3670 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3671 DAG.getIntPtrConstant(0));
3673 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3674 DAG.getIntPtrConstant(0));
3675 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3679 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3680 const ARMSubtarget *ST) {
3681 EVT VT = N->getValueType(0);
3683 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3684 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3685 VT == MVT::v4i16 || VT == MVT::v8i16) &&
3686 "Unexpected type for custom ctpop lowering");
3688 if (VT.getVectorElementType() == MVT::i32)
3689 return lowerCTPOP32BitElements(N, DAG);
3691 return lowerCTPOP16BitElements(N, DAG);
3694 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3695 const ARMSubtarget *ST) {
3696 EVT VT = N->getValueType(0);
3697 DebugLoc dl = N->getDebugLoc();
3702 // Lower vector shifts on NEON to use VSHL.
3703 assert(ST->hasNEON() && "unexpected vector shift");
3705 // Left shifts translate directly to the vshiftu intrinsic.
3706 if (N->getOpcode() == ISD::SHL)
3707 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3708 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3709 N->getOperand(0), N->getOperand(1));
3711 assert((N->getOpcode() == ISD::SRA ||
3712 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3714 // NEON uses the same intrinsics for both left and right shifts. For
3715 // right shifts, the shift amounts are negative, so negate the vector of
3717 EVT ShiftVT = N->getOperand(1).getValueType();
3718 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3719 getZeroVector(ShiftVT, DAG, dl),
3721 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3722 Intrinsic::arm_neon_vshifts :
3723 Intrinsic::arm_neon_vshiftu);
3724 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3725 DAG.getConstant(vshiftInt, MVT::i32),
3726 N->getOperand(0), NegatedCount);
3729 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3730 const ARMSubtarget *ST) {
3731 EVT VT = N->getValueType(0);
3732 DebugLoc dl = N->getDebugLoc();
3734 // We can get here for a node like i32 = ISD::SHL i32, i64
3738 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3739 "Unknown shift to lower!");
3741 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3742 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3743 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3746 // If we are in thumb mode, we don't have RRX.
3747 if (ST->isThumb1Only()) return SDValue();
3749 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3750 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3751 DAG.getConstant(0, MVT::i32));
3752 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3753 DAG.getConstant(1, MVT::i32));
3755 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3756 // captures the result into a carry flag.
3757 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3758 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3760 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3761 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3763 // Merge the pieces into a single i64 value.
3764 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3767 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3768 SDValue TmpOp0, TmpOp1;
3769 bool Invert = false;
3773 SDValue Op0 = Op.getOperand(0);
3774 SDValue Op1 = Op.getOperand(1);
3775 SDValue CC = Op.getOperand(2);
3776 EVT VT = Op.getValueType();
3777 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3778 DebugLoc dl = Op.getDebugLoc();
3780 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3781 switch (SetCCOpcode) {
3782 default: llvm_unreachable("Illegal FP comparison");
3784 case ISD::SETNE: Invert = true; // Fallthrough
3786 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3788 case ISD::SETLT: Swap = true; // Fallthrough
3790 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3792 case ISD::SETLE: Swap = true; // Fallthrough
3794 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3795 case ISD::SETUGE: Swap = true; // Fallthrough
3796 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3797 case ISD::SETUGT: Swap = true; // Fallthrough
3798 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3799 case ISD::SETUEQ: Invert = true; // Fallthrough
3801 // Expand this to (OLT | OGT).
3805 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3806 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3808 case ISD::SETUO: Invert = true; // Fallthrough
3810 // Expand this to (OLT | OGE).
3814 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3815 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3819 // Integer comparisons.
3820 switch (SetCCOpcode) {
3821 default: llvm_unreachable("Illegal integer comparison");
3822 case ISD::SETNE: Invert = true;
3823 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3824 case ISD::SETLT: Swap = true;
3825 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3826 case ISD::SETLE: Swap = true;
3827 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3828 case ISD::SETULT: Swap = true;
3829 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3830 case ISD::SETULE: Swap = true;
3831 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3834 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3835 if (Opc == ARMISD::VCEQ) {
3838 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3840 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3843 // Ignore bitconvert.
3844 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3845 AndOp = AndOp.getOperand(0);
3847 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3849 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3850 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3857 std::swap(Op0, Op1);
3859 // If one of the operands is a constant vector zero, attempt to fold the
3860 // comparison to a specialized compare-against-zero form.
3862 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3864 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3865 if (Opc == ARMISD::VCGE)
3866 Opc = ARMISD::VCLEZ;
3867 else if (Opc == ARMISD::VCGT)
3868 Opc = ARMISD::VCLTZ;
3873 if (SingleOp.getNode()) {
3876 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3878 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3880 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3882 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3884 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3886 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3889 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3893 Result = DAG.getNOT(dl, Result, VT);
3898 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3899 /// valid vector constant for a NEON instruction with a "modified immediate"
3900 /// operand (e.g., VMOV). If so, return the encoded value.
3901 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3902 unsigned SplatBitSize, SelectionDAG &DAG,
3903 EVT &VT, bool is128Bits, NEONModImmType type) {
3904 unsigned OpCmode, Imm;
3906 // SplatBitSize is set to the smallest size that splats the vector, so a
3907 // zero vector will always have SplatBitSize == 8. However, NEON modified
3908 // immediate instructions others than VMOV do not support the 8-bit encoding
3909 // of a zero vector, and the default encoding of zero is supposed to be the
3914 switch (SplatBitSize) {
3916 if (type != VMOVModImm)
3918 // Any 1-byte value is OK. Op=0, Cmode=1110.
3919 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3922 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3926 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3927 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3928 if ((SplatBits & ~0xff) == 0) {
3929 // Value = 0x00nn: Op=x, Cmode=100x.
3934 if ((SplatBits & ~0xff00) == 0) {
3935 // Value = 0xnn00: Op=x, Cmode=101x.
3937 Imm = SplatBits >> 8;
3943 // NEON's 32-bit VMOV supports splat values where:
3944 // * only one byte is nonzero, or
3945 // * the least significant byte is 0xff and the second byte is nonzero, or
3946 // * the least significant 2 bytes are 0xff and the third is nonzero.
3947 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3948 if ((SplatBits & ~0xff) == 0) {
3949 // Value = 0x000000nn: Op=x, Cmode=000x.
3954 if ((SplatBits & ~0xff00) == 0) {
3955 // Value = 0x0000nn00: Op=x, Cmode=001x.
3957 Imm = SplatBits >> 8;
3960 if ((SplatBits & ~0xff0000) == 0) {
3961 // Value = 0x00nn0000: Op=x, Cmode=010x.
3963 Imm = SplatBits >> 16;
3966 if ((SplatBits & ~0xff000000) == 0) {
3967 // Value = 0xnn000000: Op=x, Cmode=011x.
3969 Imm = SplatBits >> 24;
3973 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3974 if (type == OtherModImm) return SDValue();
3976 if ((SplatBits & ~0xffff) == 0 &&
3977 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3978 // Value = 0x0000nnff: Op=x, Cmode=1100.
3980 Imm = SplatBits >> 8;
3985 if ((SplatBits & ~0xffffff) == 0 &&
3986 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3987 // Value = 0x00nnffff: Op=x, Cmode=1101.
3989 Imm = SplatBits >> 16;
3990 SplatBits |= 0xffff;
3994 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3995 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3996 // VMOV.I32. A (very) minor optimization would be to replicate the value
3997 // and fall through here to test for a valid 64-bit splat. But, then the
3998 // caller would also need to check and handle the change in size.
4002 if (type != VMOVModImm)
4004 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4005 uint64_t BitMask = 0xff;
4007 unsigned ImmMask = 1;
4009 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4010 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4013 } else if ((SplatBits & BitMask) != 0) {
4019 // Op=1, Cmode=1110.
4022 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4027 llvm_unreachable("unexpected size for isNEONModifiedImm");
4030 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4031 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4034 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4035 const ARMSubtarget *ST) const {
4036 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4039 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4040 assert(Op.getValueType() == MVT::f32 &&
4041 "ConstantFP custom lowering should only occur for f32.");
4043 // Try splatting with a VMOV.f32...
4044 APFloat FPVal = CFP->getValueAPF();
4045 int ImmVal = ARM_AM::getFP32Imm(FPVal);
4047 DebugLoc DL = Op.getDebugLoc();
4048 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4049 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4051 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4052 DAG.getConstant(0, MVT::i32));
4055 // If that fails, try a VMOV.i32
4057 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4058 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4060 if (NewVal != SDValue()) {
4061 DebugLoc DL = Op.getDebugLoc();
4062 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4064 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4066 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4067 DAG.getConstant(0, MVT::i32));
4070 // Finally, try a VMVN.i32
4071 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4073 if (NewVal != SDValue()) {
4074 DebugLoc DL = Op.getDebugLoc();
4075 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4076 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4078 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4079 DAG.getConstant(0, MVT::i32));
4085 // check if an VEXT instruction can handle the shuffle mask when the
4086 // vector sources of the shuffle are the same.
4087 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4088 unsigned NumElts = VT.getVectorNumElements();
4090 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4096 // If this is a VEXT shuffle, the immediate value is the index of the first
4097 // element. The other shuffle indices must be the successive elements after
4099 unsigned ExpectedElt = Imm;
4100 for (unsigned i = 1; i < NumElts; ++i) {
4101 // Increment the expected index. If it wraps around, just follow it
4102 // back to index zero and keep going.
4104 if (ExpectedElt == NumElts)
4107 if (M[i] < 0) continue; // ignore UNDEF indices
4108 if (ExpectedElt != static_cast<unsigned>(M[i]))
4116 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4117 bool &ReverseVEXT, unsigned &Imm) {
4118 unsigned NumElts = VT.getVectorNumElements();
4119 ReverseVEXT = false;
4121 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4127 // If this is a VEXT shuffle, the immediate value is the index of the first
4128 // element. The other shuffle indices must be the successive elements after
4130 unsigned ExpectedElt = Imm;
4131 for (unsigned i = 1; i < NumElts; ++i) {
4132 // Increment the expected index. If it wraps around, it may still be
4133 // a VEXT but the source vectors must be swapped.
4135 if (ExpectedElt == NumElts * 2) {
4140 if (M[i] < 0) continue; // ignore UNDEF indices
4141 if (ExpectedElt != static_cast<unsigned>(M[i]))
4145 // Adjust the index value if the source operands will be swapped.
4152 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4153 /// instruction with the specified blocksize. (The order of the elements
4154 /// within each block of the vector is reversed.)
4155 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4156 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4157 "Only possible block sizes for VREV are: 16, 32, 64");
4159 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4163 unsigned NumElts = VT.getVectorNumElements();
4164 unsigned BlockElts = M[0] + 1;
4165 // If the first shuffle index is UNDEF, be optimistic.
4167 BlockElts = BlockSize / EltSz;
4169 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4172 for (unsigned i = 0; i < NumElts; ++i) {
4173 if (M[i] < 0) continue; // ignore UNDEF indices
4174 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4181 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4182 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4183 // range, then 0 is placed into the resulting vector. So pretty much any mask
4184 // of 8 elements can work here.
4185 return VT == MVT::v8i8 && M.size() == 8;
4188 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4189 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4193 unsigned NumElts = VT.getVectorNumElements();
4194 WhichResult = (M[0] == 0 ? 0 : 1);
4195 for (unsigned i = 0; i < NumElts; i += 2) {
4196 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4197 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4203 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4204 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4205 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4206 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4207 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4211 unsigned NumElts = VT.getVectorNumElements();
4212 WhichResult = (M[0] == 0 ? 0 : 1);
4213 for (unsigned i = 0; i < NumElts; i += 2) {
4214 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4215 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4221 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4222 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4226 unsigned NumElts = VT.getVectorNumElements();
4227 WhichResult = (M[0] == 0 ? 0 : 1);
4228 for (unsigned i = 0; i != NumElts; ++i) {
4229 if (M[i] < 0) continue; // ignore UNDEF indices
4230 if ((unsigned) M[i] != 2 * i + WhichResult)
4234 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4235 if (VT.is64BitVector() && EltSz == 32)
4241 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4242 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4243 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4244 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4245 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4249 unsigned Half = VT.getVectorNumElements() / 2;
4250 WhichResult = (M[0] == 0 ? 0 : 1);
4251 for (unsigned j = 0; j != 2; ++j) {
4252 unsigned Idx = WhichResult;
4253 for (unsigned i = 0; i != Half; ++i) {
4254 int MIdx = M[i + j * Half];
4255 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4261 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4262 if (VT.is64BitVector() && EltSz == 32)
4268 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4269 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4273 unsigned NumElts = VT.getVectorNumElements();
4274 WhichResult = (M[0] == 0 ? 0 : 1);
4275 unsigned Idx = WhichResult * NumElts / 2;
4276 for (unsigned i = 0; i != NumElts; i += 2) {
4277 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4278 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4283 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4284 if (VT.is64BitVector() && EltSz == 32)
4290 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4291 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4292 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4293 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4294 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4298 unsigned NumElts = VT.getVectorNumElements();
4299 WhichResult = (M[0] == 0 ? 0 : 1);
4300 unsigned Idx = WhichResult * NumElts / 2;
4301 for (unsigned i = 0; i != NumElts; i += 2) {
4302 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4303 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4308 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4309 if (VT.is64BitVector() && EltSz == 32)
4315 // If N is an integer constant that can be moved into a register in one
4316 // instruction, return an SDValue of such a constant (will become a MOV
4317 // instruction). Otherwise return null.
4318 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4319 const ARMSubtarget *ST, DebugLoc dl) {
4321 if (!isa<ConstantSDNode>(N))
4323 Val = cast<ConstantSDNode>(N)->getZExtValue();
4325 if (ST->isThumb1Only()) {
4326 if (Val <= 255 || ~Val <= 255)
4327 return DAG.getConstant(Val, MVT::i32);
4329 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4330 return DAG.getConstant(Val, MVT::i32);
4335 // If this is a case we can't handle, return null and let the default
4336 // expansion code take care of it.
4337 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4338 const ARMSubtarget *ST) const {
4339 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4340 DebugLoc dl = Op.getDebugLoc();
4341 EVT VT = Op.getValueType();
4343 APInt SplatBits, SplatUndef;
4344 unsigned SplatBitSize;
4346 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4347 if (SplatBitSize <= 64) {
4348 // Check if an immediate VMOV works.
4350 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4351 SplatUndef.getZExtValue(), SplatBitSize,
4352 DAG, VmovVT, VT.is128BitVector(),
4354 if (Val.getNode()) {
4355 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4356 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4359 // Try an immediate VMVN.
4360 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4361 Val = isNEONModifiedImm(NegatedImm,
4362 SplatUndef.getZExtValue(), SplatBitSize,
4363 DAG, VmovVT, VT.is128BitVector(),
4365 if (Val.getNode()) {
4366 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4367 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4370 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4371 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4372 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4374 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4375 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4381 // Scan through the operands to see if only one value is used.
4383 // As an optimisation, even if more than one value is used it may be more
4384 // profitable to splat with one value then change some lanes.
4386 // Heuristically we decide to do this if the vector has a "dominant" value,
4387 // defined as splatted to more than half of the lanes.
4388 unsigned NumElts = VT.getVectorNumElements();
4389 bool isOnlyLowElement = true;
4390 bool usesOnlyOneValue = true;
4391 bool hasDominantValue = false;
4392 bool isConstant = true;
4394 // Map of the number of times a particular SDValue appears in the
4396 DenseMap<SDValue, unsigned> ValueCounts;
4398 for (unsigned i = 0; i < NumElts; ++i) {
4399 SDValue V = Op.getOperand(i);
4400 if (V.getOpcode() == ISD::UNDEF)
4403 isOnlyLowElement = false;
4404 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4407 ValueCounts.insert(std::make_pair(V, 0));
4408 unsigned &Count = ValueCounts[V];
4410 // Is this value dominant? (takes up more than half of the lanes)
4411 if (++Count > (NumElts / 2)) {
4412 hasDominantValue = true;
4416 if (ValueCounts.size() != 1)
4417 usesOnlyOneValue = false;
4418 if (!Value.getNode() && ValueCounts.size() > 0)
4419 Value = ValueCounts.begin()->first;
4421 if (ValueCounts.size() == 0)
4422 return DAG.getUNDEF(VT);
4424 if (isOnlyLowElement)
4425 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4427 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4429 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4430 // i32 and try again.
4431 if (hasDominantValue && EltSize <= 32) {
4435 // If we are VDUPing a value that comes directly from a vector, that will
4436 // cause an unnecessary move to and from a GPR, where instead we could
4437 // just use VDUPLANE.
4438 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4439 // We need to create a new undef vector to use for the VDUPLANE if the
4440 // size of the vector from which we get the value is different than the
4441 // size of the vector that we need to create. We will insert the element
4442 // such that the register coalescer will remove unnecessary copies.
4443 if (VT != Value->getOperand(0).getValueType()) {
4444 ConstantSDNode *constIndex;
4445 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4446 assert(constIndex && "The index is not a constant!");
4447 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4448 VT.getVectorNumElements();
4449 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4450 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4451 Value, DAG.getConstant(index, MVT::i32)),
4452 DAG.getConstant(index, MVT::i32));
4454 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4455 Value->getOperand(0), Value->getOperand(1));
4459 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4461 if (!usesOnlyOneValue) {
4462 // The dominant value was splatted as 'N', but we now have to insert
4463 // all differing elements.
4464 for (unsigned I = 0; I < NumElts; ++I) {
4465 if (Op.getOperand(I) == Value)
4467 SmallVector<SDValue, 3> Ops;
4469 Ops.push_back(Op.getOperand(I));
4470 Ops.push_back(DAG.getConstant(I, MVT::i32));
4471 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4476 if (VT.getVectorElementType().isFloatingPoint()) {
4477 SmallVector<SDValue, 8> Ops;
4478 for (unsigned i = 0; i < NumElts; ++i)
4479 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4481 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4482 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4483 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4485 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4487 if (usesOnlyOneValue) {
4488 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4489 if (isConstant && Val.getNode())
4490 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4494 // If all elements are constants and the case above didn't get hit, fall back
4495 // to the default expansion, which will generate a load from the constant
4500 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4502 SDValue shuffle = ReconstructShuffle(Op, DAG);
4503 if (shuffle != SDValue())
4507 // Vectors with 32- or 64-bit elements can be built by directly assigning
4508 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4509 // will be legalized.
4510 if (EltSize >= 32) {
4511 // Do the expansion with floating-point types, since that is what the VFP
4512 // registers are defined to use, and since i64 is not legal.
4513 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4514 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4515 SmallVector<SDValue, 8> Ops;
4516 for (unsigned i = 0; i < NumElts; ++i)
4517 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4518 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4519 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4525 // Gather data to see if the operation can be modelled as a
4526 // shuffle in combination with VEXTs.
4527 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4528 SelectionDAG &DAG) const {
4529 DebugLoc dl = Op.getDebugLoc();
4530 EVT VT = Op.getValueType();
4531 unsigned NumElts = VT.getVectorNumElements();
4533 SmallVector<SDValue, 2> SourceVecs;
4534 SmallVector<unsigned, 2> MinElts;
4535 SmallVector<unsigned, 2> MaxElts;
4537 for (unsigned i = 0; i < NumElts; ++i) {
4538 SDValue V = Op.getOperand(i);
4539 if (V.getOpcode() == ISD::UNDEF)
4541 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4542 // A shuffle can only come from building a vector from various
4543 // elements of other vectors.
4545 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4546 VT.getVectorElementType()) {
4547 // This code doesn't know how to handle shuffles where the vector
4548 // element types do not match (this happens because type legalization
4549 // promotes the return type of EXTRACT_VECTOR_ELT).
4550 // FIXME: It might be appropriate to extend this code to handle
4551 // mismatched types.
4555 // Record this extraction against the appropriate vector if possible...
4556 SDValue SourceVec = V.getOperand(0);
4557 // If the element number isn't a constant, we can't effectively
4558 // analyze what's going on.
4559 if (!isa<ConstantSDNode>(V.getOperand(1)))
4561 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4562 bool FoundSource = false;
4563 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4564 if (SourceVecs[j] == SourceVec) {
4565 if (MinElts[j] > EltNo)
4567 if (MaxElts[j] < EltNo)
4574 // Or record a new source if not...
4576 SourceVecs.push_back(SourceVec);
4577 MinElts.push_back(EltNo);
4578 MaxElts.push_back(EltNo);
4582 // Currently only do something sane when at most two source vectors
4584 if (SourceVecs.size() > 2)
4587 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4588 int VEXTOffsets[2] = {0, 0};
4590 // This loop extracts the usage patterns of the source vectors
4591 // and prepares appropriate SDValues for a shuffle if possible.
4592 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4593 if (SourceVecs[i].getValueType() == VT) {
4594 // No VEXT necessary
4595 ShuffleSrcs[i] = SourceVecs[i];
4598 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4599 // It probably isn't worth padding out a smaller vector just to
4600 // break it down again in a shuffle.
4604 // Since only 64-bit and 128-bit vectors are legal on ARM and
4605 // we've eliminated the other cases...
4606 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4607 "unexpected vector sizes in ReconstructShuffle");
4609 if (MaxElts[i] - MinElts[i] >= NumElts) {
4610 // Span too large for a VEXT to cope
4614 if (MinElts[i] >= NumElts) {
4615 // The extraction can just take the second half
4616 VEXTOffsets[i] = NumElts;
4617 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4619 DAG.getIntPtrConstant(NumElts));
4620 } else if (MaxElts[i] < NumElts) {
4621 // The extraction can just take the first half
4623 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4625 DAG.getIntPtrConstant(0));
4627 // An actual VEXT is needed
4628 VEXTOffsets[i] = MinElts[i];
4629 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4631 DAG.getIntPtrConstant(0));
4632 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4634 DAG.getIntPtrConstant(NumElts));
4635 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4636 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4640 SmallVector<int, 8> Mask;
4642 for (unsigned i = 0; i < NumElts; ++i) {
4643 SDValue Entry = Op.getOperand(i);
4644 if (Entry.getOpcode() == ISD::UNDEF) {
4649 SDValue ExtractVec = Entry.getOperand(0);
4650 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4651 .getOperand(1))->getSExtValue();
4652 if (ExtractVec == SourceVecs[0]) {
4653 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4655 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4659 // Final check before we try to produce nonsense...
4660 if (isShuffleMaskLegal(Mask, VT))
4661 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4667 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4668 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4669 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4670 /// are assumed to be legal.
4672 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4674 if (VT.getVectorNumElements() == 4 &&
4675 (VT.is128BitVector() || VT.is64BitVector())) {
4676 unsigned PFIndexes[4];
4677 for (unsigned i = 0; i != 4; ++i) {
4681 PFIndexes[i] = M[i];
4684 // Compute the index in the perfect shuffle table.
4685 unsigned PFTableIndex =
4686 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4687 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4688 unsigned Cost = (PFEntry >> 30);
4695 unsigned Imm, WhichResult;
4697 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4698 return (EltSize >= 32 ||
4699 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4700 isVREVMask(M, VT, 64) ||
4701 isVREVMask(M, VT, 32) ||
4702 isVREVMask(M, VT, 16) ||
4703 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4704 isVTBLMask(M, VT) ||
4705 isVTRNMask(M, VT, WhichResult) ||
4706 isVUZPMask(M, VT, WhichResult) ||
4707 isVZIPMask(M, VT, WhichResult) ||
4708 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4709 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4710 isVZIP_v_undef_Mask(M, VT, WhichResult));
4713 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4714 /// the specified operations to build the shuffle.
4715 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4716 SDValue RHS, SelectionDAG &DAG,
4718 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4719 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4720 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4723 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4732 OP_VUZPL, // VUZP, left result
4733 OP_VUZPR, // VUZP, right result
4734 OP_VZIPL, // VZIP, left result
4735 OP_VZIPR, // VZIP, right result
4736 OP_VTRNL, // VTRN, left result
4737 OP_VTRNR // VTRN, right result
4740 if (OpNum == OP_COPY) {
4741 if (LHSID == (1*9+2)*9+3) return LHS;
4742 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4746 SDValue OpLHS, OpRHS;
4747 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4748 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4749 EVT VT = OpLHS.getValueType();
4752 default: llvm_unreachable("Unknown shuffle opcode!");
4754 // VREV divides the vector in half and swaps within the half.
4755 if (VT.getVectorElementType() == MVT::i32 ||
4756 VT.getVectorElementType() == MVT::f32)
4757 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4758 // vrev <4 x i16> -> VREV32
4759 if (VT.getVectorElementType() == MVT::i16)
4760 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4761 // vrev <4 x i8> -> VREV16
4762 assert(VT.getVectorElementType() == MVT::i8);
4763 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4768 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4769 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4773 return DAG.getNode(ARMISD::VEXT, dl, VT,
4775 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4778 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4779 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4782 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4783 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4786 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4787 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4791 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4792 ArrayRef<int> ShuffleMask,
4793 SelectionDAG &DAG) {
4794 // Check to see if we can use the VTBL instruction.
4795 SDValue V1 = Op.getOperand(0);
4796 SDValue V2 = Op.getOperand(1);
4797 DebugLoc DL = Op.getDebugLoc();
4799 SmallVector<SDValue, 8> VTBLMask;
4800 for (ArrayRef<int>::iterator
4801 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4802 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4804 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4805 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4806 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4809 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4810 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4814 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4815 SDValue V1 = Op.getOperand(0);
4816 SDValue V2 = Op.getOperand(1);
4817 DebugLoc dl = Op.getDebugLoc();
4818 EVT VT = Op.getValueType();
4819 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4821 // Convert shuffles that are directly supported on NEON to target-specific
4822 // DAG nodes, instead of keeping them as shuffles and matching them again
4823 // during code selection. This is more efficient and avoids the possibility
4824 // of inconsistencies between legalization and selection.
4825 // FIXME: floating-point vectors should be canonicalized to integer vectors
4826 // of the same time so that they get CSEd properly.
4827 ArrayRef<int> ShuffleMask = SVN->getMask();
4829 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4830 if (EltSize <= 32) {
4831 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4832 int Lane = SVN->getSplatIndex();
4833 // If this is undef splat, generate it via "just" vdup, if possible.
4834 if (Lane == -1) Lane = 0;
4836 // Test if V1 is a SCALAR_TO_VECTOR.
4837 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4838 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4840 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4841 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4843 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4844 !isa<ConstantSDNode>(V1.getOperand(0))) {
4845 bool IsScalarToVector = true;
4846 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4847 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4848 IsScalarToVector = false;
4851 if (IsScalarToVector)
4852 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4854 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4855 DAG.getConstant(Lane, MVT::i32));
4860 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4863 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4864 DAG.getConstant(Imm, MVT::i32));
4867 if (isVREVMask(ShuffleMask, VT, 64))
4868 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4869 if (isVREVMask(ShuffleMask, VT, 32))
4870 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4871 if (isVREVMask(ShuffleMask, VT, 16))
4872 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4874 if (V2->getOpcode() == ISD::UNDEF &&
4875 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4876 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4877 DAG.getConstant(Imm, MVT::i32));
4880 // Check for Neon shuffles that modify both input vectors in place.
4881 // If both results are used, i.e., if there are two shuffles with the same
4882 // source operands and with masks corresponding to both results of one of
4883 // these operations, DAG memoization will ensure that a single node is
4884 // used for both shuffles.
4885 unsigned WhichResult;
4886 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4887 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4888 V1, V2).getValue(WhichResult);
4889 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4890 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4891 V1, V2).getValue(WhichResult);
4892 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4893 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4894 V1, V2).getValue(WhichResult);
4896 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4897 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4898 V1, V1).getValue(WhichResult);
4899 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4900 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4901 V1, V1).getValue(WhichResult);
4902 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4903 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4904 V1, V1).getValue(WhichResult);
4907 // If the shuffle is not directly supported and it has 4 elements, use
4908 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4909 unsigned NumElts = VT.getVectorNumElements();
4911 unsigned PFIndexes[4];
4912 for (unsigned i = 0; i != 4; ++i) {
4913 if (ShuffleMask[i] < 0)
4916 PFIndexes[i] = ShuffleMask[i];
4919 // Compute the index in the perfect shuffle table.
4920 unsigned PFTableIndex =
4921 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4922 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4923 unsigned Cost = (PFEntry >> 30);
4926 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4929 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4930 if (EltSize >= 32) {
4931 // Do the expansion with floating-point types, since that is what the VFP
4932 // registers are defined to use, and since i64 is not legal.
4933 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4934 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4935 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4936 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4937 SmallVector<SDValue, 8> Ops;
4938 for (unsigned i = 0; i < NumElts; ++i) {
4939 if (ShuffleMask[i] < 0)
4940 Ops.push_back(DAG.getUNDEF(EltVT));
4942 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4943 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4944 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4947 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4948 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4951 if (VT == MVT::v8i8) {
4952 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4953 if (NewOp.getNode())
4960 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4961 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4962 SDValue Lane = Op.getOperand(2);
4963 if (!isa<ConstantSDNode>(Lane))
4969 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4970 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4971 SDValue Lane = Op.getOperand(1);
4972 if (!isa<ConstantSDNode>(Lane))
4975 SDValue Vec = Op.getOperand(0);
4976 if (Op.getValueType() == MVT::i32 &&
4977 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4978 DebugLoc dl = Op.getDebugLoc();
4979 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4985 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4986 // The only time a CONCAT_VECTORS operation can have legal types is when
4987 // two 64-bit vectors are concatenated to a 128-bit vector.
4988 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4989 "unexpected CONCAT_VECTORS");
4990 DebugLoc dl = Op.getDebugLoc();
4991 SDValue Val = DAG.getUNDEF(MVT::v2f64);
4992 SDValue Op0 = Op.getOperand(0);
4993 SDValue Op1 = Op.getOperand(1);
4994 if (Op0.getOpcode() != ISD::UNDEF)
4995 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4996 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4997 DAG.getIntPtrConstant(0));
4998 if (Op1.getOpcode() != ISD::UNDEF)
4999 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5000 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5001 DAG.getIntPtrConstant(1));
5002 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5005 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5006 /// element has been zero/sign-extended, depending on the isSigned parameter,
5007 /// from an integer type half its size.
5008 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5010 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5011 EVT VT = N->getValueType(0);
5012 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5013 SDNode *BVN = N->getOperand(0).getNode();
5014 if (BVN->getValueType(0) != MVT::v4i32 ||
5015 BVN->getOpcode() != ISD::BUILD_VECTOR)
5017 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5018 unsigned HiElt = 1 - LoElt;
5019 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5020 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5021 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5022 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5023 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5026 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5027 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5030 if (Hi0->isNullValue() && Hi1->isNullValue())
5036 if (N->getOpcode() != ISD::BUILD_VECTOR)
5039 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5040 SDNode *Elt = N->getOperand(i).getNode();
5041 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5042 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5043 unsigned HalfSize = EltSize / 2;
5045 if (!isIntN(HalfSize, C->getSExtValue()))
5048 if (!isUIntN(HalfSize, C->getZExtValue()))
5059 /// isSignExtended - Check if a node is a vector value that is sign-extended
5060 /// or a constant BUILD_VECTOR with sign-extended elements.
5061 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5062 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5064 if (isExtendedBUILD_VECTOR(N, DAG, true))
5069 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5070 /// or a constant BUILD_VECTOR with zero-extended elements.
5071 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5072 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5074 if (isExtendedBUILD_VECTOR(N, DAG, false))
5079 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5080 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5081 /// We insert the required extension here to get the vector to fill a D register.
5082 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5085 unsigned ExtOpcode) {
5086 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5087 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5088 // 64-bits we need to insert a new extension so that it will be 64-bits.
5089 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5090 if (OrigTy.getSizeInBits() >= 64)
5093 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5094 MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5096 switch (OrigSimpleTy) {
5097 default: llvm_unreachable("Unexpected Orig Vector Type");
5106 return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5109 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5110 /// does not do any sign/zero extension. If the original vector is less
5111 /// than 64 bits, an appropriate extension will be added after the load to
5112 /// reach a total size of 64 bits. We have to add the extension separately
5113 /// because ARM does not have a sign/zero extending load for vectors.
5114 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5115 SDValue NonExtendingLoad =
5116 DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5117 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5118 LD->isNonTemporal(), LD->isInvariant(),
5119 LD->getAlignment());
5121 switch (LD->getExtensionType()) {
5122 default: llvm_unreachable("Unexpected LoadExtType");
5124 case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5125 case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5127 MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5128 MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5129 return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5130 MemType, ExtType, ExtOp);
5133 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5134 /// extending load, or BUILD_VECTOR with extended elements, return the
5135 /// unextended value. The unextended vector should be 64 bits so that it can
5136 /// be used as an operand to a VMULL instruction. If the original vector size
5137 /// before extension is less than 64 bits we add a an extension to resize
5138 /// the vector to 64 bits.
5139 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5140 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5141 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5142 N->getOperand(0)->getValueType(0),
5146 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5147 return SkipLoadExtensionForVMULL(LD, DAG);
5149 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5150 // have been legalized as a BITCAST from v4i32.
5151 if (N->getOpcode() == ISD::BITCAST) {
5152 SDNode *BVN = N->getOperand(0).getNode();
5153 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5154 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5155 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5156 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5157 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5159 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5160 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5161 EVT VT = N->getValueType(0);
5162 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5163 unsigned NumElts = VT.getVectorNumElements();
5164 MVT TruncVT = MVT::getIntegerVT(EltSize);
5165 SmallVector<SDValue, 8> Ops;
5166 for (unsigned i = 0; i != NumElts; ++i) {
5167 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5168 const APInt &CInt = C->getAPIntValue();
5169 // Element types smaller than 32 bits are not legal, so use i32 elements.
5170 // The values are implicitly truncated so sext vs. zext doesn't matter.
5171 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5173 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5174 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5177 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5178 unsigned Opcode = N->getOpcode();
5179 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5180 SDNode *N0 = N->getOperand(0).getNode();
5181 SDNode *N1 = N->getOperand(1).getNode();
5182 return N0->hasOneUse() && N1->hasOneUse() &&
5183 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5188 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5189 unsigned Opcode = N->getOpcode();
5190 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5191 SDNode *N0 = N->getOperand(0).getNode();
5192 SDNode *N1 = N->getOperand(1).getNode();
5193 return N0->hasOneUse() && N1->hasOneUse() &&
5194 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5199 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5200 // Multiplications are only custom-lowered for 128-bit vectors so that
5201 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5202 EVT VT = Op.getValueType();
5203 assert(VT.is128BitVector() && VT.isInteger() &&
5204 "unexpected type for custom-lowering ISD::MUL");
5205 SDNode *N0 = Op.getOperand(0).getNode();
5206 SDNode *N1 = Op.getOperand(1).getNode();
5207 unsigned NewOpc = 0;
5209 bool isN0SExt = isSignExtended(N0, DAG);
5210 bool isN1SExt = isSignExtended(N1, DAG);
5211 if (isN0SExt && isN1SExt)
5212 NewOpc = ARMISD::VMULLs;
5214 bool isN0ZExt = isZeroExtended(N0, DAG);
5215 bool isN1ZExt = isZeroExtended(N1, DAG);
5216 if (isN0ZExt && isN1ZExt)
5217 NewOpc = ARMISD::VMULLu;
5218 else if (isN1SExt || isN1ZExt) {
5219 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5220 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5221 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5222 NewOpc = ARMISD::VMULLs;
5224 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5225 NewOpc = ARMISD::VMULLu;
5227 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5229 NewOpc = ARMISD::VMULLu;
5235 if (VT == MVT::v2i64)
5236 // Fall through to expand this. It is not legal.
5239 // Other vector multiplications are legal.
5244 // Legalize to a VMULL instruction.
5245 DebugLoc DL = Op.getDebugLoc();
5247 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5249 Op0 = SkipExtensionForVMULL(N0, DAG);
5250 assert(Op0.getValueType().is64BitVector() &&
5251 Op1.getValueType().is64BitVector() &&
5252 "unexpected types for extended operands to VMULL");
5253 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5256 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5257 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5264 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5265 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5266 EVT Op1VT = Op1.getValueType();
5267 return DAG.getNode(N0->getOpcode(), DL, VT,
5268 DAG.getNode(NewOpc, DL, VT,
5269 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5270 DAG.getNode(NewOpc, DL, VT,
5271 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5275 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5277 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5278 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5279 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5280 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5281 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5282 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5283 // Get reciprocal estimate.
5284 // float4 recip = vrecpeq_f32(yf);
5285 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5286 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5287 // Because char has a smaller range than uchar, we can actually get away
5288 // without any newton steps. This requires that we use a weird bias
5289 // of 0xb000, however (again, this has been exhaustively tested).
5290 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5291 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5292 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5293 Y = DAG.getConstant(0xb000, MVT::i32);
5294 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5295 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5296 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5297 // Convert back to short.
5298 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5299 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5304 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5306 // Convert to float.
5307 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5308 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5309 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5310 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5311 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5312 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5314 // Use reciprocal estimate and one refinement step.
5315 // float4 recip = vrecpeq_f32(yf);
5316 // recip *= vrecpsq_f32(yf, recip);
5317 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5318 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5319 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5320 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5322 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5323 // Because short has a smaller range than ushort, we can actually get away
5324 // with only a single newton step. This requires that we use a weird bias
5325 // of 89, however (again, this has been exhaustively tested).
5326 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5327 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5328 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5329 N1 = DAG.getConstant(0x89, MVT::i32);
5330 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5331 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5332 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5333 // Convert back to integer and return.
5334 // return vmovn_s32(vcvt_s32_f32(result));
5335 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5336 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5340 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5341 EVT VT = Op.getValueType();
5342 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5343 "unexpected type for custom-lowering ISD::SDIV");
5345 DebugLoc dl = Op.getDebugLoc();
5346 SDValue N0 = Op.getOperand(0);
5347 SDValue N1 = Op.getOperand(1);
5350 if (VT == MVT::v8i8) {
5351 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5352 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5354 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5355 DAG.getIntPtrConstant(4));
5356 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5357 DAG.getIntPtrConstant(4));
5358 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5359 DAG.getIntPtrConstant(0));
5360 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5361 DAG.getIntPtrConstant(0));
5363 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5364 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5366 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5367 N0 = LowerCONCAT_VECTORS(N0, DAG);
5369 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5372 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5375 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5376 EVT VT = Op.getValueType();
5377 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5378 "unexpected type for custom-lowering ISD::UDIV");
5380 DebugLoc dl = Op.getDebugLoc();
5381 SDValue N0 = Op.getOperand(0);
5382 SDValue N1 = Op.getOperand(1);
5385 if (VT == MVT::v8i8) {
5386 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5387 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5389 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5390 DAG.getIntPtrConstant(4));
5391 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5392 DAG.getIntPtrConstant(4));
5393 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5394 DAG.getIntPtrConstant(0));
5395 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5396 DAG.getIntPtrConstant(0));
5398 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5399 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5401 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5402 N0 = LowerCONCAT_VECTORS(N0, DAG);
5404 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5405 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5410 // v4i16 sdiv ... Convert to float.
5411 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5412 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5413 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5414 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5415 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5416 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5418 // Use reciprocal estimate and two refinement steps.
5419 // float4 recip = vrecpeq_f32(yf);
5420 // recip *= vrecpsq_f32(yf, recip);
5421 // recip *= vrecpsq_f32(yf, recip);
5422 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5423 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5424 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5425 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5427 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5428 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5429 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5431 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5432 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5433 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5434 // and that it will never cause us to return an answer too large).
5435 // float4 result = as_float4(as_int4(xf*recip) + 2);
5436 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5437 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5438 N1 = DAG.getConstant(2, MVT::i32);
5439 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5440 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5441 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5442 // Convert back to integer and return.
5443 // return vmovn_u32(vcvt_s32_f32(result));
5444 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5445 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5449 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5450 EVT VT = Op.getNode()->getValueType(0);
5451 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5454 bool ExtraOp = false;
5455 switch (Op.getOpcode()) {
5456 default: llvm_unreachable("Invalid code");
5457 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5458 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5459 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5460 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5464 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5466 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5467 Op.getOperand(1), Op.getOperand(2));
5470 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5471 // Monotonic load/store is legal for all targets
5472 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5475 // Aquire/Release load/store is not legal for targets without a
5476 // dmb or equivalent available.
5482 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5483 SelectionDAG &DAG, unsigned NewOp) {
5484 DebugLoc dl = Node->getDebugLoc();
5485 assert (Node->getValueType(0) == MVT::i64 &&
5486 "Only know how to expand i64 atomics");
5488 SmallVector<SDValue, 6> Ops;
5489 Ops.push_back(Node->getOperand(0)); // Chain
5490 Ops.push_back(Node->getOperand(1)); // Ptr
5492 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5493 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5494 // High part of Val1
5495 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5496 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5497 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5498 // High part of Val1
5499 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5500 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5501 // High part of Val2
5502 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5503 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5505 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5507 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5508 cast<MemSDNode>(Node)->getMemOperand());
5509 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5510 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5511 Results.push_back(Result.getValue(2));
5514 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5515 switch (Op.getOpcode()) {
5516 default: llvm_unreachable("Don't know how to custom lower this!");
5517 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5518 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5519 case ISD::GlobalAddress:
5520 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5521 LowerGlobalAddressELF(Op, DAG);
5522 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5523 case ISD::SELECT: return LowerSELECT(Op, DAG);
5524 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5525 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5526 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5527 case ISD::VASTART: return LowerVASTART(Op, DAG);
5528 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5529 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5530 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5531 case ISD::SINT_TO_FP:
5532 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5533 case ISD::FP_TO_SINT:
5534 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5535 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5536 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5537 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5538 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5539 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5540 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5541 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5543 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5546 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5547 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5548 case ISD::SRL_PARTS:
5549 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5550 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5551 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5552 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5553 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5554 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5555 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5556 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5557 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5558 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5559 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5560 case ISD::MUL: return LowerMUL(Op, DAG);
5561 case ISD::SDIV: return LowerSDIV(Op, DAG);
5562 case ISD::UDIV: return LowerUDIV(Op, DAG);
5566 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5567 case ISD::ATOMIC_LOAD:
5568 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5572 /// ReplaceNodeResults - Replace the results of node with an illegal result
5573 /// type with new values built out of custom code.
5574 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5575 SmallVectorImpl<SDValue>&Results,
5576 SelectionDAG &DAG) const {
5578 switch (N->getOpcode()) {
5580 llvm_unreachable("Don't know how to custom expand this!");
5582 Res = ExpandBITCAST(N, DAG);
5586 Res = Expand64BitShift(N, DAG, Subtarget);
5588 case ISD::ATOMIC_LOAD_ADD:
5589 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5591 case ISD::ATOMIC_LOAD_AND:
5592 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5594 case ISD::ATOMIC_LOAD_NAND:
5595 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5597 case ISD::ATOMIC_LOAD_OR:
5598 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5600 case ISD::ATOMIC_LOAD_SUB:
5601 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5603 case ISD::ATOMIC_LOAD_XOR:
5604 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5606 case ISD::ATOMIC_SWAP:
5607 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5609 case ISD::ATOMIC_CMP_SWAP:
5610 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5612 case ISD::ATOMIC_LOAD_MIN:
5613 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5615 case ISD::ATOMIC_LOAD_UMIN:
5616 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5618 case ISD::ATOMIC_LOAD_MAX:
5619 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5621 case ISD::ATOMIC_LOAD_UMAX:
5622 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5626 Results.push_back(Res);
5629 //===----------------------------------------------------------------------===//
5630 // ARM Scheduler Hooks
5631 //===----------------------------------------------------------------------===//
5634 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5635 MachineBasicBlock *BB,
5636 unsigned Size) const {
5637 unsigned dest = MI->getOperand(0).getReg();
5638 unsigned ptr = MI->getOperand(1).getReg();
5639 unsigned oldval = MI->getOperand(2).getReg();
5640 unsigned newval = MI->getOperand(3).getReg();
5641 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5642 DebugLoc dl = MI->getDebugLoc();
5643 bool isThumb2 = Subtarget->isThumb2();
5645 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5646 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5647 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5648 (const TargetRegisterClass*)&ARM::GPRRegClass);
5651 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5652 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5653 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5656 unsigned ldrOpc, strOpc;
5658 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5660 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5661 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5664 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5665 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5668 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5669 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5673 MachineFunction *MF = BB->getParent();
5674 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5675 MachineFunction::iterator It = BB;
5676 ++It; // insert the new blocks after the current block
5678 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5679 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5680 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5681 MF->insert(It, loop1MBB);
5682 MF->insert(It, loop2MBB);
5683 MF->insert(It, exitMBB);
5685 // Transfer the remainder of BB and its successor edges to exitMBB.
5686 exitMBB->splice(exitMBB->begin(), BB,
5687 llvm::next(MachineBasicBlock::iterator(MI)),
5689 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5693 // fallthrough --> loop1MBB
5694 BB->addSuccessor(loop1MBB);
5697 // ldrex dest, [ptr]
5701 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5702 if (ldrOpc == ARM::t2LDREX)
5704 AddDefaultPred(MIB);
5705 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5706 .addReg(dest).addReg(oldval));
5707 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5708 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5709 BB->addSuccessor(loop2MBB);
5710 BB->addSuccessor(exitMBB);
5713 // strex scratch, newval, [ptr]
5717 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5718 if (strOpc == ARM::t2STREX)
5720 AddDefaultPred(MIB);
5721 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5722 .addReg(scratch).addImm(0));
5723 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5724 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5725 BB->addSuccessor(loop1MBB);
5726 BB->addSuccessor(exitMBB);
5732 MI->eraseFromParent(); // The instruction is gone now.
5738 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5739 unsigned Size, unsigned BinOpcode) const {
5740 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5741 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5743 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5744 MachineFunction *MF = BB->getParent();
5745 MachineFunction::iterator It = BB;
5748 unsigned dest = MI->getOperand(0).getReg();
5749 unsigned ptr = MI->getOperand(1).getReg();
5750 unsigned incr = MI->getOperand(2).getReg();
5751 DebugLoc dl = MI->getDebugLoc();
5752 bool isThumb2 = Subtarget->isThumb2();
5754 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5756 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5757 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5760 unsigned ldrOpc, strOpc;
5762 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5764 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5765 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5768 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5769 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5772 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5773 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5777 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5778 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5779 MF->insert(It, loopMBB);
5780 MF->insert(It, exitMBB);
5782 // Transfer the remainder of BB and its successor edges to exitMBB.
5783 exitMBB->splice(exitMBB->begin(), BB,
5784 llvm::next(MachineBasicBlock::iterator(MI)),
5786 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5788 const TargetRegisterClass *TRC = isThumb2 ?
5789 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5790 (const TargetRegisterClass*)&ARM::GPRRegClass;
5791 unsigned scratch = MRI.createVirtualRegister(TRC);
5792 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5796 // fallthrough --> loopMBB
5797 BB->addSuccessor(loopMBB);
5801 // <binop> scratch2, dest, incr
5802 // strex scratch, scratch2, ptr
5805 // fallthrough --> exitMBB
5807 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5808 if (ldrOpc == ARM::t2LDREX)
5810 AddDefaultPred(MIB);
5812 // operand order needs to go the other way for NAND
5813 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5814 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5815 addReg(incr).addReg(dest)).addReg(0);
5817 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5818 addReg(dest).addReg(incr)).addReg(0);
5821 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5822 if (strOpc == ARM::t2STREX)
5824 AddDefaultPred(MIB);
5825 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5826 .addReg(scratch).addImm(0));
5827 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5828 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5830 BB->addSuccessor(loopMBB);
5831 BB->addSuccessor(exitMBB);
5837 MI->eraseFromParent(); // The instruction is gone now.
5843 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5844 MachineBasicBlock *BB,
5847 ARMCC::CondCodes Cond) const {
5848 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5850 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5851 MachineFunction *MF = BB->getParent();
5852 MachineFunction::iterator It = BB;
5855 unsigned dest = MI->getOperand(0).getReg();
5856 unsigned ptr = MI->getOperand(1).getReg();
5857 unsigned incr = MI->getOperand(2).getReg();
5858 unsigned oldval = dest;
5859 DebugLoc dl = MI->getDebugLoc();
5860 bool isThumb2 = Subtarget->isThumb2();
5862 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5864 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5865 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5868 unsigned ldrOpc, strOpc, extendOpc;
5870 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5872 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5873 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5874 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5877 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5878 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5879 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5882 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5883 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5888 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5889 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5890 MF->insert(It, loopMBB);
5891 MF->insert(It, exitMBB);
5893 // Transfer the remainder of BB and its successor edges to exitMBB.
5894 exitMBB->splice(exitMBB->begin(), BB,
5895 llvm::next(MachineBasicBlock::iterator(MI)),
5897 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5899 const TargetRegisterClass *TRC = isThumb2 ?
5900 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5901 (const TargetRegisterClass*)&ARM::GPRRegClass;
5902 unsigned scratch = MRI.createVirtualRegister(TRC);
5903 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5907 // fallthrough --> loopMBB
5908 BB->addSuccessor(loopMBB);
5912 // (sign extend dest, if required)
5914 // cmov.cond scratch2, incr, dest
5915 // strex scratch, scratch2, ptr
5918 // fallthrough --> exitMBB
5920 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5921 if (ldrOpc == ARM::t2LDREX)
5923 AddDefaultPred(MIB);
5925 // Sign extend the value, if necessary.
5926 if (signExtend && extendOpc) {
5927 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5928 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5933 // Build compare and cmov instructions.
5934 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5935 .addReg(oldval).addReg(incr));
5936 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5937 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5939 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5940 if (strOpc == ARM::t2STREX)
5942 AddDefaultPred(MIB);
5943 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5944 .addReg(scratch).addImm(0));
5945 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5946 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5948 BB->addSuccessor(loopMBB);
5949 BB->addSuccessor(exitMBB);
5955 MI->eraseFromParent(); // The instruction is gone now.
5961 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5962 unsigned Op1, unsigned Op2,
5963 bool NeedsCarry, bool IsCmpxchg,
5964 bool IsMinMax, ARMCC::CondCodes CC) const {
5965 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5966 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5968 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5969 MachineFunction *MF = BB->getParent();
5970 MachineFunction::iterator It = BB;
5973 unsigned destlo = MI->getOperand(0).getReg();
5974 unsigned desthi = MI->getOperand(1).getReg();
5975 unsigned ptr = MI->getOperand(2).getReg();
5976 unsigned vallo = MI->getOperand(3).getReg();
5977 unsigned valhi = MI->getOperand(4).getReg();
5978 DebugLoc dl = MI->getDebugLoc();
5979 bool isThumb2 = Subtarget->isThumb2();
5981 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5983 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5984 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5985 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5988 unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5989 unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5991 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5992 MachineBasicBlock *contBB = 0, *cont2BB = 0;
5993 if (IsCmpxchg || IsMinMax)
5994 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5996 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5997 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5999 MF->insert(It, loopMBB);
6000 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6001 if (IsCmpxchg) MF->insert(It, cont2BB);
6002 MF->insert(It, exitMBB);
6004 // Transfer the remainder of BB and its successor edges to exitMBB.
6005 exitMBB->splice(exitMBB->begin(), BB,
6006 llvm::next(MachineBasicBlock::iterator(MI)),
6008 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6010 const TargetRegisterClass *TRC = isThumb2 ?
6011 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6012 (const TargetRegisterClass*)&ARM::GPRRegClass;
6013 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6017 // fallthrough --> loopMBB
6018 BB->addSuccessor(loopMBB);
6021 // ldrexd r2, r3, ptr
6022 // <binopa> r0, r2, incr
6023 // <binopb> r1, r3, incr
6024 // strexd storesuccess, r0, r1, ptr
6025 // cmp storesuccess, #0
6027 // fallthrough --> exitMBB
6029 // Note that the registers are explicitly specified because there is not any
6030 // way to force the register allocator to allocate a register pair.
6032 // FIXME: The hardcoded registers are not necessary for Thumb2, but we
6033 // need to properly enforce the restriction that the two output registers
6034 // for ldrexd must be different.
6037 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6038 unsigned GPRPair1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6041 //We need an extra double register for doing min/max.
6042 unsigned undef = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6043 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6044 GPRPair2 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6045 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), undef);
6046 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6049 .addImm(ARM::gsub_0);
6050 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair2)
6053 .addImm(ARM::gsub_1);
6056 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6057 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6058 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6059 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6060 .addReg(GPRPair0, 0, ARM::gsub_0);
6061 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6062 .addReg(GPRPair0, 0, ARM::gsub_1);
6066 for (unsigned i = 0; i < 2; i++) {
6067 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6069 .addReg(i == 0 ? destlo : desthi)
6070 .addReg(i == 0 ? vallo : valhi));
6071 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6072 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6073 BB->addSuccessor(exitMBB);
6074 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6075 BB = (i == 0 ? contBB : cont2BB);
6078 // Copy to physregs for strexd
6079 unsigned setlo = MI->getOperand(5).getReg();
6080 unsigned sethi = MI->getOperand(6).getReg();
6081 unsigned undef = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6082 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6083 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), undef);
6084 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6087 .addImm(ARM::gsub_0);
6088 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair1)
6091 .addImm(ARM::gsub_1);
6093 // Perform binary operation
6094 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6095 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6096 .addReg(destlo).addReg(vallo))
6097 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6098 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6099 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6100 .addReg(desthi).addReg(valhi))
6101 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6103 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6104 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6105 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6106 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6109 .addImm(ARM::gsub_0);
6110 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair1)
6113 .addImm(ARM::gsub_1);
6115 // Copy to physregs for strexd
6116 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6117 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6118 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6119 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6122 .addImm(ARM::gsub_0);
6123 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), GPRPair1)
6126 .addImm(ARM::gsub_1);
6128 unsigned GPRPairStore = GPRPair1;
6130 // Compare and branch to exit block.
6131 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6132 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6133 BB->addSuccessor(exitMBB);
6134 BB->addSuccessor(contBB);
6136 GPRPairStore = GPRPair2;
6140 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6141 .addReg(GPRPairStore).addReg(ptr));
6143 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6144 .addReg(storesuccess).addImm(0));
6145 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6146 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6148 BB->addSuccessor(loopMBB);
6149 BB->addSuccessor(exitMBB);
6155 MI->eraseFromParent(); // The instruction is gone now.
6160 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6161 /// registers the function context.
6162 void ARMTargetLowering::
6163 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6164 MachineBasicBlock *DispatchBB, int FI) const {
6165 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6166 DebugLoc dl = MI->getDebugLoc();
6167 MachineFunction *MF = MBB->getParent();
6168 MachineRegisterInfo *MRI = &MF->getRegInfo();
6169 MachineConstantPool *MCP = MF->getConstantPool();
6170 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6171 const Function *F = MF->getFunction();
6173 bool isThumb = Subtarget->isThumb();
6174 bool isThumb2 = Subtarget->isThumb2();
6176 unsigned PCLabelId = AFI->createPICLabelUId();
6177 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6178 ARMConstantPoolValue *CPV =
6179 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6180 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6182 const TargetRegisterClass *TRC = isThumb ?
6183 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6184 (const TargetRegisterClass*)&ARM::GPRRegClass;
6186 // Grab constant pool and fixed stack memory operands.
6187 MachineMemOperand *CPMMO =
6188 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6189 MachineMemOperand::MOLoad, 4, 4);
6191 MachineMemOperand *FIMMOSt =
6192 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6193 MachineMemOperand::MOStore, 4, 4);
6195 // Load the address of the dispatch MBB into the jump buffer.
6197 // Incoming value: jbuf
6198 // ldr.n r5, LCPI1_1
6201 // str r5, [$jbuf, #+4] ; &jbuf[1]
6202 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6203 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6204 .addConstantPoolIndex(CPI)
6205 .addMemOperand(CPMMO));
6206 // Set the low bit because of thumb mode.
6207 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6209 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6210 .addReg(NewVReg1, RegState::Kill)
6212 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6213 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6214 .addReg(NewVReg2, RegState::Kill)
6216 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6217 .addReg(NewVReg3, RegState::Kill)
6219 .addImm(36) // &jbuf[1] :: pc
6220 .addMemOperand(FIMMOSt));
6221 } else if (isThumb) {
6222 // Incoming value: jbuf
6223 // ldr.n r1, LCPI1_4
6227 // add r2, $jbuf, #+4 ; &jbuf[1]
6229 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6230 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6231 .addConstantPoolIndex(CPI)
6232 .addMemOperand(CPMMO));
6233 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6234 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6235 .addReg(NewVReg1, RegState::Kill)
6237 // Set the low bit because of thumb mode.
6238 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6239 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6240 .addReg(ARM::CPSR, RegState::Define)
6242 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6243 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6244 .addReg(ARM::CPSR, RegState::Define)
6245 .addReg(NewVReg2, RegState::Kill)
6246 .addReg(NewVReg3, RegState::Kill));
6247 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6248 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6250 .addImm(36)); // &jbuf[1] :: pc
6251 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6252 .addReg(NewVReg4, RegState::Kill)
6253 .addReg(NewVReg5, RegState::Kill)
6255 .addMemOperand(FIMMOSt));
6257 // Incoming value: jbuf
6260 // str r1, [$jbuf, #+4] ; &jbuf[1]
6261 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6262 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6263 .addConstantPoolIndex(CPI)
6265 .addMemOperand(CPMMO));
6266 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6267 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6268 .addReg(NewVReg1, RegState::Kill)
6269 .addImm(PCLabelId));
6270 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6271 .addReg(NewVReg2, RegState::Kill)
6273 .addImm(36) // &jbuf[1] :: pc
6274 .addMemOperand(FIMMOSt));
6278 MachineBasicBlock *ARMTargetLowering::
6279 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6280 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6281 DebugLoc dl = MI->getDebugLoc();
6282 MachineFunction *MF = MBB->getParent();
6283 MachineRegisterInfo *MRI = &MF->getRegInfo();
6284 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6285 MachineFrameInfo *MFI = MF->getFrameInfo();
6286 int FI = MFI->getFunctionContextIndex();
6288 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6289 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6290 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6292 // Get a mapping of the call site numbers to all of the landing pads they're
6294 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6295 unsigned MaxCSNum = 0;
6296 MachineModuleInfo &MMI = MF->getMMI();
6297 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6299 if (!BB->isLandingPad()) continue;
6301 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6303 for (MachineBasicBlock::iterator
6304 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6305 if (!II->isEHLabel()) continue;
6307 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6308 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6310 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6311 for (SmallVectorImpl<unsigned>::iterator
6312 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6313 CSI != CSE; ++CSI) {
6314 CallSiteNumToLPad[*CSI].push_back(BB);
6315 MaxCSNum = std::max(MaxCSNum, *CSI);
6321 // Get an ordered list of the machine basic blocks for the jump table.
6322 std::vector<MachineBasicBlock*> LPadList;
6323 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6324 LPadList.reserve(CallSiteNumToLPad.size());
6325 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6326 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6327 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6328 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6329 LPadList.push_back(*II);
6330 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6334 assert(!LPadList.empty() &&
6335 "No landing pad destinations for the dispatch jump table!");
6337 // Create the jump table and associated information.
6338 MachineJumpTableInfo *JTI =
6339 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6340 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6341 unsigned UId = AFI->createJumpTableUId();
6343 // Create the MBBs for the dispatch code.
6345 // Shove the dispatch's address into the return slot in the function context.
6346 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6347 DispatchBB->setIsLandingPad();
6349 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6350 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
6351 DispatchBB->addSuccessor(TrapBB);
6353 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6354 DispatchBB->addSuccessor(DispContBB);
6357 MF->insert(MF->end(), DispatchBB);
6358 MF->insert(MF->end(), DispContBB);
6359 MF->insert(MF->end(), TrapBB);
6361 // Insert code into the entry block that creates and registers the function
6363 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6365 MachineMemOperand *FIMMOLd =
6366 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6367 MachineMemOperand::MOLoad |
6368 MachineMemOperand::MOVolatile, 4, 4);
6370 MachineInstrBuilder MIB;
6371 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6373 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6374 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6376 // Add a register mask with no preserved registers. This results in all
6377 // registers being marked as clobbered.
6378 MIB.addRegMask(RI.getNoPreservedMask());
6380 unsigned NumLPads = LPadList.size();
6381 if (Subtarget->isThumb2()) {
6382 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6383 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6386 .addMemOperand(FIMMOLd));
6388 if (NumLPads < 256) {
6389 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6391 .addImm(LPadList.size()));
6393 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6394 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6395 .addImm(NumLPads & 0xFFFF));
6397 unsigned VReg2 = VReg1;
6398 if ((NumLPads & 0xFFFF0000) != 0) {
6399 VReg2 = MRI->createVirtualRegister(TRC);
6400 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6402 .addImm(NumLPads >> 16));
6405 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6410 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6415 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6416 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6417 .addJumpTableIndex(MJTI)
6420 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6423 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6424 .addReg(NewVReg3, RegState::Kill)
6426 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6428 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6429 .addReg(NewVReg4, RegState::Kill)
6431 .addJumpTableIndex(MJTI)
6433 } else if (Subtarget->isThumb()) {
6434 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6435 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6438 .addMemOperand(FIMMOLd));
6440 if (NumLPads < 256) {
6441 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6445 MachineConstantPool *ConstantPool = MF->getConstantPool();
6446 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6447 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6449 // MachineConstantPool wants an explicit alignment.
6450 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6452 Align = getDataLayout()->getTypeAllocSize(C->getType());
6453 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6455 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6456 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6457 .addReg(VReg1, RegState::Define)
6458 .addConstantPoolIndex(Idx));
6459 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6464 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6469 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6470 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6471 .addReg(ARM::CPSR, RegState::Define)
6475 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6476 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6477 .addJumpTableIndex(MJTI)
6480 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6481 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6482 .addReg(ARM::CPSR, RegState::Define)
6483 .addReg(NewVReg2, RegState::Kill)
6486 MachineMemOperand *JTMMOLd =
6487 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6488 MachineMemOperand::MOLoad, 4, 4);
6490 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6491 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6492 .addReg(NewVReg4, RegState::Kill)
6494 .addMemOperand(JTMMOLd));
6496 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6497 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6498 .addReg(ARM::CPSR, RegState::Define)
6499 .addReg(NewVReg5, RegState::Kill)
6502 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6503 .addReg(NewVReg6, RegState::Kill)
6504 .addJumpTableIndex(MJTI)
6507 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6508 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6511 .addMemOperand(FIMMOLd));
6513 if (NumLPads < 256) {
6514 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6517 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6518 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6519 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6520 .addImm(NumLPads & 0xFFFF));
6522 unsigned VReg2 = VReg1;
6523 if ((NumLPads & 0xFFFF0000) != 0) {
6524 VReg2 = MRI->createVirtualRegister(TRC);
6525 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6527 .addImm(NumLPads >> 16));
6530 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6534 MachineConstantPool *ConstantPool = MF->getConstantPool();
6535 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6536 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6538 // MachineConstantPool wants an explicit alignment.
6539 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6541 Align = getDataLayout()->getTypeAllocSize(C->getType());
6542 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6544 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6545 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6546 .addReg(VReg1, RegState::Define)
6547 .addConstantPoolIndex(Idx)
6549 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6551 .addReg(VReg1, RegState::Kill));
6554 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6559 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6561 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6563 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6564 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6565 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6566 .addJumpTableIndex(MJTI)
6569 MachineMemOperand *JTMMOLd =
6570 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6571 MachineMemOperand::MOLoad, 4, 4);
6572 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6574 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6575 .addReg(NewVReg3, RegState::Kill)
6578 .addMemOperand(JTMMOLd));
6580 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6581 .addReg(NewVReg5, RegState::Kill)
6583 .addJumpTableIndex(MJTI)
6587 // Add the jump table entries as successors to the MBB.
6588 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6589 for (std::vector<MachineBasicBlock*>::iterator
6590 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6591 MachineBasicBlock *CurMBB = *I;
6592 if (SeenMBBs.insert(CurMBB))
6593 DispContBB->addSuccessor(CurMBB);
6596 // N.B. the order the invoke BBs are processed in doesn't matter here.
6597 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6598 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6599 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6600 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6601 MachineBasicBlock *BB = *I;
6603 // Remove the landing pad successor from the invoke block and replace it
6604 // with the new dispatch block.
6605 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6607 while (!Successors.empty()) {
6608 MachineBasicBlock *SMBB = Successors.pop_back_val();
6609 if (SMBB->isLandingPad()) {
6610 BB->removeSuccessor(SMBB);
6611 MBBLPads.push_back(SMBB);
6615 BB->addSuccessor(DispatchBB);
6617 // Find the invoke call and mark all of the callee-saved registers as
6618 // 'implicit defined' so that they're spilled. This prevents code from
6619 // moving instructions to before the EH block, where they will never be
6621 for (MachineBasicBlock::reverse_iterator
6622 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6623 if (!II->isCall()) continue;
6625 DenseMap<unsigned, bool> DefRegs;
6626 for (MachineInstr::mop_iterator
6627 OI = II->operands_begin(), OE = II->operands_end();
6629 if (!OI->isReg()) continue;
6630 DefRegs[OI->getReg()] = true;
6633 MachineInstrBuilder MIB(*MF, &*II);
6635 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6636 unsigned Reg = SavedRegs[i];
6637 if (Subtarget->isThumb2() &&
6638 !ARM::tGPRRegClass.contains(Reg) &&
6639 !ARM::hGPRRegClass.contains(Reg))
6641 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6643 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6646 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6653 // Mark all former landing pads as non-landing pads. The dispatch is the only
6655 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6656 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6657 (*I)->setIsLandingPad(false);
6659 // The instruction is gone now.
6660 MI->eraseFromParent();
6666 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6667 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6668 E = MBB->succ_end(); I != E; ++I)
6671 llvm_unreachable("Expecting a BB with two successors!");
6674 MachineBasicBlock *ARMTargetLowering::
6675 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6676 // This pseudo instruction has 3 operands: dst, src, size
6677 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6678 // Otherwise, we will generate unrolled scalar copies.
6679 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6680 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6681 MachineFunction::iterator It = BB;
6684 unsigned dest = MI->getOperand(0).getReg();
6685 unsigned src = MI->getOperand(1).getReg();
6686 unsigned SizeVal = MI->getOperand(2).getImm();
6687 unsigned Align = MI->getOperand(3).getImm();
6688 DebugLoc dl = MI->getDebugLoc();
6690 bool isThumb2 = Subtarget->isThumb2();
6691 MachineFunction *MF = BB->getParent();
6692 MachineRegisterInfo &MRI = MF->getRegInfo();
6693 unsigned ldrOpc, strOpc, UnitSize = 0;
6695 const TargetRegisterClass *TRC = isThumb2 ?
6696 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6697 (const TargetRegisterClass*)&ARM::GPRRegClass;
6698 const TargetRegisterClass *TRC_Vec = 0;
6701 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6702 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6704 } else if (Align & 2) {
6705 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6706 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6709 // Check whether we can use NEON instructions.
6710 if (!MF->getFunction()->getFnAttributes().
6711 hasAttribute(Attribute::NoImplicitFloat) &&
6712 Subtarget->hasNEON()) {
6713 if ((Align % 16 == 0) && SizeVal >= 16) {
6714 ldrOpc = ARM::VLD1q32wb_fixed;
6715 strOpc = ARM::VST1q32wb_fixed;
6717 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6719 else if ((Align % 8 == 0) && SizeVal >= 8) {
6720 ldrOpc = ARM::VLD1d32wb_fixed;
6721 strOpc = ARM::VST1d32wb_fixed;
6723 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6726 // Can't use NEON instructions.
6727 if (UnitSize == 0) {
6728 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6729 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6734 unsigned BytesLeft = SizeVal % UnitSize;
6735 unsigned LoopSize = SizeVal - BytesLeft;
6737 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6738 // Use LDR and STR to copy.
6739 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6740 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6741 unsigned srcIn = src;
6742 unsigned destIn = dest;
6743 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6744 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6745 unsigned srcOut = MRI.createVirtualRegister(TRC);
6746 unsigned destOut = MRI.createVirtualRegister(TRC);
6747 if (UnitSize >= 8) {
6748 AddDefaultPred(BuildMI(*BB, MI, dl,
6749 TII->get(ldrOpc), scratch)
6750 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6752 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6753 .addReg(destIn).addImm(0).addReg(scratch));
6754 } else if (isThumb2) {
6755 AddDefaultPred(BuildMI(*BB, MI, dl,
6756 TII->get(ldrOpc), scratch)
6757 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6759 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6760 .addReg(scratch).addReg(destIn)
6763 AddDefaultPred(BuildMI(*BB, MI, dl,
6764 TII->get(ldrOpc), scratch)
6765 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6768 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6769 .addReg(scratch).addReg(destIn)
6770 .addReg(0).addImm(UnitSize));
6776 // Handle the leftover bytes with LDRB and STRB.
6777 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6778 // [destOut] = STRB_POST(scratch, destIn, 1)
6779 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6780 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6781 for (unsigned i = 0; i < BytesLeft; i++) {
6782 unsigned scratch = MRI.createVirtualRegister(TRC);
6783 unsigned srcOut = MRI.createVirtualRegister(TRC);
6784 unsigned destOut = MRI.createVirtualRegister(TRC);
6786 AddDefaultPred(BuildMI(*BB, MI, dl,
6787 TII->get(ldrOpc),scratch)
6788 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6790 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6791 .addReg(scratch).addReg(destIn)
6792 .addReg(0).addImm(1));
6794 AddDefaultPred(BuildMI(*BB, MI, dl,
6795 TII->get(ldrOpc),scratch)
6796 .addReg(srcOut, RegState::Define).addReg(srcIn)
6797 .addReg(0).addImm(1));
6799 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6800 .addReg(scratch).addReg(destIn)
6801 .addReg(0).addImm(1));
6806 MI->eraseFromParent(); // The instruction is gone now.
6810 // Expand the pseudo op to a loop.
6813 // movw varEnd, # --> with thumb2
6815 // ldrcp varEnd, idx --> without thumb2
6816 // fallthrough --> loopMBB
6818 // PHI varPhi, varEnd, varLoop
6819 // PHI srcPhi, src, srcLoop
6820 // PHI destPhi, dst, destLoop
6821 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6822 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6823 // subs varLoop, varPhi, #UnitSize
6825 // fallthrough --> exitMBB
6827 // epilogue to handle left-over bytes
6828 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6829 // [destOut] = STRB_POST(scratch, destLoop, 1)
6830 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6831 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6832 MF->insert(It, loopMBB);
6833 MF->insert(It, exitMBB);
6835 // Transfer the remainder of BB and its successor edges to exitMBB.
6836 exitMBB->splice(exitMBB->begin(), BB,
6837 llvm::next(MachineBasicBlock::iterator(MI)),
6839 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6841 // Load an immediate to varEnd.
6842 unsigned varEnd = MRI.createVirtualRegister(TRC);
6844 unsigned VReg1 = varEnd;
6845 if ((LoopSize & 0xFFFF0000) != 0)
6846 VReg1 = MRI.createVirtualRegister(TRC);
6847 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6848 .addImm(LoopSize & 0xFFFF));
6850 if ((LoopSize & 0xFFFF0000) != 0)
6851 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6853 .addImm(LoopSize >> 16));
6855 MachineConstantPool *ConstantPool = MF->getConstantPool();
6856 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6857 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6859 // MachineConstantPool wants an explicit alignment.
6860 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6862 Align = getDataLayout()->getTypeAllocSize(C->getType());
6863 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6865 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6866 .addReg(varEnd, RegState::Define)
6867 .addConstantPoolIndex(Idx)
6870 BB->addSuccessor(loopMBB);
6872 // Generate the loop body:
6873 // varPhi = PHI(varLoop, varEnd)
6874 // srcPhi = PHI(srcLoop, src)
6875 // destPhi = PHI(destLoop, dst)
6876 MachineBasicBlock *entryBB = BB;
6878 unsigned varLoop = MRI.createVirtualRegister(TRC);
6879 unsigned varPhi = MRI.createVirtualRegister(TRC);
6880 unsigned srcLoop = MRI.createVirtualRegister(TRC);
6881 unsigned srcPhi = MRI.createVirtualRegister(TRC);
6882 unsigned destLoop = MRI.createVirtualRegister(TRC);
6883 unsigned destPhi = MRI.createVirtualRegister(TRC);
6885 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6886 .addReg(varLoop).addMBB(loopMBB)
6887 .addReg(varEnd).addMBB(entryBB);
6888 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6889 .addReg(srcLoop).addMBB(loopMBB)
6890 .addReg(src).addMBB(entryBB);
6891 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6892 .addReg(destLoop).addMBB(loopMBB)
6893 .addReg(dest).addMBB(entryBB);
6895 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6896 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6897 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6898 if (UnitSize >= 8) {
6899 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6900 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6902 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6903 .addReg(destPhi).addImm(0).addReg(scratch));
6904 } else if (isThumb2) {
6905 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6906 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6908 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6909 .addReg(scratch).addReg(destPhi)
6912 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6913 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6916 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6917 .addReg(scratch).addReg(destPhi)
6918 .addReg(0).addImm(UnitSize));
6921 // Decrement loop variable by UnitSize.
6922 MachineInstrBuilder MIB = BuildMI(BB, dl,
6923 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6924 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6925 MIB->getOperand(5).setReg(ARM::CPSR);
6926 MIB->getOperand(5).setIsDef(true);
6928 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6929 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6931 // loopMBB can loop back to loopMBB or fall through to exitMBB.
6932 BB->addSuccessor(loopMBB);
6933 BB->addSuccessor(exitMBB);
6935 // Add epilogue to handle BytesLeft.
6937 MachineInstr *StartOfExit = exitMBB->begin();
6938 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6939 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6941 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6942 // [destOut] = STRB_POST(scratch, destLoop, 1)
6943 unsigned srcIn = srcLoop;
6944 unsigned destIn = destLoop;
6945 for (unsigned i = 0; i < BytesLeft; i++) {
6946 unsigned scratch = MRI.createVirtualRegister(TRC);
6947 unsigned srcOut = MRI.createVirtualRegister(TRC);
6948 unsigned destOut = MRI.createVirtualRegister(TRC);
6950 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6951 TII->get(ldrOpc),scratch)
6952 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6954 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6955 .addReg(scratch).addReg(destIn)
6958 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6959 TII->get(ldrOpc),scratch)
6960 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6962 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6963 .addReg(scratch).addReg(destIn)
6964 .addReg(0).addImm(1));
6970 MI->eraseFromParent(); // The instruction is gone now.
6975 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6976 MachineBasicBlock *BB) const {
6977 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6978 DebugLoc dl = MI->getDebugLoc();
6979 bool isThumb2 = Subtarget->isThumb2();
6980 switch (MI->getOpcode()) {
6983 llvm_unreachable("Unexpected instr type to insert");
6985 // The Thumb2 pre-indexed stores have the same MI operands, they just
6986 // define them differently in the .td files from the isel patterns, so
6987 // they need pseudos.
6988 case ARM::t2STR_preidx:
6989 MI->setDesc(TII->get(ARM::t2STR_PRE));
6991 case ARM::t2STRB_preidx:
6992 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6994 case ARM::t2STRH_preidx:
6995 MI->setDesc(TII->get(ARM::t2STRH_PRE));
6998 case ARM::STRi_preidx:
6999 case ARM::STRBi_preidx: {
7000 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7001 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7002 // Decode the offset.
7003 unsigned Offset = MI->getOperand(4).getImm();
7004 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7005 Offset = ARM_AM::getAM2Offset(Offset);
7009 MachineMemOperand *MMO = *MI->memoperands_begin();
7010 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7011 .addOperand(MI->getOperand(0)) // Rn_wb
7012 .addOperand(MI->getOperand(1)) // Rt
7013 .addOperand(MI->getOperand(2)) // Rn
7014 .addImm(Offset) // offset (skip GPR==zero_reg)
7015 .addOperand(MI->getOperand(5)) // pred
7016 .addOperand(MI->getOperand(6))
7017 .addMemOperand(MMO);
7018 MI->eraseFromParent();
7021 case ARM::STRr_preidx:
7022 case ARM::STRBr_preidx:
7023 case ARM::STRH_preidx: {
7025 switch (MI->getOpcode()) {
7026 default: llvm_unreachable("unexpected opcode!");
7027 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7028 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7029 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7031 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7032 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7033 MIB.addOperand(MI->getOperand(i));
7034 MI->eraseFromParent();
7037 case ARM::ATOMIC_LOAD_ADD_I8:
7038 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7039 case ARM::ATOMIC_LOAD_ADD_I16:
7040 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7041 case ARM::ATOMIC_LOAD_ADD_I32:
7042 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7044 case ARM::ATOMIC_LOAD_AND_I8:
7045 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7046 case ARM::ATOMIC_LOAD_AND_I16:
7047 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7048 case ARM::ATOMIC_LOAD_AND_I32:
7049 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7051 case ARM::ATOMIC_LOAD_OR_I8:
7052 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7053 case ARM::ATOMIC_LOAD_OR_I16:
7054 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7055 case ARM::ATOMIC_LOAD_OR_I32:
7056 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7058 case ARM::ATOMIC_LOAD_XOR_I8:
7059 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7060 case ARM::ATOMIC_LOAD_XOR_I16:
7061 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7062 case ARM::ATOMIC_LOAD_XOR_I32:
7063 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7065 case ARM::ATOMIC_LOAD_NAND_I8:
7066 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7067 case ARM::ATOMIC_LOAD_NAND_I16:
7068 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7069 case ARM::ATOMIC_LOAD_NAND_I32:
7070 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7072 case ARM::ATOMIC_LOAD_SUB_I8:
7073 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7074 case ARM::ATOMIC_LOAD_SUB_I16:
7075 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7076 case ARM::ATOMIC_LOAD_SUB_I32:
7077 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7079 case ARM::ATOMIC_LOAD_MIN_I8:
7080 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7081 case ARM::ATOMIC_LOAD_MIN_I16:
7082 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7083 case ARM::ATOMIC_LOAD_MIN_I32:
7084 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7086 case ARM::ATOMIC_LOAD_MAX_I8:
7087 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7088 case ARM::ATOMIC_LOAD_MAX_I16:
7089 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7090 case ARM::ATOMIC_LOAD_MAX_I32:
7091 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7093 case ARM::ATOMIC_LOAD_UMIN_I8:
7094 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7095 case ARM::ATOMIC_LOAD_UMIN_I16:
7096 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7097 case ARM::ATOMIC_LOAD_UMIN_I32:
7098 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7100 case ARM::ATOMIC_LOAD_UMAX_I8:
7101 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7102 case ARM::ATOMIC_LOAD_UMAX_I16:
7103 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7104 case ARM::ATOMIC_LOAD_UMAX_I32:
7105 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7107 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7108 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7109 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7111 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7112 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7113 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7116 case ARM::ATOMADD6432:
7117 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7118 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7119 /*NeedsCarry*/ true);
7120 case ARM::ATOMSUB6432:
7121 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7122 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7123 /*NeedsCarry*/ true);
7124 case ARM::ATOMOR6432:
7125 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7126 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7127 case ARM::ATOMXOR6432:
7128 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7129 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7130 case ARM::ATOMAND6432:
7131 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7132 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7133 case ARM::ATOMSWAP6432:
7134 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7135 case ARM::ATOMCMPXCHG6432:
7136 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7137 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7138 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7139 case ARM::ATOMMIN6432:
7140 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7141 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7142 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7143 /*IsMinMax*/ true, ARMCC::LE);
7144 case ARM::ATOMMAX6432:
7145 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7146 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7147 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7148 /*IsMinMax*/ true, ARMCC::GE);
7149 case ARM::ATOMUMIN6432:
7150 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7151 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7152 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7153 /*IsMinMax*/ true, ARMCC::LS);
7154 case ARM::ATOMUMAX6432:
7155 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7156 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7157 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7158 /*IsMinMax*/ true, ARMCC::HS);
7160 case ARM::tMOVCCr_pseudo: {
7161 // To "insert" a SELECT_CC instruction, we actually have to insert the
7162 // diamond control-flow pattern. The incoming instruction knows the
7163 // destination vreg to set, the condition code register to branch on, the
7164 // true/false values to select between, and a branch opcode to use.
7165 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7166 MachineFunction::iterator It = BB;
7172 // cmpTY ccX, r1, r2
7174 // fallthrough --> copy0MBB
7175 MachineBasicBlock *thisMBB = BB;
7176 MachineFunction *F = BB->getParent();
7177 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7178 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7179 F->insert(It, copy0MBB);
7180 F->insert(It, sinkMBB);
7182 // Transfer the remainder of BB and its successor edges to sinkMBB.
7183 sinkMBB->splice(sinkMBB->begin(), BB,
7184 llvm::next(MachineBasicBlock::iterator(MI)),
7186 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7188 BB->addSuccessor(copy0MBB);
7189 BB->addSuccessor(sinkMBB);
7191 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7192 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7195 // %FalseValue = ...
7196 // # fallthrough to sinkMBB
7199 // Update machine-CFG edges
7200 BB->addSuccessor(sinkMBB);
7203 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7206 BuildMI(*BB, BB->begin(), dl,
7207 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7208 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7209 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7211 MI->eraseFromParent(); // The pseudo instruction is gone now.
7216 case ARM::BCCZi64: {
7217 // If there is an unconditional branch to the other successor, remove it.
7218 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7220 // Compare both parts that make up the double comparison separately for
7222 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7224 unsigned LHS1 = MI->getOperand(1).getReg();
7225 unsigned LHS2 = MI->getOperand(2).getReg();
7227 AddDefaultPred(BuildMI(BB, dl,
7228 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7229 .addReg(LHS1).addImm(0));
7230 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7231 .addReg(LHS2).addImm(0)
7232 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7234 unsigned RHS1 = MI->getOperand(3).getReg();
7235 unsigned RHS2 = MI->getOperand(4).getReg();
7236 AddDefaultPred(BuildMI(BB, dl,
7237 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7238 .addReg(LHS1).addReg(RHS1));
7239 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7240 .addReg(LHS2).addReg(RHS2)
7241 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7244 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7245 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7246 if (MI->getOperand(0).getImm() == ARMCC::NE)
7247 std::swap(destMBB, exitMBB);
7249 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7250 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7252 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7254 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7256 MI->eraseFromParent(); // The pseudo instruction is gone now.
7260 case ARM::Int_eh_sjlj_setjmp:
7261 case ARM::Int_eh_sjlj_setjmp_nofp:
7262 case ARM::tInt_eh_sjlj_setjmp:
7263 case ARM::t2Int_eh_sjlj_setjmp:
7264 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7265 EmitSjLjDispatchBlock(MI, BB);
7270 // To insert an ABS instruction, we have to insert the
7271 // diamond control-flow pattern. The incoming instruction knows the
7272 // source vreg to test against 0, the destination vreg to set,
7273 // the condition code register to branch on, the
7274 // true/false values to select between, and a branch opcode to use.
7279 // BCC (branch to SinkBB if V0 >= 0)
7280 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7281 // SinkBB: V1 = PHI(V2, V3)
7282 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7283 MachineFunction::iterator BBI = BB;
7285 MachineFunction *Fn = BB->getParent();
7286 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7287 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7288 Fn->insert(BBI, RSBBB);
7289 Fn->insert(BBI, SinkBB);
7291 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7292 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7293 bool isThumb2 = Subtarget->isThumb2();
7294 MachineRegisterInfo &MRI = Fn->getRegInfo();
7295 // In Thumb mode S must not be specified if source register is the SP or
7296 // PC and if destination register is the SP, so restrict register class
7297 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7298 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7299 (const TargetRegisterClass*)&ARM::GPRRegClass);
7301 // Transfer the remainder of BB and its successor edges to sinkMBB.
7302 SinkBB->splice(SinkBB->begin(), BB,
7303 llvm::next(MachineBasicBlock::iterator(MI)),
7305 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7307 BB->addSuccessor(RSBBB);
7308 BB->addSuccessor(SinkBB);
7310 // fall through to SinkMBB
7311 RSBBB->addSuccessor(SinkBB);
7313 // insert a cmp at the end of BB
7314 AddDefaultPred(BuildMI(BB, dl,
7315 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7316 .addReg(ABSSrcReg).addImm(0));
7318 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7320 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7321 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7323 // insert rsbri in RSBBB
7324 // Note: BCC and rsbri will be converted into predicated rsbmi
7325 // by if-conversion pass
7326 BuildMI(*RSBBB, RSBBB->begin(), dl,
7327 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7328 .addReg(ABSSrcReg, RegState::Kill)
7329 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7331 // insert PHI in SinkBB,
7332 // reuse ABSDstReg to not change uses of ABS instruction
7333 BuildMI(*SinkBB, SinkBB->begin(), dl,
7334 TII->get(ARM::PHI), ABSDstReg)
7335 .addReg(NewRsbDstReg).addMBB(RSBBB)
7336 .addReg(ABSSrcReg).addMBB(BB);
7338 // remove ABS instruction
7339 MI->eraseFromParent();
7341 // return last added BB
7344 case ARM::COPY_STRUCT_BYVAL_I32:
7346 return EmitStructByval(MI, BB);
7350 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7351 SDNode *Node) const {
7352 if (!MI->hasPostISelHook()) {
7353 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7354 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7358 const MCInstrDesc *MCID = &MI->getDesc();
7359 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7360 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7361 // operand is still set to noreg. If needed, set the optional operand's
7362 // register to CPSR, and remove the redundant implicit def.
7364 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7366 // Rename pseudo opcodes.
7367 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7369 const ARMBaseInstrInfo *TII =
7370 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7371 MCID = &TII->get(NewOpc);
7373 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7374 "converted opcode should be the same except for cc_out");
7378 // Add the optional cc_out operand
7379 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7381 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7383 // Any ARM instruction that sets the 's' bit should specify an optional
7384 // "cc_out" operand in the last operand position.
7385 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7386 assert(!NewOpc && "Optional cc_out operand required");
7389 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7390 // since we already have an optional CPSR def.
7391 bool definesCPSR = false;
7392 bool deadCPSR = false;
7393 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7395 const MachineOperand &MO = MI->getOperand(i);
7396 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7400 MI->RemoveOperand(i);
7405 assert(!NewOpc && "Optional cc_out operand required");
7408 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7410 assert(!MI->getOperand(ccOutIdx).getReg() &&
7411 "expect uninitialized optional cc_out operand");
7415 // If this instruction was defined with an optional CPSR def and its dag node
7416 // had a live implicit CPSR def, then activate the optional CPSR def.
7417 MachineOperand &MO = MI->getOperand(ccOutIdx);
7418 MO.setReg(ARM::CPSR);
7422 //===----------------------------------------------------------------------===//
7423 // ARM Optimization Hooks
7424 //===----------------------------------------------------------------------===//
7426 // Helper function that checks if N is a null or all ones constant.
7427 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7428 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7431 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7434 // Return true if N is conditionally 0 or all ones.
7435 // Detects these expressions where cc is an i1 value:
7437 // (select cc 0, y) [AllOnes=0]
7438 // (select cc y, 0) [AllOnes=0]
7439 // (zext cc) [AllOnes=0]
7440 // (sext cc) [AllOnes=0/1]
7441 // (select cc -1, y) [AllOnes=1]
7442 // (select cc y, -1) [AllOnes=1]
7444 // Invert is set when N is the null/all ones constant when CC is false.
7445 // OtherOp is set to the alternative value of N.
7446 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7447 SDValue &CC, bool &Invert,
7449 SelectionDAG &DAG) {
7450 switch (N->getOpcode()) {
7451 default: return false;
7453 CC = N->getOperand(0);
7454 SDValue N1 = N->getOperand(1);
7455 SDValue N2 = N->getOperand(2);
7456 if (isZeroOrAllOnes(N1, AllOnes)) {
7461 if (isZeroOrAllOnes(N2, AllOnes)) {
7468 case ISD::ZERO_EXTEND:
7469 // (zext cc) can never be the all ones value.
7473 case ISD::SIGN_EXTEND: {
7474 EVT VT = N->getValueType(0);
7475 CC = N->getOperand(0);
7476 if (CC.getValueType() != MVT::i1)
7480 // When looking for an AllOnes constant, N is an sext, and the 'other'
7482 OtherOp = DAG.getConstant(0, VT);
7483 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7484 // When looking for a 0 constant, N can be zext or sext.
7485 OtherOp = DAG.getConstant(1, VT);
7487 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7493 // Combine a constant select operand into its use:
7495 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7496 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7497 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7498 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7499 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7501 // The transform is rejected if the select doesn't have a constant operand that
7502 // is null, or all ones when AllOnes is set.
7504 // Also recognize sext/zext from i1:
7506 // (add (zext cc), x) -> (select cc (add x, 1), x)
7507 // (add (sext cc), x) -> (select cc (add x, -1), x)
7509 // These transformations eventually create predicated instructions.
7511 // @param N The node to transform.
7512 // @param Slct The N operand that is a select.
7513 // @param OtherOp The other N operand (x above).
7514 // @param DCI Context.
7515 // @param AllOnes Require the select constant to be all ones instead of null.
7516 // @returns The new node, or SDValue() on failure.
7518 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7519 TargetLowering::DAGCombinerInfo &DCI,
7520 bool AllOnes = false) {
7521 SelectionDAG &DAG = DCI.DAG;
7522 EVT VT = N->getValueType(0);
7523 SDValue NonConstantVal;
7526 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7527 NonConstantVal, DAG))
7530 // Slct is now know to be the desired identity constant when CC is true.
7531 SDValue TrueVal = OtherOp;
7532 SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7533 OtherOp, NonConstantVal);
7534 // Unless SwapSelectOps says CC should be false.
7536 std::swap(TrueVal, FalseVal);
7538 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7539 CCOp, TrueVal, FalseVal);
7542 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7544 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7545 TargetLowering::DAGCombinerInfo &DCI) {
7546 SDValue N0 = N->getOperand(0);
7547 SDValue N1 = N->getOperand(1);
7548 if (N0.getNode()->hasOneUse()) {
7549 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7550 if (Result.getNode())
7553 if (N1.getNode()->hasOneUse()) {
7554 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7555 if (Result.getNode())
7561 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7562 // (only after legalization).
7563 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7564 TargetLowering::DAGCombinerInfo &DCI,
7565 const ARMSubtarget *Subtarget) {
7567 // Only perform optimization if after legalize, and if NEON is available. We
7568 // also expected both operands to be BUILD_VECTORs.
7569 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7570 || N0.getOpcode() != ISD::BUILD_VECTOR
7571 || N1.getOpcode() != ISD::BUILD_VECTOR)
7574 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7575 EVT VT = N->getValueType(0);
7576 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7579 // Check that the vector operands are of the right form.
7580 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7581 // operands, where N is the size of the formed vector.
7582 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7583 // index such that we have a pair wise add pattern.
7585 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7586 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7588 SDValue Vec = N0->getOperand(0)->getOperand(0);
7589 SDNode *V = Vec.getNode();
7590 unsigned nextIndex = 0;
7592 // For each operands to the ADD which are BUILD_VECTORs,
7593 // check to see if each of their operands are an EXTRACT_VECTOR with
7594 // the same vector and appropriate index.
7595 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7596 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7597 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7599 SDValue ExtVec0 = N0->getOperand(i);
7600 SDValue ExtVec1 = N1->getOperand(i);
7602 // First operand is the vector, verify its the same.
7603 if (V != ExtVec0->getOperand(0).getNode() ||
7604 V != ExtVec1->getOperand(0).getNode())
7607 // Second is the constant, verify its correct.
7608 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7609 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7611 // For the constant, we want to see all the even or all the odd.
7612 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7613 || C1->getZExtValue() != nextIndex+1)
7622 // Create VPADDL node.
7623 SelectionDAG &DAG = DCI.DAG;
7624 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7626 // Build operand list.
7627 SmallVector<SDValue, 8> Ops;
7628 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7629 TLI.getPointerTy()));
7631 // Input is the vector.
7634 // Get widened type and narrowed type.
7636 unsigned numElem = VT.getVectorNumElements();
7637 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7638 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7639 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7640 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7642 llvm_unreachable("Invalid vector element type for padd optimization.");
7645 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7646 widenType, &Ops[0], Ops.size());
7647 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7650 static SDValue findMUL_LOHI(SDValue V) {
7651 if (V->getOpcode() == ISD::UMUL_LOHI ||
7652 V->getOpcode() == ISD::SMUL_LOHI)
7657 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7658 TargetLowering::DAGCombinerInfo &DCI,
7659 const ARMSubtarget *Subtarget) {
7661 if (Subtarget->isThumb1Only()) return SDValue();
7663 // Only perform the checks after legalize when the pattern is available.
7664 if (DCI.isBeforeLegalize()) return SDValue();
7666 // Look for multiply add opportunities.
7667 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7668 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7669 // a glue link from the first add to the second add.
7670 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7671 // a S/UMLAL instruction.
7674 // \ / \ [no multiline comment]
7680 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7681 SDValue AddcOp0 = AddcNode->getOperand(0);
7682 SDValue AddcOp1 = AddcNode->getOperand(1);
7684 // Check if the two operands are from the same mul_lohi node.
7685 if (AddcOp0.getNode() == AddcOp1.getNode())
7688 assert(AddcNode->getNumValues() == 2 &&
7689 AddcNode->getValueType(0) == MVT::i32 &&
7690 AddcNode->getValueType(1) == MVT::Glue &&
7691 "Expect ADDC with two result values: i32, glue");
7693 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7694 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7695 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7696 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7697 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7700 // Look for the glued ADDE.
7701 SDNode* AddeNode = AddcNode->getGluedUser();
7702 if (AddeNode == NULL)
7705 // Make sure it is really an ADDE.
7706 if (AddeNode->getOpcode() != ISD::ADDE)
7709 assert(AddeNode->getNumOperands() == 3 &&
7710 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7711 "ADDE node has the wrong inputs");
7713 // Check for the triangle shape.
7714 SDValue AddeOp0 = AddeNode->getOperand(0);
7715 SDValue AddeOp1 = AddeNode->getOperand(1);
7717 // Make sure that the ADDE operands are not coming from the same node.
7718 if (AddeOp0.getNode() == AddeOp1.getNode())
7721 // Find the MUL_LOHI node walking up ADDE's operands.
7722 bool IsLeftOperandMUL = false;
7723 SDValue MULOp = findMUL_LOHI(AddeOp0);
7724 if (MULOp == SDValue())
7725 MULOp = findMUL_LOHI(AddeOp1);
7727 IsLeftOperandMUL = true;
7728 if (MULOp == SDValue())
7731 // Figure out the right opcode.
7732 unsigned Opc = MULOp->getOpcode();
7733 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7735 // Figure out the high and low input values to the MLAL node.
7736 SDValue* HiMul = &MULOp;
7737 SDValue* HiAdd = NULL;
7738 SDValue* LoMul = NULL;
7739 SDValue* LowAdd = NULL;
7741 if (IsLeftOperandMUL)
7747 if (AddcOp0->getOpcode() == Opc) {
7751 if (AddcOp1->getOpcode() == Opc) {
7759 if (LoMul->getNode() != HiMul->getNode())
7762 // Create the merged node.
7763 SelectionDAG &DAG = DCI.DAG;
7765 // Build operand list.
7766 SmallVector<SDValue, 8> Ops;
7767 Ops.push_back(LoMul->getOperand(0));
7768 Ops.push_back(LoMul->getOperand(1));
7769 Ops.push_back(*LowAdd);
7770 Ops.push_back(*HiAdd);
7772 SDValue MLALNode = DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7773 DAG.getVTList(MVT::i32, MVT::i32),
7774 &Ops[0], Ops.size());
7776 // Replace the ADDs' nodes uses by the MLA node's values.
7777 SDValue HiMLALResult(MLALNode.getNode(), 1);
7778 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7780 SDValue LoMLALResult(MLALNode.getNode(), 0);
7781 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7783 // Return original node to notify the driver to stop replacing.
7784 SDValue resNode(AddcNode, 0);
7788 /// PerformADDCCombine - Target-specific dag combine transform from
7789 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7790 static SDValue PerformADDCCombine(SDNode *N,
7791 TargetLowering::DAGCombinerInfo &DCI,
7792 const ARMSubtarget *Subtarget) {
7794 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7798 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7799 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7800 /// called with the default operands, and if that fails, with commuted
7802 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7803 TargetLowering::DAGCombinerInfo &DCI,
7804 const ARMSubtarget *Subtarget){
7806 // Attempt to create vpaddl for this add.
7807 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7808 if (Result.getNode())
7811 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7812 if (N0.getNode()->hasOneUse()) {
7813 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7814 if (Result.getNode()) return Result;
7819 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7821 static SDValue PerformADDCombine(SDNode *N,
7822 TargetLowering::DAGCombinerInfo &DCI,
7823 const ARMSubtarget *Subtarget) {
7824 SDValue N0 = N->getOperand(0);
7825 SDValue N1 = N->getOperand(1);
7827 // First try with the default operand order.
7828 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7829 if (Result.getNode())
7832 // If that didn't work, try again with the operands commuted.
7833 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7836 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7838 static SDValue PerformSUBCombine(SDNode *N,
7839 TargetLowering::DAGCombinerInfo &DCI) {
7840 SDValue N0 = N->getOperand(0);
7841 SDValue N1 = N->getOperand(1);
7843 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7844 if (N1.getNode()->hasOneUse()) {
7845 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7846 if (Result.getNode()) return Result;
7852 /// PerformVMULCombine
7853 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7854 /// special multiplier accumulator forwarding.
7860 static SDValue PerformVMULCombine(SDNode *N,
7861 TargetLowering::DAGCombinerInfo &DCI,
7862 const ARMSubtarget *Subtarget) {
7863 if (!Subtarget->hasVMLxForwarding())
7866 SelectionDAG &DAG = DCI.DAG;
7867 SDValue N0 = N->getOperand(0);
7868 SDValue N1 = N->getOperand(1);
7869 unsigned Opcode = N0.getOpcode();
7870 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7871 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7872 Opcode = N1.getOpcode();
7873 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7874 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7879 EVT VT = N->getValueType(0);
7880 DebugLoc DL = N->getDebugLoc();
7881 SDValue N00 = N0->getOperand(0);
7882 SDValue N01 = N0->getOperand(1);
7883 return DAG.getNode(Opcode, DL, VT,
7884 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7885 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7888 static SDValue PerformMULCombine(SDNode *N,
7889 TargetLowering::DAGCombinerInfo &DCI,
7890 const ARMSubtarget *Subtarget) {
7891 SelectionDAG &DAG = DCI.DAG;
7893 if (Subtarget->isThumb1Only())
7896 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7899 EVT VT = N->getValueType(0);
7900 if (VT.is64BitVector() || VT.is128BitVector())
7901 return PerformVMULCombine(N, DCI, Subtarget);
7905 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7909 int64_t MulAmt = C->getSExtValue();
7910 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7912 ShiftAmt = ShiftAmt & (32 - 1);
7913 SDValue V = N->getOperand(0);
7914 DebugLoc DL = N->getDebugLoc();
7917 MulAmt >>= ShiftAmt;
7920 if (isPowerOf2_32(MulAmt - 1)) {
7921 // (mul x, 2^N + 1) => (add (shl x, N), x)
7922 Res = DAG.getNode(ISD::ADD, DL, VT,
7924 DAG.getNode(ISD::SHL, DL, VT,
7926 DAG.getConstant(Log2_32(MulAmt - 1),
7928 } else if (isPowerOf2_32(MulAmt + 1)) {
7929 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7930 Res = DAG.getNode(ISD::SUB, DL, VT,
7931 DAG.getNode(ISD::SHL, DL, VT,
7933 DAG.getConstant(Log2_32(MulAmt + 1),
7939 uint64_t MulAmtAbs = -MulAmt;
7940 if (isPowerOf2_32(MulAmtAbs + 1)) {
7941 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7942 Res = DAG.getNode(ISD::SUB, DL, VT,
7944 DAG.getNode(ISD::SHL, DL, VT,
7946 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7948 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7949 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7950 Res = DAG.getNode(ISD::ADD, DL, VT,
7952 DAG.getNode(ISD::SHL, DL, VT,
7954 DAG.getConstant(Log2_32(MulAmtAbs-1),
7956 Res = DAG.getNode(ISD::SUB, DL, VT,
7957 DAG.getConstant(0, MVT::i32),Res);
7964 Res = DAG.getNode(ISD::SHL, DL, VT,
7965 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7967 // Do not add new nodes to DAG combiner worklist.
7968 DCI.CombineTo(N, Res, false);
7972 static SDValue PerformANDCombine(SDNode *N,
7973 TargetLowering::DAGCombinerInfo &DCI,
7974 const ARMSubtarget *Subtarget) {
7976 // Attempt to use immediate-form VBIC
7977 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7978 DebugLoc dl = N->getDebugLoc();
7979 EVT VT = N->getValueType(0);
7980 SelectionDAG &DAG = DCI.DAG;
7982 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7985 APInt SplatBits, SplatUndef;
7986 unsigned SplatBitSize;
7989 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7990 if (SplatBitSize <= 64) {
7992 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7993 SplatUndef.getZExtValue(), SplatBitSize,
7994 DAG, VbicVT, VT.is128BitVector(),
7996 if (Val.getNode()) {
7998 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7999 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8000 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8005 if (!Subtarget->isThumb1Only()) {
8006 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8007 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8008 if (Result.getNode())
8015 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8016 static SDValue PerformORCombine(SDNode *N,
8017 TargetLowering::DAGCombinerInfo &DCI,
8018 const ARMSubtarget *Subtarget) {
8019 // Attempt to use immediate-form VORR
8020 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8021 DebugLoc dl = N->getDebugLoc();
8022 EVT VT = N->getValueType(0);
8023 SelectionDAG &DAG = DCI.DAG;
8025 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8028 APInt SplatBits, SplatUndef;
8029 unsigned SplatBitSize;
8031 if (BVN && Subtarget->hasNEON() &&
8032 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8033 if (SplatBitSize <= 64) {
8035 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8036 SplatUndef.getZExtValue(), SplatBitSize,
8037 DAG, VorrVT, VT.is128BitVector(),
8039 if (Val.getNode()) {
8041 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8042 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8043 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8048 if (!Subtarget->isThumb1Only()) {
8049 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8050 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8051 if (Result.getNode())
8055 // The code below optimizes (or (and X, Y), Z).
8056 // The AND operand needs to have a single user to make these optimizations
8058 SDValue N0 = N->getOperand(0);
8059 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8061 SDValue N1 = N->getOperand(1);
8063 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8064 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8065 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8067 unsigned SplatBitSize;
8070 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8072 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8073 HasAnyUndefs) && !HasAnyUndefs) {
8074 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8076 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8077 HasAnyUndefs) && !HasAnyUndefs &&
8078 SplatBits0 == ~SplatBits1) {
8079 // Canonicalize the vector type to make instruction selection simpler.
8080 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8081 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8082 N0->getOperand(1), N0->getOperand(0),
8084 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8089 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8092 // BFI is only available on V6T2+
8093 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8096 DebugLoc DL = N->getDebugLoc();
8097 // 1) or (and A, mask), val => ARMbfi A, val, mask
8098 // iff (val & mask) == val
8100 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8101 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8102 // && mask == ~mask2
8103 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8104 // && ~mask == mask2
8105 // (i.e., copy a bitfield value into another bitfield of the same width)
8110 SDValue N00 = N0.getOperand(0);
8112 // The value and the mask need to be constants so we can verify this is
8113 // actually a bitfield set. If the mask is 0xffff, we can do better
8114 // via a movt instruction, so don't use BFI in that case.
8115 SDValue MaskOp = N0.getOperand(1);
8116 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8119 unsigned Mask = MaskC->getZExtValue();
8123 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8124 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8126 unsigned Val = N1C->getZExtValue();
8127 if ((Val & ~Mask) != Val)
8130 if (ARM::isBitFieldInvertedMask(Mask)) {
8131 Val >>= CountTrailingZeros_32(~Mask);
8133 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8134 DAG.getConstant(Val, MVT::i32),
8135 DAG.getConstant(Mask, MVT::i32));
8137 // Do not add new nodes to DAG combiner worklist.
8138 DCI.CombineTo(N, Res, false);
8141 } else if (N1.getOpcode() == ISD::AND) {
8142 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8143 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8146 unsigned Mask2 = N11C->getZExtValue();
8148 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8150 if (ARM::isBitFieldInvertedMask(Mask) &&
8152 // The pack halfword instruction works better for masks that fit it,
8153 // so use that when it's available.
8154 if (Subtarget->hasT2ExtractPack() &&
8155 (Mask == 0xffff || Mask == 0xffff0000))
8158 unsigned amt = CountTrailingZeros_32(Mask2);
8159 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8160 DAG.getConstant(amt, MVT::i32));
8161 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8162 DAG.getConstant(Mask, MVT::i32));
8163 // Do not add new nodes to DAG combiner worklist.
8164 DCI.CombineTo(N, Res, false);
8166 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8168 // The pack halfword instruction works better for masks that fit it,
8169 // so use that when it's available.
8170 if (Subtarget->hasT2ExtractPack() &&
8171 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8174 unsigned lsb = CountTrailingZeros_32(Mask);
8175 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8176 DAG.getConstant(lsb, MVT::i32));
8177 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8178 DAG.getConstant(Mask2, MVT::i32));
8179 // Do not add new nodes to DAG combiner worklist.
8180 DCI.CombineTo(N, Res, false);
8185 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8186 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8187 ARM::isBitFieldInvertedMask(~Mask)) {
8188 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8189 // where lsb(mask) == #shamt and masked bits of B are known zero.
8190 SDValue ShAmt = N00.getOperand(1);
8191 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8192 unsigned LSB = CountTrailingZeros_32(Mask);
8196 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8197 DAG.getConstant(~Mask, MVT::i32));
8199 // Do not add new nodes to DAG combiner worklist.
8200 DCI.CombineTo(N, Res, false);
8206 static SDValue PerformXORCombine(SDNode *N,
8207 TargetLowering::DAGCombinerInfo &DCI,
8208 const ARMSubtarget *Subtarget) {
8209 EVT VT = N->getValueType(0);
8210 SelectionDAG &DAG = DCI.DAG;
8212 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8215 if (!Subtarget->isThumb1Only()) {
8216 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8217 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8218 if (Result.getNode())
8225 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8226 /// the bits being cleared by the AND are not demanded by the BFI.
8227 static SDValue PerformBFICombine(SDNode *N,
8228 TargetLowering::DAGCombinerInfo &DCI) {
8229 SDValue N1 = N->getOperand(1);
8230 if (N1.getOpcode() == ISD::AND) {
8231 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8234 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8235 unsigned LSB = CountTrailingZeros_32(~InvMask);
8236 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8237 unsigned Mask = (1 << Width)-1;
8238 unsigned Mask2 = N11C->getZExtValue();
8239 if ((Mask & (~Mask2)) == 0)
8240 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8241 N->getOperand(0), N1.getOperand(0),
8247 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8248 /// ARMISD::VMOVRRD.
8249 static SDValue PerformVMOVRRDCombine(SDNode *N,
8250 TargetLowering::DAGCombinerInfo &DCI) {
8251 // vmovrrd(vmovdrr x, y) -> x,y
8252 SDValue InDouble = N->getOperand(0);
8253 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8254 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8256 // vmovrrd(load f64) -> (load i32), (load i32)
8257 SDNode *InNode = InDouble.getNode();
8258 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8259 InNode->getValueType(0) == MVT::f64 &&
8260 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8261 !cast<LoadSDNode>(InNode)->isVolatile()) {
8262 // TODO: Should this be done for non-FrameIndex operands?
8263 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8265 SelectionDAG &DAG = DCI.DAG;
8266 DebugLoc DL = LD->getDebugLoc();
8267 SDValue BasePtr = LD->getBasePtr();
8268 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8269 LD->getPointerInfo(), LD->isVolatile(),
8270 LD->isNonTemporal(), LD->isInvariant(),
8271 LD->getAlignment());
8273 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8274 DAG.getConstant(4, MVT::i32));
8275 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8276 LD->getPointerInfo(), LD->isVolatile(),
8277 LD->isNonTemporal(), LD->isInvariant(),
8278 std::min(4U, LD->getAlignment() / 2));
8280 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8281 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8282 DCI.RemoveFromWorklist(LD);
8290 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8291 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8292 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8293 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8294 SDValue Op0 = N->getOperand(0);
8295 SDValue Op1 = N->getOperand(1);
8296 if (Op0.getOpcode() == ISD::BITCAST)
8297 Op0 = Op0.getOperand(0);
8298 if (Op1.getOpcode() == ISD::BITCAST)
8299 Op1 = Op1.getOperand(0);
8300 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8301 Op0.getNode() == Op1.getNode() &&
8302 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8303 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8304 N->getValueType(0), Op0.getOperand(0));
8308 /// PerformSTORECombine - Target-specific dag combine xforms for
8310 static SDValue PerformSTORECombine(SDNode *N,
8311 TargetLowering::DAGCombinerInfo &DCI) {
8312 StoreSDNode *St = cast<StoreSDNode>(N);
8313 if (St->isVolatile())
8316 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8317 // pack all of the elements in one place. Next, store to memory in fewer
8319 SDValue StVal = St->getValue();
8320 EVT VT = StVal.getValueType();
8321 if (St->isTruncatingStore() && VT.isVector()) {
8322 SelectionDAG &DAG = DCI.DAG;
8323 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8324 EVT StVT = St->getMemoryVT();
8325 unsigned NumElems = VT.getVectorNumElements();
8326 assert(StVT != VT && "Cannot truncate to the same type");
8327 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8328 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8330 // From, To sizes and ElemCount must be pow of two
8331 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8333 // We are going to use the original vector elt for storing.
8334 // Accumulated smaller vector elements must be a multiple of the store size.
8335 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8337 unsigned SizeRatio = FromEltSz / ToEltSz;
8338 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8340 // Create a type on which we perform the shuffle.
8341 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8342 NumElems*SizeRatio);
8343 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8345 DebugLoc DL = St->getDebugLoc();
8346 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8347 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8348 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8350 // Can't shuffle using an illegal type.
8351 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8353 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8354 DAG.getUNDEF(WideVec.getValueType()),
8356 // At this point all of the data is stored at the bottom of the
8357 // register. We now need to save it to mem.
8359 // Find the largest store unit
8360 MVT StoreType = MVT::i8;
8361 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8362 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8363 MVT Tp = (MVT::SimpleValueType)tp;
8364 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8367 // Didn't find a legal store type.
8368 if (!TLI.isTypeLegal(StoreType))
8371 // Bitcast the original vector into a vector of store-size units
8372 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8373 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8374 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8375 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8376 SmallVector<SDValue, 8> Chains;
8377 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8378 TLI.getPointerTy());
8379 SDValue BasePtr = St->getBasePtr();
8381 // Perform one or more big stores into memory.
8382 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8383 for (unsigned I = 0; I < E; I++) {
8384 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8385 StoreType, ShuffWide,
8386 DAG.getIntPtrConstant(I));
8387 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8388 St->getPointerInfo(), St->isVolatile(),
8389 St->isNonTemporal(), St->getAlignment());
8390 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8392 Chains.push_back(Ch);
8394 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8398 if (!ISD::isNormalStore(St))
8401 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8402 // ARM stores of arguments in the same cache line.
8403 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8404 StVal.getNode()->hasOneUse()) {
8405 SelectionDAG &DAG = DCI.DAG;
8406 DebugLoc DL = St->getDebugLoc();
8407 SDValue BasePtr = St->getBasePtr();
8408 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8409 StVal.getNode()->getOperand(0), BasePtr,
8410 St->getPointerInfo(), St->isVolatile(),
8411 St->isNonTemporal(), St->getAlignment());
8413 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8414 DAG.getConstant(4, MVT::i32));
8415 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8416 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8417 St->isNonTemporal(),
8418 std::min(4U, St->getAlignment() / 2));
8421 if (StVal.getValueType() != MVT::i64 ||
8422 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8425 // Bitcast an i64 store extracted from a vector to f64.
8426 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8427 SelectionDAG &DAG = DCI.DAG;
8428 DebugLoc dl = StVal.getDebugLoc();
8429 SDValue IntVec = StVal.getOperand(0);
8430 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8431 IntVec.getValueType().getVectorNumElements());
8432 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8433 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8434 Vec, StVal.getOperand(1));
8435 dl = N->getDebugLoc();
8436 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8437 // Make the DAGCombiner fold the bitcasts.
8438 DCI.AddToWorklist(Vec.getNode());
8439 DCI.AddToWorklist(ExtElt.getNode());
8440 DCI.AddToWorklist(V.getNode());
8441 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8442 St->getPointerInfo(), St->isVolatile(),
8443 St->isNonTemporal(), St->getAlignment(),
8447 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8448 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8449 /// i64 vector to have f64 elements, since the value can then be loaded
8450 /// directly into a VFP register.
8451 static bool hasNormalLoadOperand(SDNode *N) {
8452 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8453 for (unsigned i = 0; i < NumElts; ++i) {
8454 SDNode *Elt = N->getOperand(i).getNode();
8455 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8461 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8462 /// ISD::BUILD_VECTOR.
8463 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8464 TargetLowering::DAGCombinerInfo &DCI){
8465 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8466 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8467 // into a pair of GPRs, which is fine when the value is used as a scalar,
8468 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8469 SelectionDAG &DAG = DCI.DAG;
8470 if (N->getNumOperands() == 2) {
8471 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8476 // Load i64 elements as f64 values so that type legalization does not split
8477 // them up into i32 values.
8478 EVT VT = N->getValueType(0);
8479 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8481 DebugLoc dl = N->getDebugLoc();
8482 SmallVector<SDValue, 8> Ops;
8483 unsigned NumElts = VT.getVectorNumElements();
8484 for (unsigned i = 0; i < NumElts; ++i) {
8485 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8487 // Make the DAGCombiner fold the bitcast.
8488 DCI.AddToWorklist(V.getNode());
8490 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8491 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8492 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8495 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8496 /// ISD::INSERT_VECTOR_ELT.
8497 static SDValue PerformInsertEltCombine(SDNode *N,
8498 TargetLowering::DAGCombinerInfo &DCI) {
8499 // Bitcast an i64 load inserted into a vector to f64.
8500 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8501 EVT VT = N->getValueType(0);
8502 SDNode *Elt = N->getOperand(1).getNode();
8503 if (VT.getVectorElementType() != MVT::i64 ||
8504 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8507 SelectionDAG &DAG = DCI.DAG;
8508 DebugLoc dl = N->getDebugLoc();
8509 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8510 VT.getVectorNumElements());
8511 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8512 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8513 // Make the DAGCombiner fold the bitcasts.
8514 DCI.AddToWorklist(Vec.getNode());
8515 DCI.AddToWorklist(V.getNode());
8516 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8517 Vec, V, N->getOperand(2));
8518 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8521 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8522 /// ISD::VECTOR_SHUFFLE.
8523 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8524 // The LLVM shufflevector instruction does not require the shuffle mask
8525 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8526 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8527 // operands do not match the mask length, they are extended by concatenating
8528 // them with undef vectors. That is probably the right thing for other
8529 // targets, but for NEON it is better to concatenate two double-register
8530 // size vector operands into a single quad-register size vector. Do that
8531 // transformation here:
8532 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8533 // shuffle(concat(v1, v2), undef)
8534 SDValue Op0 = N->getOperand(0);
8535 SDValue Op1 = N->getOperand(1);
8536 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8537 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8538 Op0.getNumOperands() != 2 ||
8539 Op1.getNumOperands() != 2)
8541 SDValue Concat0Op1 = Op0.getOperand(1);
8542 SDValue Concat1Op1 = Op1.getOperand(1);
8543 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8544 Concat1Op1.getOpcode() != ISD::UNDEF)
8546 // Skip the transformation if any of the types are illegal.
8547 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8548 EVT VT = N->getValueType(0);
8549 if (!TLI.isTypeLegal(VT) ||
8550 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8551 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8554 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8555 Op0.getOperand(0), Op1.getOperand(0));
8556 // Translate the shuffle mask.
8557 SmallVector<int, 16> NewMask;
8558 unsigned NumElts = VT.getVectorNumElements();
8559 unsigned HalfElts = NumElts/2;
8560 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8561 for (unsigned n = 0; n < NumElts; ++n) {
8562 int MaskElt = SVN->getMaskElt(n);
8564 if (MaskElt < (int)HalfElts)
8566 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8567 NewElt = HalfElts + MaskElt - NumElts;
8568 NewMask.push_back(NewElt);
8570 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8571 DAG.getUNDEF(VT), NewMask.data());
8574 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8575 /// NEON load/store intrinsics to merge base address updates.
8576 static SDValue CombineBaseUpdate(SDNode *N,
8577 TargetLowering::DAGCombinerInfo &DCI) {
8578 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8581 SelectionDAG &DAG = DCI.DAG;
8582 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8583 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8584 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8585 SDValue Addr = N->getOperand(AddrOpIdx);
8587 // Search for a use of the address operand that is an increment.
8588 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8589 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8591 if (User->getOpcode() != ISD::ADD ||
8592 UI.getUse().getResNo() != Addr.getResNo())
8595 // Check that the add is independent of the load/store. Otherwise, folding
8596 // it would create a cycle.
8597 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8600 // Find the new opcode for the updating load/store.
8602 bool isLaneOp = false;
8603 unsigned NewOpc = 0;
8604 unsigned NumVecs = 0;
8606 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8608 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8609 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8611 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8613 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8615 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8617 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8618 NumVecs = 2; isLaneOp = true; break;
8619 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8620 NumVecs = 3; isLaneOp = true; break;
8621 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8622 NumVecs = 4; isLaneOp = true; break;
8623 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8624 NumVecs = 1; isLoad = false; break;
8625 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8626 NumVecs = 2; isLoad = false; break;
8627 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8628 NumVecs = 3; isLoad = false; break;
8629 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8630 NumVecs = 4; isLoad = false; break;
8631 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8632 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8633 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8634 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8635 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8636 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8640 switch (N->getOpcode()) {
8641 default: llvm_unreachable("unexpected opcode for Neon base update");
8642 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8643 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8644 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8648 // Find the size of memory referenced by the load/store.
8651 VecTy = N->getValueType(0);
8653 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8654 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8656 NumBytes /= VecTy.getVectorNumElements();
8658 // If the increment is a constant, it must match the memory ref size.
8659 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8660 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8661 uint64_t IncVal = CInc->getZExtValue();
8662 if (IncVal != NumBytes)
8664 } else if (NumBytes >= 3 * 16) {
8665 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8666 // separate instructions that make it harder to use a non-constant update.
8670 // Create the new updating load/store node.
8672 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8674 for (n = 0; n < NumResultVecs; ++n)
8676 Tys[n++] = MVT::i32;
8677 Tys[n] = MVT::Other;
8678 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8679 SmallVector<SDValue, 8> Ops;
8680 Ops.push_back(N->getOperand(0)); // incoming chain
8681 Ops.push_back(N->getOperand(AddrOpIdx));
8683 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8684 Ops.push_back(N->getOperand(i));
8686 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8687 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8688 Ops.data(), Ops.size(),
8689 MemInt->getMemoryVT(),
8690 MemInt->getMemOperand());
8693 std::vector<SDValue> NewResults;
8694 for (unsigned i = 0; i < NumResultVecs; ++i) {
8695 NewResults.push_back(SDValue(UpdN.getNode(), i));
8697 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8698 DCI.CombineTo(N, NewResults);
8699 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8706 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8707 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8708 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8710 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8711 SelectionDAG &DAG = DCI.DAG;
8712 EVT VT = N->getValueType(0);
8713 // vldN-dup instructions only support 64-bit vectors for N > 1.
8714 if (!VT.is64BitVector())
8717 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8718 SDNode *VLD = N->getOperand(0).getNode();
8719 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8721 unsigned NumVecs = 0;
8722 unsigned NewOpc = 0;
8723 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8724 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8726 NewOpc = ARMISD::VLD2DUP;
8727 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8729 NewOpc = ARMISD::VLD3DUP;
8730 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8732 NewOpc = ARMISD::VLD4DUP;
8737 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8738 // numbers match the load.
8739 unsigned VLDLaneNo =
8740 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8741 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8743 // Ignore uses of the chain result.
8744 if (UI.getUse().getResNo() == NumVecs)
8747 if (User->getOpcode() != ARMISD::VDUPLANE ||
8748 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8752 // Create the vldN-dup node.
8755 for (n = 0; n < NumVecs; ++n)
8757 Tys[n] = MVT::Other;
8758 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8759 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8760 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8761 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8762 Ops, 2, VLDMemInt->getMemoryVT(),
8763 VLDMemInt->getMemOperand());
8766 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8768 unsigned ResNo = UI.getUse().getResNo();
8769 // Ignore uses of the chain result.
8770 if (ResNo == NumVecs)
8773 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8776 // Now the vldN-lane intrinsic is dead except for its chain result.
8777 // Update uses of the chain.
8778 std::vector<SDValue> VLDDupResults;
8779 for (unsigned n = 0; n < NumVecs; ++n)
8780 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8781 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8782 DCI.CombineTo(VLD, VLDDupResults);
8787 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8788 /// ARMISD::VDUPLANE.
8789 static SDValue PerformVDUPLANECombine(SDNode *N,
8790 TargetLowering::DAGCombinerInfo &DCI) {
8791 SDValue Op = N->getOperand(0);
8793 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8794 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8795 if (CombineVLDDUP(N, DCI))
8796 return SDValue(N, 0);
8798 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8799 // redundant. Ignore bit_converts for now; element sizes are checked below.
8800 while (Op.getOpcode() == ISD::BITCAST)
8801 Op = Op.getOperand(0);
8802 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8805 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8806 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8807 // The canonical VMOV for a zero vector uses a 32-bit element size.
8808 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8810 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8812 EVT VT = N->getValueType(0);
8813 if (EltSize > VT.getVectorElementType().getSizeInBits())
8816 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8819 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8820 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8821 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8825 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8827 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8832 APFloat APF = C->getValueAPF();
8833 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8834 != APFloat::opOK || !isExact)
8837 c0 = (I == 0) ? cN : c0;
8838 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8845 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8846 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8847 /// when the VMUL has a constant operand that is a power of 2.
8849 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8850 /// vmul.f32 d16, d17, d16
8851 /// vcvt.s32.f32 d16, d16
8853 /// vcvt.s32.f32 d16, d16, #3
8854 static SDValue PerformVCVTCombine(SDNode *N,
8855 TargetLowering::DAGCombinerInfo &DCI,
8856 const ARMSubtarget *Subtarget) {
8857 SelectionDAG &DAG = DCI.DAG;
8858 SDValue Op = N->getOperand(0);
8860 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8861 Op.getOpcode() != ISD::FMUL)
8865 SDValue N0 = Op->getOperand(0);
8866 SDValue ConstVec = Op->getOperand(1);
8867 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8869 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8870 !isConstVecPow2(ConstVec, isSigned, C))
8873 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8874 Intrinsic::arm_neon_vcvtfp2fxu;
8875 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8877 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8878 DAG.getConstant(Log2_64(C), MVT::i32));
8881 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8882 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8883 /// when the VDIV has a constant operand that is a power of 2.
8885 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8886 /// vcvt.f32.s32 d16, d16
8887 /// vdiv.f32 d16, d17, d16
8889 /// vcvt.f32.s32 d16, d16, #3
8890 static SDValue PerformVDIVCombine(SDNode *N,
8891 TargetLowering::DAGCombinerInfo &DCI,
8892 const ARMSubtarget *Subtarget) {
8893 SelectionDAG &DAG = DCI.DAG;
8894 SDValue Op = N->getOperand(0);
8895 unsigned OpOpcode = Op.getNode()->getOpcode();
8897 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8898 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8902 SDValue ConstVec = N->getOperand(1);
8903 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8905 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8906 !isConstVecPow2(ConstVec, isSigned, C))
8909 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8910 Intrinsic::arm_neon_vcvtfxu2fp;
8911 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8913 DAG.getConstant(IntrinsicOpcode, MVT::i32),
8914 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8917 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8918 /// operand of a vector shift operation, where all the elements of the
8919 /// build_vector must have the same constant integer value.
8920 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8921 // Ignore bit_converts.
8922 while (Op.getOpcode() == ISD::BITCAST)
8923 Op = Op.getOperand(0);
8924 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8925 APInt SplatBits, SplatUndef;
8926 unsigned SplatBitSize;
8928 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8929 HasAnyUndefs, ElementBits) ||
8930 SplatBitSize > ElementBits)
8932 Cnt = SplatBits.getSExtValue();
8936 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8937 /// operand of a vector shift left operation. That value must be in the range:
8938 /// 0 <= Value < ElementBits for a left shift; or
8939 /// 0 <= Value <= ElementBits for a long left shift.
8940 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8941 assert(VT.isVector() && "vector shift count is not a vector type");
8942 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8943 if (! getVShiftImm(Op, ElementBits, Cnt))
8945 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8948 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8949 /// operand of a vector shift right operation. For a shift opcode, the value
8950 /// is positive, but for an intrinsic the value count must be negative. The
8951 /// absolute value must be in the range:
8952 /// 1 <= |Value| <= ElementBits for a right shift; or
8953 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8954 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8956 assert(VT.isVector() && "vector shift count is not a vector type");
8957 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8958 if (! getVShiftImm(Op, ElementBits, Cnt))
8962 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8965 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8966 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8967 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8970 // Don't do anything for most intrinsics.
8973 // Vector shifts: check for immediate versions and lower them.
8974 // Note: This is done during DAG combining instead of DAG legalizing because
8975 // the build_vectors for 64-bit vector element shift counts are generally
8976 // not legal, and it is hard to see their values after they get legalized to
8977 // loads from a constant pool.
8978 case Intrinsic::arm_neon_vshifts:
8979 case Intrinsic::arm_neon_vshiftu:
8980 case Intrinsic::arm_neon_vshiftls:
8981 case Intrinsic::arm_neon_vshiftlu:
8982 case Intrinsic::arm_neon_vshiftn:
8983 case Intrinsic::arm_neon_vrshifts:
8984 case Intrinsic::arm_neon_vrshiftu:
8985 case Intrinsic::arm_neon_vrshiftn:
8986 case Intrinsic::arm_neon_vqshifts:
8987 case Intrinsic::arm_neon_vqshiftu:
8988 case Intrinsic::arm_neon_vqshiftsu:
8989 case Intrinsic::arm_neon_vqshiftns:
8990 case Intrinsic::arm_neon_vqshiftnu:
8991 case Intrinsic::arm_neon_vqshiftnsu:
8992 case Intrinsic::arm_neon_vqrshiftns:
8993 case Intrinsic::arm_neon_vqrshiftnu:
8994 case Intrinsic::arm_neon_vqrshiftnsu: {
8995 EVT VT = N->getOperand(1).getValueType();
8997 unsigned VShiftOpc = 0;
9000 case Intrinsic::arm_neon_vshifts:
9001 case Intrinsic::arm_neon_vshiftu:
9002 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9003 VShiftOpc = ARMISD::VSHL;
9006 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9007 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9008 ARMISD::VSHRs : ARMISD::VSHRu);
9013 case Intrinsic::arm_neon_vshiftls:
9014 case Intrinsic::arm_neon_vshiftlu:
9015 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9017 llvm_unreachable("invalid shift count for vshll intrinsic");
9019 case Intrinsic::arm_neon_vrshifts:
9020 case Intrinsic::arm_neon_vrshiftu:
9021 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9025 case Intrinsic::arm_neon_vqshifts:
9026 case Intrinsic::arm_neon_vqshiftu:
9027 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9031 case Intrinsic::arm_neon_vqshiftsu:
9032 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9034 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9036 case Intrinsic::arm_neon_vshiftn:
9037 case Intrinsic::arm_neon_vrshiftn:
9038 case Intrinsic::arm_neon_vqshiftns:
9039 case Intrinsic::arm_neon_vqshiftnu:
9040 case Intrinsic::arm_neon_vqshiftnsu:
9041 case Intrinsic::arm_neon_vqrshiftns:
9042 case Intrinsic::arm_neon_vqrshiftnu:
9043 case Intrinsic::arm_neon_vqrshiftnsu:
9044 // Narrowing shifts require an immediate right shift.
9045 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9047 llvm_unreachable("invalid shift count for narrowing vector shift "
9051 llvm_unreachable("unhandled vector shift");
9055 case Intrinsic::arm_neon_vshifts:
9056 case Intrinsic::arm_neon_vshiftu:
9057 // Opcode already set above.
9059 case Intrinsic::arm_neon_vshiftls:
9060 case Intrinsic::arm_neon_vshiftlu:
9061 if (Cnt == VT.getVectorElementType().getSizeInBits())
9062 VShiftOpc = ARMISD::VSHLLi;
9064 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9065 ARMISD::VSHLLs : ARMISD::VSHLLu);
9067 case Intrinsic::arm_neon_vshiftn:
9068 VShiftOpc = ARMISD::VSHRN; break;
9069 case Intrinsic::arm_neon_vrshifts:
9070 VShiftOpc = ARMISD::VRSHRs; break;
9071 case Intrinsic::arm_neon_vrshiftu:
9072 VShiftOpc = ARMISD::VRSHRu; break;
9073 case Intrinsic::arm_neon_vrshiftn:
9074 VShiftOpc = ARMISD::VRSHRN; break;
9075 case Intrinsic::arm_neon_vqshifts:
9076 VShiftOpc = ARMISD::VQSHLs; break;
9077 case Intrinsic::arm_neon_vqshiftu:
9078 VShiftOpc = ARMISD::VQSHLu; break;
9079 case Intrinsic::arm_neon_vqshiftsu:
9080 VShiftOpc = ARMISD::VQSHLsu; break;
9081 case Intrinsic::arm_neon_vqshiftns:
9082 VShiftOpc = ARMISD::VQSHRNs; break;
9083 case Intrinsic::arm_neon_vqshiftnu:
9084 VShiftOpc = ARMISD::VQSHRNu; break;
9085 case Intrinsic::arm_neon_vqshiftnsu:
9086 VShiftOpc = ARMISD::VQSHRNsu; break;
9087 case Intrinsic::arm_neon_vqrshiftns:
9088 VShiftOpc = ARMISD::VQRSHRNs; break;
9089 case Intrinsic::arm_neon_vqrshiftnu:
9090 VShiftOpc = ARMISD::VQRSHRNu; break;
9091 case Intrinsic::arm_neon_vqrshiftnsu:
9092 VShiftOpc = ARMISD::VQRSHRNsu; break;
9095 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9096 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9099 case Intrinsic::arm_neon_vshiftins: {
9100 EVT VT = N->getOperand(1).getValueType();
9102 unsigned VShiftOpc = 0;
9104 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9105 VShiftOpc = ARMISD::VSLI;
9106 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9107 VShiftOpc = ARMISD::VSRI;
9109 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9112 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9113 N->getOperand(1), N->getOperand(2),
9114 DAG.getConstant(Cnt, MVT::i32));
9117 case Intrinsic::arm_neon_vqrshifts:
9118 case Intrinsic::arm_neon_vqrshiftu:
9119 // No immediate versions of these to check for.
9126 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9127 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9128 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9129 /// vector element shift counts are generally not legal, and it is hard to see
9130 /// their values after they get legalized to loads from a constant pool.
9131 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9132 const ARMSubtarget *ST) {
9133 EVT VT = N->getValueType(0);
9134 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9135 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9136 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9137 SDValue N1 = N->getOperand(1);
9138 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9139 SDValue N0 = N->getOperand(0);
9140 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9141 DAG.MaskedValueIsZero(N0.getOperand(0),
9142 APInt::getHighBitsSet(32, 16)))
9143 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9147 // Nothing to be done for scalar shifts.
9148 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9149 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9152 assert(ST->hasNEON() && "unexpected vector shift");
9155 switch (N->getOpcode()) {
9156 default: llvm_unreachable("unexpected shift opcode");
9159 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9160 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9161 DAG.getConstant(Cnt, MVT::i32));
9166 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9167 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9168 ARMISD::VSHRs : ARMISD::VSHRu);
9169 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9170 DAG.getConstant(Cnt, MVT::i32));
9176 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9177 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9178 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9179 const ARMSubtarget *ST) {
9180 SDValue N0 = N->getOperand(0);
9182 // Check for sign- and zero-extensions of vector extract operations of 8-
9183 // and 16-bit vector elements. NEON supports these directly. They are
9184 // handled during DAG combining because type legalization will promote them
9185 // to 32-bit types and it is messy to recognize the operations after that.
9186 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9187 SDValue Vec = N0.getOperand(0);
9188 SDValue Lane = N0.getOperand(1);
9189 EVT VT = N->getValueType(0);
9190 EVT EltVT = N0.getValueType();
9191 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9193 if (VT == MVT::i32 &&
9194 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9195 TLI.isTypeLegal(Vec.getValueType()) &&
9196 isa<ConstantSDNode>(Lane)) {
9199 switch (N->getOpcode()) {
9200 default: llvm_unreachable("unexpected opcode");
9201 case ISD::SIGN_EXTEND:
9202 Opc = ARMISD::VGETLANEs;
9204 case ISD::ZERO_EXTEND:
9205 case ISD::ANY_EXTEND:
9206 Opc = ARMISD::VGETLANEu;
9209 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9216 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9217 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9218 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9219 const ARMSubtarget *ST) {
9220 // If the target supports NEON, try to use vmax/vmin instructions for f32
9221 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9222 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9223 // a NaN; only do the transformation when it matches that behavior.
9225 // For now only do this when using NEON for FP operations; if using VFP, it
9226 // is not obvious that the benefit outweighs the cost of switching to the
9228 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9229 N->getValueType(0) != MVT::f32)
9232 SDValue CondLHS = N->getOperand(0);
9233 SDValue CondRHS = N->getOperand(1);
9234 SDValue LHS = N->getOperand(2);
9235 SDValue RHS = N->getOperand(3);
9236 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9238 unsigned Opcode = 0;
9240 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9241 IsReversed = false; // x CC y ? x : y
9242 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9243 IsReversed = true ; // x CC y ? y : x
9257 // If LHS is NaN, an ordered comparison will be false and the result will
9258 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9259 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9260 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9261 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9263 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9264 // will return -0, so vmin can only be used for unsafe math or if one of
9265 // the operands is known to be nonzero.
9266 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9267 !DAG.getTarget().Options.UnsafeFPMath &&
9268 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9270 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9279 // If LHS is NaN, an ordered comparison will be false and the result will
9280 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9281 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9282 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9283 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9285 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9286 // will return +0, so vmax can only be used for unsafe math or if one of
9287 // the operands is known to be nonzero.
9288 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9289 !DAG.getTarget().Options.UnsafeFPMath &&
9290 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9292 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9298 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9301 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9303 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9304 SDValue Cmp = N->getOperand(4);
9305 if (Cmp.getOpcode() != ARMISD::CMPZ)
9306 // Only looking at EQ and NE cases.
9309 EVT VT = N->getValueType(0);
9310 DebugLoc dl = N->getDebugLoc();
9311 SDValue LHS = Cmp.getOperand(0);
9312 SDValue RHS = Cmp.getOperand(1);
9313 SDValue FalseVal = N->getOperand(0);
9314 SDValue TrueVal = N->getOperand(1);
9315 SDValue ARMcc = N->getOperand(2);
9316 ARMCC::CondCodes CC =
9317 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9335 /// FIXME: Turn this into a target neutral optimization?
9337 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9338 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9339 N->getOperand(3), Cmp);
9340 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9342 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9343 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9344 N->getOperand(3), NewCmp);
9347 if (Res.getNode()) {
9348 APInt KnownZero, KnownOne;
9349 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9350 // Capture demanded bits information that would be otherwise lost.
9351 if (KnownZero == 0xfffffffe)
9352 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9353 DAG.getValueType(MVT::i1));
9354 else if (KnownZero == 0xffffff00)
9355 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9356 DAG.getValueType(MVT::i8));
9357 else if (KnownZero == 0xffff0000)
9358 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9359 DAG.getValueType(MVT::i16));
9365 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9366 DAGCombinerInfo &DCI) const {
9367 switch (N->getOpcode()) {
9369 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9370 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9371 case ISD::SUB: return PerformSUBCombine(N, DCI);
9372 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9373 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9374 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9375 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9376 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9377 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9378 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9379 case ISD::STORE: return PerformSTORECombine(N, DCI);
9380 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9381 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9382 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9383 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9384 case ISD::FP_TO_SINT:
9385 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9386 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9387 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9390 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9391 case ISD::SIGN_EXTEND:
9392 case ISD::ZERO_EXTEND:
9393 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9394 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9395 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9396 case ARMISD::VLD2DUP:
9397 case ARMISD::VLD3DUP:
9398 case ARMISD::VLD4DUP:
9399 return CombineBaseUpdate(N, DCI);
9400 case ISD::INTRINSIC_VOID:
9401 case ISD::INTRINSIC_W_CHAIN:
9402 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9403 case Intrinsic::arm_neon_vld1:
9404 case Intrinsic::arm_neon_vld2:
9405 case Intrinsic::arm_neon_vld3:
9406 case Intrinsic::arm_neon_vld4:
9407 case Intrinsic::arm_neon_vld2lane:
9408 case Intrinsic::arm_neon_vld3lane:
9409 case Intrinsic::arm_neon_vld4lane:
9410 case Intrinsic::arm_neon_vst1:
9411 case Intrinsic::arm_neon_vst2:
9412 case Intrinsic::arm_neon_vst3:
9413 case Intrinsic::arm_neon_vst4:
9414 case Intrinsic::arm_neon_vst2lane:
9415 case Intrinsic::arm_neon_vst3lane:
9416 case Intrinsic::arm_neon_vst4lane:
9417 return CombineBaseUpdate(N, DCI);
9425 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9427 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9430 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9431 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9432 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9434 switch (VT.getSimpleVT().SimpleTy) {
9440 // Unaligned access can use (for example) LRDB, LRDH, LDR
9441 if (AllowsUnaligned) {
9443 *Fast = Subtarget->hasV7Ops();
9450 // For any little-endian targets with neon, we can support unaligned ld/st
9451 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9452 // A big-endian target may also explictly support unaligned accesses
9453 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9463 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9464 unsigned AlignCheck) {
9465 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9466 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9469 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9470 unsigned DstAlign, unsigned SrcAlign,
9471 bool IsMemset, bool ZeroMemset,
9473 MachineFunction &MF) const {
9474 const Function *F = MF.getFunction();
9476 // See if we can use NEON instructions for this...
9477 if ((!IsMemset || ZeroMemset) &&
9478 Subtarget->hasNEON() &&
9479 !F->getFnAttributes().hasAttribute(Attribute::NoImplicitFloat)) {
9482 (memOpAlign(SrcAlign, DstAlign, 16) ||
9483 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9485 } else if (Size >= 8 &&
9486 (memOpAlign(SrcAlign, DstAlign, 8) ||
9487 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9492 // Lowering to i32/i16 if the size permits.
9498 // Let the target-independent logic figure it out.
9502 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9503 if (Val.getOpcode() != ISD::LOAD)
9506 EVT VT1 = Val.getValueType();
9507 if (!VT1.isSimple() || !VT1.isInteger() ||
9508 !VT2.isSimple() || !VT2.isInteger())
9511 switch (VT1.getSimpleVT().SimpleTy) {
9516 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9523 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9528 switch (VT.getSimpleVT().SimpleTy) {
9529 default: return false;
9544 if ((V & (Scale - 1)) != 0)
9547 return V == (V & ((1LL << 5) - 1));
9550 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9551 const ARMSubtarget *Subtarget) {
9558 switch (VT.getSimpleVT().SimpleTy) {
9559 default: return false;
9564 // + imm12 or - imm8
9566 return V == (V & ((1LL << 8) - 1));
9567 return V == (V & ((1LL << 12) - 1));
9570 // Same as ARM mode. FIXME: NEON?
9571 if (!Subtarget->hasVFP2())
9576 return V == (V & ((1LL << 8) - 1));
9580 /// isLegalAddressImmediate - Return true if the integer value can be used
9581 /// as the offset of the target addressing mode for load / store of the
9583 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9584 const ARMSubtarget *Subtarget) {
9591 if (Subtarget->isThumb1Only())
9592 return isLegalT1AddressImmediate(V, VT);
9593 else if (Subtarget->isThumb2())
9594 return isLegalT2AddressImmediate(V, VT, Subtarget);
9599 switch (VT.getSimpleVT().SimpleTy) {
9600 default: return false;
9605 return V == (V & ((1LL << 12) - 1));
9608 return V == (V & ((1LL << 8) - 1));
9611 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9616 return V == (V & ((1LL << 8) - 1));
9620 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9622 int Scale = AM.Scale;
9626 switch (VT.getSimpleVT().SimpleTy) {
9627 default: return false;
9636 return Scale == 2 || Scale == 4 || Scale == 8;
9639 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9643 // Note, we allow "void" uses (basically, uses that aren't loads or
9644 // stores), because arm allows folding a scale into many arithmetic
9645 // operations. This should be made more precise and revisited later.
9647 // Allow r << imm, but the imm has to be a multiple of two.
9648 if (Scale & 1) return false;
9649 return isPowerOf2_32(Scale);
9653 /// isLegalAddressingMode - Return true if the addressing mode represented
9654 /// by AM is legal for this target, for a load/store of the specified type.
9655 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9657 EVT VT = getValueType(Ty, true);
9658 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9661 // Can never fold addr of global into load/store.
9666 case 0: // no scale reg, must be "r+i" or "r", or "i".
9669 if (Subtarget->isThumb1Only())
9673 // ARM doesn't support any R+R*scale+imm addr modes.
9680 if (Subtarget->isThumb2())
9681 return isLegalT2ScaledAddressingMode(AM, VT);
9683 int Scale = AM.Scale;
9684 switch (VT.getSimpleVT().SimpleTy) {
9685 default: return false;
9689 if (Scale < 0) Scale = -Scale;
9693 return isPowerOf2_32(Scale & ~1);
9697 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9702 // Note, we allow "void" uses (basically, uses that aren't loads or
9703 // stores), because arm allows folding a scale into many arithmetic
9704 // operations. This should be made more precise and revisited later.
9706 // Allow r << imm, but the imm has to be a multiple of two.
9707 if (Scale & 1) return false;
9708 return isPowerOf2_32(Scale);
9714 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9715 /// icmp immediate, that is the target has icmp instructions which can compare
9716 /// a register against the immediate without having to materialize the
9717 /// immediate into a register.
9718 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9719 // Thumb2 and ARM modes can use cmn for negative immediates.
9720 if (!Subtarget->isThumb())
9721 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9722 if (Subtarget->isThumb2())
9723 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9724 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9725 return Imm >= 0 && Imm <= 255;
9728 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9729 /// *or sub* immediate, that is the target has add or sub instructions which can
9730 /// add a register with the immediate without having to materialize the
9731 /// immediate into a register.
9732 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9733 // Same encoding for add/sub, just flip the sign.
9734 int64_t AbsImm = llvm::abs64(Imm);
9735 if (!Subtarget->isThumb())
9736 return ARM_AM::getSOImmVal(AbsImm) != -1;
9737 if (Subtarget->isThumb2())
9738 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9739 // Thumb1 only has 8-bit unsigned immediate.
9740 return AbsImm >= 0 && AbsImm <= 255;
9743 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9744 bool isSEXTLoad, SDValue &Base,
9745 SDValue &Offset, bool &isInc,
9746 SelectionDAG &DAG) {
9747 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9750 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9752 Base = Ptr->getOperand(0);
9753 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9754 int RHSC = (int)RHS->getZExtValue();
9755 if (RHSC < 0 && RHSC > -256) {
9756 assert(Ptr->getOpcode() == ISD::ADD);
9758 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9762 isInc = (Ptr->getOpcode() == ISD::ADD);
9763 Offset = Ptr->getOperand(1);
9765 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9767 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9768 int RHSC = (int)RHS->getZExtValue();
9769 if (RHSC < 0 && RHSC > -0x1000) {
9770 assert(Ptr->getOpcode() == ISD::ADD);
9772 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9773 Base = Ptr->getOperand(0);
9778 if (Ptr->getOpcode() == ISD::ADD) {
9780 ARM_AM::ShiftOpc ShOpcVal=
9781 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9782 if (ShOpcVal != ARM_AM::no_shift) {
9783 Base = Ptr->getOperand(1);
9784 Offset = Ptr->getOperand(0);
9786 Base = Ptr->getOperand(0);
9787 Offset = Ptr->getOperand(1);
9792 isInc = (Ptr->getOpcode() == ISD::ADD);
9793 Base = Ptr->getOperand(0);
9794 Offset = Ptr->getOperand(1);
9798 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9802 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9803 bool isSEXTLoad, SDValue &Base,
9804 SDValue &Offset, bool &isInc,
9805 SelectionDAG &DAG) {
9806 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9809 Base = Ptr->getOperand(0);
9810 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9811 int RHSC = (int)RHS->getZExtValue();
9812 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9813 assert(Ptr->getOpcode() == ISD::ADD);
9815 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9817 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9818 isInc = Ptr->getOpcode() == ISD::ADD;
9819 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9827 /// getPreIndexedAddressParts - returns true by value, base pointer and
9828 /// offset pointer and addressing mode by reference if the node's address
9829 /// can be legally represented as pre-indexed load / store address.
9831 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9833 ISD::MemIndexedMode &AM,
9834 SelectionDAG &DAG) const {
9835 if (Subtarget->isThumb1Only())
9840 bool isSEXTLoad = false;
9841 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9842 Ptr = LD->getBasePtr();
9843 VT = LD->getMemoryVT();
9844 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9845 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9846 Ptr = ST->getBasePtr();
9847 VT = ST->getMemoryVT();
9852 bool isLegal = false;
9853 if (Subtarget->isThumb2())
9854 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9855 Offset, isInc, DAG);
9857 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9858 Offset, isInc, DAG);
9862 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9866 /// getPostIndexedAddressParts - returns true by value, base pointer and
9867 /// offset pointer and addressing mode by reference if this node can be
9868 /// combined with a load / store to form a post-indexed load / store.
9869 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9872 ISD::MemIndexedMode &AM,
9873 SelectionDAG &DAG) const {
9874 if (Subtarget->isThumb1Only())
9879 bool isSEXTLoad = false;
9880 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9881 VT = LD->getMemoryVT();
9882 Ptr = LD->getBasePtr();
9883 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9884 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9885 VT = ST->getMemoryVT();
9886 Ptr = ST->getBasePtr();
9891 bool isLegal = false;
9892 if (Subtarget->isThumb2())
9893 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9896 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9902 // Swap base ptr and offset to catch more post-index load / store when
9903 // it's legal. In Thumb2 mode, offset must be an immediate.
9904 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9905 !Subtarget->isThumb2())
9906 std::swap(Base, Offset);
9908 // Post-indexed load / store update the base pointer.
9913 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9917 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9920 const SelectionDAG &DAG,
9921 unsigned Depth) const {
9922 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9923 switch (Op.getOpcode()) {
9925 case ARMISD::CMOV: {
9926 // Bits are known zero/one if known on the LHS and RHS.
9927 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9928 if (KnownZero == 0 && KnownOne == 0) return;
9930 APInt KnownZeroRHS, KnownOneRHS;
9931 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9932 KnownZero &= KnownZeroRHS;
9933 KnownOne &= KnownOneRHS;
9939 //===----------------------------------------------------------------------===//
9940 // ARM Inline Assembly Support
9941 //===----------------------------------------------------------------------===//
9943 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9944 // Looking for "rev" which is V6+.
9945 if (!Subtarget->hasV6Ops())
9948 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9949 std::string AsmStr = IA->getAsmString();
9950 SmallVector<StringRef, 4> AsmPieces;
9951 SplitString(AsmStr, AsmPieces, ";\n");
9953 switch (AsmPieces.size()) {
9954 default: return false;
9956 AsmStr = AsmPieces[0];
9958 SplitString(AsmStr, AsmPieces, " \t,");
9961 if (AsmPieces.size() == 3 &&
9962 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9963 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9964 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9965 if (Ty && Ty->getBitWidth() == 32)
9966 return IntrinsicLowering::LowerToByteSwap(CI);
9974 /// getConstraintType - Given a constraint letter, return the type of
9975 /// constraint it is for this target.
9976 ARMTargetLowering::ConstraintType
9977 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9978 if (Constraint.size() == 1) {
9979 switch (Constraint[0]) {
9981 case 'l': return C_RegisterClass;
9982 case 'w': return C_RegisterClass;
9983 case 'h': return C_RegisterClass;
9984 case 'x': return C_RegisterClass;
9985 case 't': return C_RegisterClass;
9986 case 'j': return C_Other; // Constant for movw.
9987 // An address with a single base register. Due to the way we
9988 // currently handle addresses it is the same as an 'r' memory constraint.
9989 case 'Q': return C_Memory;
9991 } else if (Constraint.size() == 2) {
9992 switch (Constraint[0]) {
9994 // All 'U+' constraints are addresses.
9995 case 'U': return C_Memory;
9998 return TargetLowering::getConstraintType(Constraint);
10001 /// Examine constraint type and operand type and determine a weight value.
10002 /// This object must already have been set up with the operand type
10003 /// and the current alternative constraint selected.
10004 TargetLowering::ConstraintWeight
10005 ARMTargetLowering::getSingleConstraintMatchWeight(
10006 AsmOperandInfo &info, const char *constraint) const {
10007 ConstraintWeight weight = CW_Invalid;
10008 Value *CallOperandVal = info.CallOperandVal;
10009 // If we don't have a value, we can't do a match,
10010 // but allow it at the lowest weight.
10011 if (CallOperandVal == NULL)
10013 Type *type = CallOperandVal->getType();
10014 // Look at the constraint type.
10015 switch (*constraint) {
10017 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10020 if (type->isIntegerTy()) {
10021 if (Subtarget->isThumb())
10022 weight = CW_SpecificReg;
10024 weight = CW_Register;
10028 if (type->isFloatingPointTy())
10029 weight = CW_Register;
10035 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10037 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10039 if (Constraint.size() == 1) {
10040 // GCC ARM Constraint Letters
10041 switch (Constraint[0]) {
10042 case 'l': // Low regs or general regs.
10043 if (Subtarget->isThumb())
10044 return RCPair(0U, &ARM::tGPRRegClass);
10045 return RCPair(0U, &ARM::GPRRegClass);
10046 case 'h': // High regs or no regs.
10047 if (Subtarget->isThumb())
10048 return RCPair(0U, &ARM::hGPRRegClass);
10051 return RCPair(0U, &ARM::GPRRegClass);
10053 if (VT == MVT::f32)
10054 return RCPair(0U, &ARM::SPRRegClass);
10055 if (VT.getSizeInBits() == 64)
10056 return RCPair(0U, &ARM::DPRRegClass);
10057 if (VT.getSizeInBits() == 128)
10058 return RCPair(0U, &ARM::QPRRegClass);
10061 if (VT == MVT::f32)
10062 return RCPair(0U, &ARM::SPR_8RegClass);
10063 if (VT.getSizeInBits() == 64)
10064 return RCPair(0U, &ARM::DPR_8RegClass);
10065 if (VT.getSizeInBits() == 128)
10066 return RCPair(0U, &ARM::QPR_8RegClass);
10069 if (VT == MVT::f32)
10070 return RCPair(0U, &ARM::SPRRegClass);
10074 if (StringRef("{cc}").equals_lower(Constraint))
10075 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10077 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10080 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10081 /// vector. If it is invalid, don't add anything to Ops.
10082 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10083 std::string &Constraint,
10084 std::vector<SDValue>&Ops,
10085 SelectionDAG &DAG) const {
10086 SDValue Result(0, 0);
10088 // Currently only support length 1 constraints.
10089 if (Constraint.length() != 1) return;
10091 char ConstraintLetter = Constraint[0];
10092 switch (ConstraintLetter) {
10095 case 'I': case 'J': case 'K': case 'L':
10096 case 'M': case 'N': case 'O':
10097 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10101 int64_t CVal64 = C->getSExtValue();
10102 int CVal = (int) CVal64;
10103 // None of these constraints allow values larger than 32 bits. Check
10104 // that the value fits in an int.
10105 if (CVal != CVal64)
10108 switch (ConstraintLetter) {
10110 // Constant suitable for movw, must be between 0 and
10112 if (Subtarget->hasV6T2Ops())
10113 if (CVal >= 0 && CVal <= 65535)
10117 if (Subtarget->isThumb1Only()) {
10118 // This must be a constant between 0 and 255, for ADD
10120 if (CVal >= 0 && CVal <= 255)
10122 } else if (Subtarget->isThumb2()) {
10123 // A constant that can be used as an immediate value in a
10124 // data-processing instruction.
10125 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10128 // A constant that can be used as an immediate value in a
10129 // data-processing instruction.
10130 if (ARM_AM::getSOImmVal(CVal) != -1)
10136 if (Subtarget->isThumb()) { // FIXME thumb2
10137 // This must be a constant between -255 and -1, for negated ADD
10138 // immediates. This can be used in GCC with an "n" modifier that
10139 // prints the negated value, for use with SUB instructions. It is
10140 // not useful otherwise but is implemented for compatibility.
10141 if (CVal >= -255 && CVal <= -1)
10144 // This must be a constant between -4095 and 4095. It is not clear
10145 // what this constraint is intended for. Implemented for
10146 // compatibility with GCC.
10147 if (CVal >= -4095 && CVal <= 4095)
10153 if (Subtarget->isThumb1Only()) {
10154 // A 32-bit value where only one byte has a nonzero value. Exclude
10155 // zero to match GCC. This constraint is used by GCC internally for
10156 // constants that can be loaded with a move/shift combination.
10157 // It is not useful otherwise but is implemented for compatibility.
10158 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10160 } else if (Subtarget->isThumb2()) {
10161 // A constant whose bitwise inverse can be used as an immediate
10162 // value in a data-processing instruction. This can be used in GCC
10163 // with a "B" modifier that prints the inverted value, for use with
10164 // BIC and MVN instructions. It is not useful otherwise but is
10165 // implemented for compatibility.
10166 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10169 // A constant whose bitwise inverse can be used as an immediate
10170 // value in a data-processing instruction. This can be used in GCC
10171 // with a "B" modifier that prints the inverted value, for use with
10172 // BIC and MVN instructions. It is not useful otherwise but is
10173 // implemented for compatibility.
10174 if (ARM_AM::getSOImmVal(~CVal) != -1)
10180 if (Subtarget->isThumb1Only()) {
10181 // This must be a constant between -7 and 7,
10182 // for 3-operand ADD/SUB immediate instructions.
10183 if (CVal >= -7 && CVal < 7)
10185 } else if (Subtarget->isThumb2()) {
10186 // A constant whose negation can be used as an immediate value in a
10187 // data-processing instruction. This can be used in GCC with an "n"
10188 // modifier that prints the negated value, for use with SUB
10189 // instructions. It is not useful otherwise but is implemented for
10191 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10194 // A constant whose negation can be used as an immediate value in a
10195 // data-processing instruction. This can be used in GCC with an "n"
10196 // modifier that prints the negated value, for use with SUB
10197 // instructions. It is not useful otherwise but is implemented for
10199 if (ARM_AM::getSOImmVal(-CVal) != -1)
10205 if (Subtarget->isThumb()) { // FIXME thumb2
10206 // This must be a multiple of 4 between 0 and 1020, for
10207 // ADD sp + immediate.
10208 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10211 // A power of two or a constant between 0 and 32. This is used in
10212 // GCC for the shift amount on shifted register operands, but it is
10213 // useful in general for any shift amounts.
10214 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10220 if (Subtarget->isThumb()) { // FIXME thumb2
10221 // This must be a constant between 0 and 31, for shift amounts.
10222 if (CVal >= 0 && CVal <= 31)
10228 if (Subtarget->isThumb()) { // FIXME thumb2
10229 // This must be a multiple of 4 between -508 and 508, for
10230 // ADD/SUB sp = sp + immediate.
10231 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10236 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10240 if (Result.getNode()) {
10241 Ops.push_back(Result);
10244 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10248 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10249 // The ARM target isn't yet aware of offsets.
10253 bool ARM::isBitFieldInvertedMask(unsigned v) {
10254 if (v == 0xffffffff)
10256 // there can be 1's on either or both "outsides", all the "inside"
10257 // bits must be 0's
10258 unsigned int lsb = 0, msb = 31;
10259 while (v & (1 << msb)) --msb;
10260 while (v & (1 << lsb)) ++lsb;
10261 for (unsigned int i = lsb; i <= msb; ++i) {
10268 /// isFPImmLegal - Returns true if the target can instruction select the
10269 /// specified FP immediate natively. If false, the legalizer will
10270 /// materialize the FP immediate as a load from a constant pool.
10271 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10272 if (!Subtarget->hasVFP3())
10274 if (VT == MVT::f32)
10275 return ARM_AM::getFP32Imm(Imm) != -1;
10276 if (VT == MVT::f64)
10277 return ARM_AM::getFP64Imm(Imm) != -1;
10281 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10282 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10283 /// specified in the intrinsic calls.
10284 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10286 unsigned Intrinsic) const {
10287 switch (Intrinsic) {
10288 case Intrinsic::arm_neon_vld1:
10289 case Intrinsic::arm_neon_vld2:
10290 case Intrinsic::arm_neon_vld3:
10291 case Intrinsic::arm_neon_vld4:
10292 case Intrinsic::arm_neon_vld2lane:
10293 case Intrinsic::arm_neon_vld3lane:
10294 case Intrinsic::arm_neon_vld4lane: {
10295 Info.opc = ISD::INTRINSIC_W_CHAIN;
10296 // Conservatively set memVT to the entire set of vectors loaded.
10297 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10298 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10299 Info.ptrVal = I.getArgOperand(0);
10301 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10302 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10303 Info.vol = false; // volatile loads with NEON intrinsics not supported
10304 Info.readMem = true;
10305 Info.writeMem = false;
10308 case Intrinsic::arm_neon_vst1:
10309 case Intrinsic::arm_neon_vst2:
10310 case Intrinsic::arm_neon_vst3:
10311 case Intrinsic::arm_neon_vst4:
10312 case Intrinsic::arm_neon_vst2lane:
10313 case Intrinsic::arm_neon_vst3lane:
10314 case Intrinsic::arm_neon_vst4lane: {
10315 Info.opc = ISD::INTRINSIC_VOID;
10316 // Conservatively set memVT to the entire set of vectors stored.
10317 unsigned NumElts = 0;
10318 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10319 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10320 if (!ArgTy->isVectorTy())
10322 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10324 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10325 Info.ptrVal = I.getArgOperand(0);
10327 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10328 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10329 Info.vol = false; // volatile stores with NEON intrinsics not supported
10330 Info.readMem = false;
10331 Info.writeMem = true;
10334 case Intrinsic::arm_strexd: {
10335 Info.opc = ISD::INTRINSIC_W_CHAIN;
10336 Info.memVT = MVT::i64;
10337 Info.ptrVal = I.getArgOperand(2);
10341 Info.readMem = false;
10342 Info.writeMem = true;
10345 case Intrinsic::arm_ldrexd: {
10346 Info.opc = ISD::INTRINSIC_W_CHAIN;
10347 Info.memVT = MVT::i64;
10348 Info.ptrVal = I.getArgOperand(0);
10352 Info.readMem = true;
10353 Info.writeMem = false;
10364 ARMScalarTargetTransformImpl::getIntImmCost(const APInt &Imm, Type *Ty) const {
10365 assert(Ty->isIntegerTy());
10367 unsigned Bits = Ty->getPrimitiveSizeInBits();
10368 if (Bits == 0 || Bits > 32)
10371 int32_t SImmVal = Imm.getSExtValue();
10372 uint32_t ZImmVal = Imm.getZExtValue();
10373 if (!Subtarget->isThumb()) {
10374 if ((SImmVal >= 0 && SImmVal < 65536) ||
10375 (ARM_AM::getSOImmVal(ZImmVal) != -1) ||
10376 (ARM_AM::getSOImmVal(~ZImmVal) != -1))
10378 return Subtarget->hasV6T2Ops() ? 2 : 3;
10379 } else if (Subtarget->isThumb2()) {
10380 if ((SImmVal >= 0 && SImmVal < 65536) ||
10381 (ARM_AM::getT2SOImmVal(ZImmVal) != -1) ||
10382 (ARM_AM::getT2SOImmVal(~ZImmVal) != -1))
10384 return Subtarget->hasV6T2Ops() ? 2 : 3;
10385 } else /*Thumb1*/ {
10386 if (SImmVal >= 0 && SImmVal < 256)
10388 if ((~ZImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal))
10390 // Load from constantpool.