1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
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::FSINCOS, MVT::f64, Expand);
785 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
786 setOperationAction(ISD::FREM, MVT::f64, Expand);
787 setOperationAction(ISD::FREM, MVT::f32, Expand);
788 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
789 !Subtarget->isThumb1Only()) {
790 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
791 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
793 setOperationAction(ISD::FPOW, MVT::f64, Expand);
794 setOperationAction(ISD::FPOW, MVT::f32, Expand);
796 if (!Subtarget->hasVFP4()) {
797 setOperationAction(ISD::FMA, MVT::f64, Expand);
798 setOperationAction(ISD::FMA, MVT::f32, Expand);
801 // Various VFP goodness
802 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
803 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
804 if (Subtarget->hasVFP2()) {
805 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
806 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
807 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
808 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
810 // Special handling for half-precision FP.
811 if (!Subtarget->hasFP16()) {
812 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
813 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
817 // We have target-specific dag combine patterns for the following nodes:
818 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
819 setTargetDAGCombine(ISD::ADD);
820 setTargetDAGCombine(ISD::SUB);
821 setTargetDAGCombine(ISD::MUL);
822 setTargetDAGCombine(ISD::AND);
823 setTargetDAGCombine(ISD::OR);
824 setTargetDAGCombine(ISD::XOR);
826 if (Subtarget->hasV6Ops())
827 setTargetDAGCombine(ISD::SRL);
829 setStackPointerRegisterToSaveRestore(ARM::SP);
831 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
832 !Subtarget->hasVFP2())
833 setSchedulingPreference(Sched::RegPressure);
835 setSchedulingPreference(Sched::Hybrid);
837 //// temporary - rewrite interface to use type
838 maxStoresPerMemset = 8;
839 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
840 maxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
841 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
842 maxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
843 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
845 // On ARM arguments smaller than 4 bytes are extended, so all arguments
846 // are at least 4 bytes aligned.
847 setMinStackArgumentAlignment(4);
849 benefitFromCodePlacementOpt = true;
851 // Prefer likely predicted branches to selects on out-of-order cores.
852 predictableSelectIsExpensive = Subtarget->isLikeA9();
854 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
857 // FIXME: It might make sense to define the representative register class as the
858 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
859 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
860 // SPR's representative would be DPR_VFP2. This should work well if register
861 // pressure tracking were modified such that a register use would increment the
862 // pressure of the register class's representative and all of it's super
863 // classes' representatives transitively. We have not implemented this because
864 // of the difficulty prior to coalescing of modeling operand register classes
865 // due to the common occurrence of cross class copies and subregister insertions
867 std::pair<const TargetRegisterClass*, uint8_t>
868 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
869 const TargetRegisterClass *RRC = 0;
871 switch (VT.SimpleTy) {
873 return TargetLowering::findRepresentativeClass(VT);
874 // Use DPR as representative register class for all floating point
875 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
876 // the cost is 1 for both f32 and f64.
877 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
878 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
879 RRC = &ARM::DPRRegClass;
880 // When NEON is used for SP, only half of the register file is available
881 // because operations that define both SP and DP results will be constrained
882 // to the VFP2 class (D0-D15). We currently model this constraint prior to
883 // coalescing by double-counting the SP regs. See the FIXME above.
884 if (Subtarget->useNEONForSinglePrecisionFP())
887 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
888 case MVT::v4f32: case MVT::v2f64:
889 RRC = &ARM::DPRRegClass;
893 RRC = &ARM::DPRRegClass;
897 RRC = &ARM::DPRRegClass;
901 return std::make_pair(RRC, Cost);
904 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
907 case ARMISD::Wrapper: return "ARMISD::Wrapper";
908 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
909 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
910 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
911 case ARMISD::CALL: return "ARMISD::CALL";
912 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
913 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
914 case ARMISD::tCALL: return "ARMISD::tCALL";
915 case ARMISD::BRCOND: return "ARMISD::BRCOND";
916 case ARMISD::BR_JT: return "ARMISD::BR_JT";
917 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
918 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
919 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
920 case ARMISD::CMP: return "ARMISD::CMP";
921 case ARMISD::CMN: return "ARMISD::CMN";
922 case ARMISD::CMPZ: return "ARMISD::CMPZ";
923 case ARMISD::CMPFP: return "ARMISD::CMPFP";
924 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
925 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
926 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
928 case ARMISD::CMOV: return "ARMISD::CMOV";
930 case ARMISD::RBIT: return "ARMISD::RBIT";
932 case ARMISD::FTOSI: return "ARMISD::FTOSI";
933 case ARMISD::FTOUI: return "ARMISD::FTOUI";
934 case ARMISD::SITOF: return "ARMISD::SITOF";
935 case ARMISD::UITOF: return "ARMISD::UITOF";
937 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
938 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
939 case ARMISD::RRX: return "ARMISD::RRX";
941 case ARMISD::ADDC: return "ARMISD::ADDC";
942 case ARMISD::ADDE: return "ARMISD::ADDE";
943 case ARMISD::SUBC: return "ARMISD::SUBC";
944 case ARMISD::SUBE: return "ARMISD::SUBE";
946 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
947 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
949 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
950 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
952 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
954 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
956 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
958 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
959 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
961 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
963 case ARMISD::VCEQ: return "ARMISD::VCEQ";
964 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
965 case ARMISD::VCGE: return "ARMISD::VCGE";
966 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
967 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
968 case ARMISD::VCGEU: return "ARMISD::VCGEU";
969 case ARMISD::VCGT: return "ARMISD::VCGT";
970 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
971 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
972 case ARMISD::VCGTU: return "ARMISD::VCGTU";
973 case ARMISD::VTST: return "ARMISD::VTST";
975 case ARMISD::VSHL: return "ARMISD::VSHL";
976 case ARMISD::VSHRs: return "ARMISD::VSHRs";
977 case ARMISD::VSHRu: return "ARMISD::VSHRu";
978 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
979 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
980 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
981 case ARMISD::VSHRN: return "ARMISD::VSHRN";
982 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
983 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
984 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
985 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
986 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
987 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
988 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
989 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
990 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
991 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
992 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
993 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
994 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
995 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
996 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
997 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
998 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
999 case ARMISD::VDUP: return "ARMISD::VDUP";
1000 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1001 case ARMISD::VEXT: return "ARMISD::VEXT";
1002 case ARMISD::VREV64: return "ARMISD::VREV64";
1003 case ARMISD::VREV32: return "ARMISD::VREV32";
1004 case ARMISD::VREV16: return "ARMISD::VREV16";
1005 case ARMISD::VZIP: return "ARMISD::VZIP";
1006 case ARMISD::VUZP: return "ARMISD::VUZP";
1007 case ARMISD::VTRN: return "ARMISD::VTRN";
1008 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1009 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1010 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1011 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1012 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1013 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1014 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1015 case ARMISD::FMAX: return "ARMISD::FMAX";
1016 case ARMISD::FMIN: return "ARMISD::FMIN";
1017 case ARMISD::BFI: return "ARMISD::BFI";
1018 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1019 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1020 case ARMISD::VBSL: return "ARMISD::VBSL";
1021 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1022 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1023 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1024 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1025 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1026 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1027 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1028 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1029 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1030 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1031 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1032 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1033 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1034 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1035 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1036 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1037 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1038 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1039 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1040 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1044 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1045 if (!VT.isVector()) return getPointerTy();
1046 return VT.changeVectorElementTypeToInteger();
1049 /// getRegClassFor - Return the register class that should be used for the
1050 /// specified value type.
1051 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1052 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1053 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1054 // load / store 4 to 8 consecutive D registers.
1055 if (Subtarget->hasNEON()) {
1056 if (VT == MVT::v4i64)
1057 return &ARM::QQPRRegClass;
1058 if (VT == MVT::v8i64)
1059 return &ARM::QQQQPRRegClass;
1061 return TargetLowering::getRegClassFor(VT);
1064 // Create a fast isel object.
1066 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1067 const TargetLibraryInfo *libInfo) const {
1068 return ARM::createFastISel(funcInfo, libInfo);
1071 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1072 /// be used for loads / stores from the global.
1073 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1074 return (Subtarget->isThumb1Only() ? 127 : 4095);
1077 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1078 unsigned NumVals = N->getNumValues();
1080 return Sched::RegPressure;
1082 for (unsigned i = 0; i != NumVals; ++i) {
1083 EVT VT = N->getValueType(i);
1084 if (VT == MVT::Glue || VT == MVT::Other)
1086 if (VT.isFloatingPoint() || VT.isVector())
1090 if (!N->isMachineOpcode())
1091 return Sched::RegPressure;
1093 // Load are scheduled for latency even if there instruction itinerary
1094 // is not available.
1095 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1096 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1098 if (MCID.getNumDefs() == 0)
1099 return Sched::RegPressure;
1100 if (!Itins->isEmpty() &&
1101 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1104 return Sched::RegPressure;
1107 //===----------------------------------------------------------------------===//
1109 //===----------------------------------------------------------------------===//
1111 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1112 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1114 default: llvm_unreachable("Unknown condition code!");
1115 case ISD::SETNE: return ARMCC::NE;
1116 case ISD::SETEQ: return ARMCC::EQ;
1117 case ISD::SETGT: return ARMCC::GT;
1118 case ISD::SETGE: return ARMCC::GE;
1119 case ISD::SETLT: return ARMCC::LT;
1120 case ISD::SETLE: return ARMCC::LE;
1121 case ISD::SETUGT: return ARMCC::HI;
1122 case ISD::SETUGE: return ARMCC::HS;
1123 case ISD::SETULT: return ARMCC::LO;
1124 case ISD::SETULE: return ARMCC::LS;
1128 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1129 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1130 ARMCC::CondCodes &CondCode2) {
1131 CondCode2 = ARMCC::AL;
1133 default: llvm_unreachable("Unknown FP condition!");
1135 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1137 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1139 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1140 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1141 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1142 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1143 case ISD::SETO: CondCode = ARMCC::VC; break;
1144 case ISD::SETUO: CondCode = ARMCC::VS; break;
1145 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1146 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1147 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1149 case ISD::SETULT: CondCode = ARMCC::LT; break;
1151 case ISD::SETULE: CondCode = ARMCC::LE; break;
1153 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1157 //===----------------------------------------------------------------------===//
1158 // Calling Convention Implementation
1159 //===----------------------------------------------------------------------===//
1161 #include "ARMGenCallingConv.inc"
1163 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1164 /// given CallingConvention value.
1165 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1167 bool isVarArg) const {
1170 llvm_unreachable("Unsupported calling convention");
1171 case CallingConv::Fast:
1172 if (Subtarget->hasVFP2() && !isVarArg) {
1173 if (!Subtarget->isAAPCS_ABI())
1174 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1175 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1176 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1179 case CallingConv::C: {
1180 // Use target triple & subtarget features to do actual dispatch.
1181 if (!Subtarget->isAAPCS_ABI())
1182 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1183 else if (Subtarget->hasVFP2() &&
1184 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1186 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1187 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1189 case CallingConv::ARM_AAPCS_VFP:
1191 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1193 case CallingConv::ARM_AAPCS:
1194 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1195 case CallingConv::ARM_APCS:
1196 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1197 case CallingConv::GHC:
1198 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1202 /// LowerCallResult - Lower the result values of a call into the
1203 /// appropriate copies out of appropriate physical registers.
1205 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1206 CallingConv::ID CallConv, bool isVarArg,
1207 const SmallVectorImpl<ISD::InputArg> &Ins,
1208 DebugLoc dl, SelectionDAG &DAG,
1209 SmallVectorImpl<SDValue> &InVals) const {
1211 // Assign locations to each value returned by this call.
1212 SmallVector<CCValAssign, 16> RVLocs;
1213 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1214 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1215 CCInfo.AnalyzeCallResult(Ins,
1216 CCAssignFnForNode(CallConv, /* Return*/ true,
1219 // Copy all of the result registers out of their specified physreg.
1220 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1221 CCValAssign VA = RVLocs[i];
1224 if (VA.needsCustom()) {
1225 // Handle f64 or half of a v2f64.
1226 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1228 Chain = Lo.getValue(1);
1229 InFlag = Lo.getValue(2);
1230 VA = RVLocs[++i]; // skip ahead to next loc
1231 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1233 Chain = Hi.getValue(1);
1234 InFlag = Hi.getValue(2);
1235 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1237 if (VA.getLocVT() == MVT::v2f64) {
1238 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1239 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1240 DAG.getConstant(0, MVT::i32));
1242 VA = RVLocs[++i]; // skip ahead to next loc
1243 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1244 Chain = Lo.getValue(1);
1245 InFlag = Lo.getValue(2);
1246 VA = RVLocs[++i]; // skip ahead to next loc
1247 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1248 Chain = Hi.getValue(1);
1249 InFlag = Hi.getValue(2);
1250 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1251 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1252 DAG.getConstant(1, MVT::i32));
1255 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1257 Chain = Val.getValue(1);
1258 InFlag = Val.getValue(2);
1261 switch (VA.getLocInfo()) {
1262 default: llvm_unreachable("Unknown loc info!");
1263 case CCValAssign::Full: break;
1264 case CCValAssign::BCvt:
1265 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1269 InVals.push_back(Val);
1275 /// LowerMemOpCallTo - Store the argument to the stack.
1277 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1278 SDValue StackPtr, SDValue Arg,
1279 DebugLoc dl, SelectionDAG &DAG,
1280 const CCValAssign &VA,
1281 ISD::ArgFlagsTy Flags) const {
1282 unsigned LocMemOffset = VA.getLocMemOffset();
1283 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1284 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1285 return DAG.getStore(Chain, dl, Arg, PtrOff,
1286 MachinePointerInfo::getStack(LocMemOffset),
1290 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1291 SDValue Chain, SDValue &Arg,
1292 RegsToPassVector &RegsToPass,
1293 CCValAssign &VA, CCValAssign &NextVA,
1295 SmallVector<SDValue, 8> &MemOpChains,
1296 ISD::ArgFlagsTy Flags) const {
1298 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1299 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1300 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1302 if (NextVA.isRegLoc())
1303 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1305 assert(NextVA.isMemLoc());
1306 if (StackPtr.getNode() == 0)
1307 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1309 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1315 /// LowerCall - Lowering a call into a callseq_start <-
1316 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1319 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1320 SmallVectorImpl<SDValue> &InVals) const {
1321 SelectionDAG &DAG = CLI.DAG;
1322 DebugLoc &dl = CLI.DL;
1323 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1324 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1325 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1326 SDValue Chain = CLI.Chain;
1327 SDValue Callee = CLI.Callee;
1328 bool &isTailCall = CLI.IsTailCall;
1329 CallingConv::ID CallConv = CLI.CallConv;
1330 bool doesNotRet = CLI.DoesNotReturn;
1331 bool isVarArg = CLI.IsVarArg;
1333 MachineFunction &MF = DAG.getMachineFunction();
1334 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1335 bool IsSibCall = false;
1336 // Disable tail calls if they're not supported.
1337 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1340 // Check if it's really possible to do a tail call.
1341 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1342 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1343 Outs, OutVals, Ins, DAG);
1344 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1345 // detected sibcalls.
1352 // Analyze operands of the call, assigning locations to each operand.
1353 SmallVector<CCValAssign, 16> ArgLocs;
1354 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1355 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1356 CCInfo.AnalyzeCallOperands(Outs,
1357 CCAssignFnForNode(CallConv, /* Return*/ false,
1360 // Get a count of how many bytes are to be pushed on the stack.
1361 unsigned NumBytes = CCInfo.getNextStackOffset();
1363 // For tail calls, memory operands are available in our caller's stack.
1367 // Adjust the stack pointer for the new arguments...
1368 // These operations are automatically eliminated by the prolog/epilog pass
1370 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1372 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1374 RegsToPassVector RegsToPass;
1375 SmallVector<SDValue, 8> MemOpChains;
1377 // Walk the register/memloc assignments, inserting copies/loads. In the case
1378 // of tail call optimization, arguments are handled later.
1379 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1381 ++i, ++realArgIdx) {
1382 CCValAssign &VA = ArgLocs[i];
1383 SDValue Arg = OutVals[realArgIdx];
1384 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1385 bool isByVal = Flags.isByVal();
1387 // Promote the value if needed.
1388 switch (VA.getLocInfo()) {
1389 default: llvm_unreachable("Unknown loc info!");
1390 case CCValAssign::Full: break;
1391 case CCValAssign::SExt:
1392 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1394 case CCValAssign::ZExt:
1395 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1397 case CCValAssign::AExt:
1398 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1400 case CCValAssign::BCvt:
1401 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1405 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1406 if (VA.needsCustom()) {
1407 if (VA.getLocVT() == MVT::v2f64) {
1408 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1409 DAG.getConstant(0, MVT::i32));
1410 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1411 DAG.getConstant(1, MVT::i32));
1413 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1414 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1416 VA = ArgLocs[++i]; // skip ahead to next loc
1417 if (VA.isRegLoc()) {
1418 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1419 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1421 assert(VA.isMemLoc());
1423 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1424 dl, DAG, VA, Flags));
1427 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1428 StackPtr, MemOpChains, Flags);
1430 } else if (VA.isRegLoc()) {
1431 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1432 } else if (isByVal) {
1433 assert(VA.isMemLoc());
1434 unsigned offset = 0;
1436 // True if this byval aggregate will be split between registers
1438 if (CCInfo.isFirstByValRegValid()) {
1439 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1441 for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1442 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1443 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1444 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1445 MachinePointerInfo(),
1446 false, false, false, 0);
1447 MemOpChains.push_back(Load.getValue(1));
1448 RegsToPass.push_back(std::make_pair(j, Load));
1450 offset = ARM::R4 - CCInfo.getFirstByValReg();
1451 CCInfo.clearFirstByValReg();
1454 if (Flags.getByValSize() - 4*offset > 0) {
1455 unsigned LocMemOffset = VA.getLocMemOffset();
1456 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1457 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1459 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1460 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1461 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1463 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1465 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1466 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1467 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1468 Ops, array_lengthof(Ops)));
1470 } else if (!IsSibCall) {
1471 assert(VA.isMemLoc());
1473 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1474 dl, DAG, VA, Flags));
1478 if (!MemOpChains.empty())
1479 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1480 &MemOpChains[0], MemOpChains.size());
1482 // Build a sequence of copy-to-reg nodes chained together with token chain
1483 // and flag operands which copy the outgoing args into the appropriate regs.
1485 // Tail call byval lowering might overwrite argument registers so in case of
1486 // tail call optimization the copies to registers are lowered later.
1488 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1489 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1490 RegsToPass[i].second, InFlag);
1491 InFlag = Chain.getValue(1);
1494 // For tail calls lower the arguments to the 'real' stack slot.
1496 // Force all the incoming stack arguments to be loaded from the stack
1497 // before any new outgoing arguments are stored to the stack, because the
1498 // outgoing stack slots may alias the incoming argument stack slots, and
1499 // the alias isn't otherwise explicit. This is slightly more conservative
1500 // than necessary, because it means that each store effectively depends
1501 // on every argument instead of just those arguments it would clobber.
1503 // Do not flag preceding copytoreg stuff together with the following stuff.
1505 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1506 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1507 RegsToPass[i].second, InFlag);
1508 InFlag = Chain.getValue(1);
1513 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1514 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1515 // node so that legalize doesn't hack it.
1516 bool isDirect = false;
1517 bool isARMFunc = false;
1518 bool isLocalARMFunc = false;
1519 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1521 if (EnableARMLongCalls) {
1522 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1523 && "long-calls with non-static relocation model!");
1524 // Handle a global address or an external symbol. If it's not one of
1525 // those, the target's already in a register, so we don't need to do
1527 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1528 const GlobalValue *GV = G->getGlobal();
1529 // Create a constant pool entry for the callee address
1530 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1531 ARMConstantPoolValue *CPV =
1532 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1534 // Get the address of the callee into a register
1535 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1536 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1537 Callee = DAG.getLoad(getPointerTy(), dl,
1538 DAG.getEntryNode(), CPAddr,
1539 MachinePointerInfo::getConstantPool(),
1540 false, false, false, 0);
1541 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1542 const char *Sym = S->getSymbol();
1544 // Create a constant pool entry for the callee address
1545 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1546 ARMConstantPoolValue *CPV =
1547 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1548 ARMPCLabelIndex, 0);
1549 // Get the address of the callee into a register
1550 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1551 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1552 Callee = DAG.getLoad(getPointerTy(), dl,
1553 DAG.getEntryNode(), CPAddr,
1554 MachinePointerInfo::getConstantPool(),
1555 false, false, false, 0);
1557 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1558 const GlobalValue *GV = G->getGlobal();
1560 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1561 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1562 getTargetMachine().getRelocationModel() != Reloc::Static;
1563 isARMFunc = !Subtarget->isThumb() || isStub;
1564 // ARM call to a local ARM function is predicable.
1565 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1566 // tBX takes a register source operand.
1567 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1568 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1569 ARMConstantPoolValue *CPV =
1570 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1571 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1572 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1573 Callee = DAG.getLoad(getPointerTy(), dl,
1574 DAG.getEntryNode(), CPAddr,
1575 MachinePointerInfo::getConstantPool(),
1576 false, false, false, 0);
1577 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1578 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1579 getPointerTy(), Callee, PICLabel);
1581 // On ELF targets for PIC code, direct calls should go through the PLT
1582 unsigned OpFlags = 0;
1583 if (Subtarget->isTargetELF() &&
1584 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1585 OpFlags = ARMII::MO_PLT;
1586 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1588 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1590 bool isStub = Subtarget->isTargetDarwin() &&
1591 getTargetMachine().getRelocationModel() != Reloc::Static;
1592 isARMFunc = !Subtarget->isThumb() || isStub;
1593 // tBX takes a register source operand.
1594 const char *Sym = S->getSymbol();
1595 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1596 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1597 ARMConstantPoolValue *CPV =
1598 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1599 ARMPCLabelIndex, 4);
1600 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1601 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1602 Callee = DAG.getLoad(getPointerTy(), dl,
1603 DAG.getEntryNode(), CPAddr,
1604 MachinePointerInfo::getConstantPool(),
1605 false, false, false, 0);
1606 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1607 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1608 getPointerTy(), Callee, PICLabel);
1610 unsigned OpFlags = 0;
1611 // On ELF targets for PIC code, direct calls should go through the PLT
1612 if (Subtarget->isTargetELF() &&
1613 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1614 OpFlags = ARMII::MO_PLT;
1615 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1619 // FIXME: handle tail calls differently.
1621 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1622 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1623 if (Subtarget->isThumb()) {
1624 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1625 CallOpc = ARMISD::CALL_NOLINK;
1627 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1629 if (!isDirect && !Subtarget->hasV5TOps())
1630 CallOpc = ARMISD::CALL_NOLINK;
1631 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1632 // Emit regular call when code size is the priority
1634 // "mov lr, pc; b _foo" to avoid confusing the RSP
1635 CallOpc = ARMISD::CALL_NOLINK;
1637 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1640 std::vector<SDValue> Ops;
1641 Ops.push_back(Chain);
1642 Ops.push_back(Callee);
1644 // Add argument registers to the end of the list so that they are known live
1646 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1647 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1648 RegsToPass[i].second.getValueType()));
1650 // Add a register mask operand representing the call-preserved registers.
1651 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1652 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1653 assert(Mask && "Missing call preserved mask for calling convention");
1654 Ops.push_back(DAG.getRegisterMask(Mask));
1656 if (InFlag.getNode())
1657 Ops.push_back(InFlag);
1659 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1661 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1663 // Returns a chain and a flag for retval copy to use.
1664 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1665 InFlag = Chain.getValue(1);
1667 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1668 DAG.getIntPtrConstant(0, true), InFlag);
1670 InFlag = Chain.getValue(1);
1672 // Handle result values, copying them out of physregs into vregs that we
1674 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1678 /// HandleByVal - Every parameter *after* a byval parameter is passed
1679 /// on the stack. Remember the next parameter register to allocate,
1680 /// and then confiscate the rest of the parameter registers to insure
1683 ARMTargetLowering::HandleByVal(
1684 CCState *State, unsigned &size, unsigned Align) const {
1685 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1686 assert((State->getCallOrPrologue() == Prologue ||
1687 State->getCallOrPrologue() == Call) &&
1688 "unhandled ParmContext");
1689 if ((!State->isFirstByValRegValid()) &&
1690 (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1691 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1692 unsigned AlignInRegs = Align / 4;
1693 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1694 for (unsigned i = 0; i < Waste; ++i)
1695 reg = State->AllocateReg(GPRArgRegs, 4);
1698 State->setFirstByValReg(reg);
1699 // At a call site, a byval parameter that is split between
1700 // registers and memory needs its size truncated here. In a
1701 // function prologue, such byval parameters are reassembled in
1702 // memory, and are not truncated.
1703 if (State->getCallOrPrologue() == Call) {
1704 unsigned excess = 4 * (ARM::R4 - reg);
1705 assert(size >= excess && "expected larger existing stack allocation");
1710 // Confiscate any remaining parameter registers to preclude their
1711 // assignment to subsequent parameters.
1712 while (State->AllocateReg(GPRArgRegs, 4))
1716 /// MatchingStackOffset - Return true if the given stack call argument is
1717 /// already available in the same position (relatively) of the caller's
1718 /// incoming argument stack.
1720 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1721 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1722 const TargetInstrInfo *TII) {
1723 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1725 if (Arg.getOpcode() == ISD::CopyFromReg) {
1726 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1727 if (!TargetRegisterInfo::isVirtualRegister(VR))
1729 MachineInstr *Def = MRI->getVRegDef(VR);
1732 if (!Flags.isByVal()) {
1733 if (!TII->isLoadFromStackSlot(Def, FI))
1738 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1739 if (Flags.isByVal())
1740 // ByVal argument is passed in as a pointer but it's now being
1741 // dereferenced. e.g.
1742 // define @foo(%struct.X* %A) {
1743 // tail call @bar(%struct.X* byval %A)
1746 SDValue Ptr = Ld->getBasePtr();
1747 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1750 FI = FINode->getIndex();
1754 assert(FI != INT_MAX);
1755 if (!MFI->isFixedObjectIndex(FI))
1757 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1760 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1761 /// for tail call optimization. Targets which want to do tail call
1762 /// optimization should implement this function.
1764 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1765 CallingConv::ID CalleeCC,
1767 bool isCalleeStructRet,
1768 bool isCallerStructRet,
1769 const SmallVectorImpl<ISD::OutputArg> &Outs,
1770 const SmallVectorImpl<SDValue> &OutVals,
1771 const SmallVectorImpl<ISD::InputArg> &Ins,
1772 SelectionDAG& DAG) const {
1773 const Function *CallerF = DAG.getMachineFunction().getFunction();
1774 CallingConv::ID CallerCC = CallerF->getCallingConv();
1775 bool CCMatch = CallerCC == CalleeCC;
1777 // Look for obvious safe cases to perform tail call optimization that do not
1778 // require ABI changes. This is what gcc calls sibcall.
1780 // Do not sibcall optimize vararg calls unless the call site is not passing
1782 if (isVarArg && !Outs.empty())
1785 // Also avoid sibcall optimization if either caller or callee uses struct
1786 // return semantics.
1787 if (isCalleeStructRet || isCallerStructRet)
1790 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1791 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1792 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1793 // support in the assembler and linker to be used. This would need to be
1794 // fixed to fully support tail calls in Thumb1.
1796 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1797 // LR. This means if we need to reload LR, it takes an extra instructions,
1798 // which outweighs the value of the tail call; but here we don't know yet
1799 // whether LR is going to be used. Probably the right approach is to
1800 // generate the tail call here and turn it back into CALL/RET in
1801 // emitEpilogue if LR is used.
1803 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1804 // but we need to make sure there are enough registers; the only valid
1805 // registers are the 4 used for parameters. We don't currently do this
1807 if (Subtarget->isThumb1Only())
1810 // If the calling conventions do not match, then we'd better make sure the
1811 // results are returned in the same way as what the caller expects.
1813 SmallVector<CCValAssign, 16> RVLocs1;
1814 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1815 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1816 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1818 SmallVector<CCValAssign, 16> RVLocs2;
1819 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1820 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1821 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1823 if (RVLocs1.size() != RVLocs2.size())
1825 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1826 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1828 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1830 if (RVLocs1[i].isRegLoc()) {
1831 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1834 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1840 // If Caller's vararg or byval argument has been split between registers and
1841 // stack, do not perform tail call, since part of the argument is in caller's
1843 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1844 getInfo<ARMFunctionInfo>();
1845 if (AFI_Caller->getVarArgsRegSaveSize())
1848 // If the callee takes no arguments then go on to check the results of the
1850 if (!Outs.empty()) {
1851 // Check if stack adjustment is needed. For now, do not do this if any
1852 // argument is passed on the stack.
1853 SmallVector<CCValAssign, 16> ArgLocs;
1854 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1855 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1856 CCInfo.AnalyzeCallOperands(Outs,
1857 CCAssignFnForNode(CalleeCC, false, isVarArg));
1858 if (CCInfo.getNextStackOffset()) {
1859 MachineFunction &MF = DAG.getMachineFunction();
1861 // Check if the arguments are already laid out in the right way as
1862 // the caller's fixed stack objects.
1863 MachineFrameInfo *MFI = MF.getFrameInfo();
1864 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1865 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1866 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1868 ++i, ++realArgIdx) {
1869 CCValAssign &VA = ArgLocs[i];
1870 EVT RegVT = VA.getLocVT();
1871 SDValue Arg = OutVals[realArgIdx];
1872 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1873 if (VA.getLocInfo() == CCValAssign::Indirect)
1875 if (VA.needsCustom()) {
1876 // f64 and vector types are split into multiple registers or
1877 // register/stack-slot combinations. The types will not match
1878 // the registers; give up on memory f64 refs until we figure
1879 // out what to do about this.
1882 if (!ArgLocs[++i].isRegLoc())
1884 if (RegVT == MVT::v2f64) {
1885 if (!ArgLocs[++i].isRegLoc())
1887 if (!ArgLocs[++i].isRegLoc())
1890 } else if (!VA.isRegLoc()) {
1891 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1903 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1904 MachineFunction &MF, bool isVarArg,
1905 const SmallVectorImpl<ISD::OutputArg> &Outs,
1906 LLVMContext &Context) const {
1907 SmallVector<CCValAssign, 16> RVLocs;
1908 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1909 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
1914 ARMTargetLowering::LowerReturn(SDValue Chain,
1915 CallingConv::ID CallConv, bool isVarArg,
1916 const SmallVectorImpl<ISD::OutputArg> &Outs,
1917 const SmallVectorImpl<SDValue> &OutVals,
1918 DebugLoc dl, SelectionDAG &DAG) const {
1920 // CCValAssign - represent the assignment of the return value to a location.
1921 SmallVector<CCValAssign, 16> RVLocs;
1923 // CCState - Info about the registers and stack slots.
1924 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1925 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1927 // Analyze outgoing return values.
1928 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1931 // If this is the first return lowered for this function, add
1932 // the regs to the liveout set for the function.
1933 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1934 for (unsigned i = 0; i != RVLocs.size(); ++i)
1935 if (RVLocs[i].isRegLoc())
1936 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1941 // Copy the result values into the output registers.
1942 for (unsigned i = 0, realRVLocIdx = 0;
1944 ++i, ++realRVLocIdx) {
1945 CCValAssign &VA = RVLocs[i];
1946 assert(VA.isRegLoc() && "Can only return in registers!");
1948 SDValue Arg = OutVals[realRVLocIdx];
1950 switch (VA.getLocInfo()) {
1951 default: llvm_unreachable("Unknown loc info!");
1952 case CCValAssign::Full: break;
1953 case CCValAssign::BCvt:
1954 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1958 if (VA.needsCustom()) {
1959 if (VA.getLocVT() == MVT::v2f64) {
1960 // Extract the first half and return it in two registers.
1961 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1962 DAG.getConstant(0, MVT::i32));
1963 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1964 DAG.getVTList(MVT::i32, MVT::i32), Half);
1966 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1967 Flag = Chain.getValue(1);
1968 VA = RVLocs[++i]; // skip ahead to next loc
1969 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1970 HalfGPRs.getValue(1), Flag);
1971 Flag = Chain.getValue(1);
1972 VA = RVLocs[++i]; // skip ahead to next loc
1974 // Extract the 2nd half and fall through to handle it as an f64 value.
1975 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1976 DAG.getConstant(1, MVT::i32));
1978 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1980 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1981 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1982 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1983 Flag = Chain.getValue(1);
1984 VA = RVLocs[++i]; // skip ahead to next loc
1985 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1988 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1990 // Guarantee that all emitted copies are
1991 // stuck together, avoiding something bad.
1992 Flag = Chain.getValue(1);
1997 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1999 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
2004 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2005 if (N->getNumValues() != 1)
2007 if (!N->hasNUsesOfValue(1, 0))
2010 SDValue TCChain = Chain;
2011 SDNode *Copy = *N->use_begin();
2012 if (Copy->getOpcode() == ISD::CopyToReg) {
2013 // If the copy has a glue operand, we conservatively assume it isn't safe to
2014 // perform a tail call.
2015 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2017 TCChain = Copy->getOperand(0);
2018 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2019 SDNode *VMov = Copy;
2020 // f64 returned in a pair of GPRs.
2021 SmallPtrSet<SDNode*, 2> Copies;
2022 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2024 if (UI->getOpcode() != ISD::CopyToReg)
2028 if (Copies.size() > 2)
2031 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2033 SDValue UseChain = UI->getOperand(0);
2034 if (Copies.count(UseChain.getNode()))
2041 } else if (Copy->getOpcode() == ISD::BITCAST) {
2042 // f32 returned in a single GPR.
2043 if (!Copy->hasOneUse())
2045 Copy = *Copy->use_begin();
2046 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2048 Chain = Copy->getOperand(0);
2053 bool HasRet = false;
2054 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2056 if (UI->getOpcode() != ARMISD::RET_FLAG)
2068 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2069 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2072 if (!CI->isTailCall())
2075 return !Subtarget->isThumb1Only();
2078 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2079 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2080 // one of the above mentioned nodes. It has to be wrapped because otherwise
2081 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2082 // be used to form addressing mode. These wrapped nodes will be selected
2084 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2085 EVT PtrVT = Op.getValueType();
2086 // FIXME there is no actual debug info here
2087 DebugLoc dl = Op.getDebugLoc();
2088 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2090 if (CP->isMachineConstantPoolEntry())
2091 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2092 CP->getAlignment());
2094 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2095 CP->getAlignment());
2096 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2099 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2100 return MachineJumpTableInfo::EK_Inline;
2103 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2104 SelectionDAG &DAG) const {
2105 MachineFunction &MF = DAG.getMachineFunction();
2106 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2107 unsigned ARMPCLabelIndex = 0;
2108 DebugLoc DL = Op.getDebugLoc();
2109 EVT PtrVT = getPointerTy();
2110 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2111 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2113 if (RelocM == Reloc::Static) {
2114 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2116 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2117 ARMPCLabelIndex = AFI->createPICLabelUId();
2118 ARMConstantPoolValue *CPV =
2119 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2120 ARMCP::CPBlockAddress, PCAdj);
2121 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2123 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2124 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2125 MachinePointerInfo::getConstantPool(),
2126 false, false, false, 0);
2127 if (RelocM == Reloc::Static)
2129 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2130 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2133 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2135 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2136 SelectionDAG &DAG) const {
2137 DebugLoc dl = GA->getDebugLoc();
2138 EVT PtrVT = getPointerTy();
2139 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2140 MachineFunction &MF = DAG.getMachineFunction();
2141 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2142 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2143 ARMConstantPoolValue *CPV =
2144 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2145 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2146 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2147 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2148 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2149 MachinePointerInfo::getConstantPool(),
2150 false, false, false, 0);
2151 SDValue Chain = Argument.getValue(1);
2153 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2154 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2156 // call __tls_get_addr.
2159 Entry.Node = Argument;
2160 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2161 Args.push_back(Entry);
2162 // FIXME: is there useful debug info available here?
2163 TargetLowering::CallLoweringInfo CLI(Chain,
2164 (Type *) Type::getInt32Ty(*DAG.getContext()),
2165 false, false, false, false,
2166 0, CallingConv::C, /*isTailCall=*/false,
2167 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2168 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2169 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2170 return CallResult.first;
2173 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2174 // "local exec" model.
2176 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2178 TLSModel::Model model) const {
2179 const GlobalValue *GV = GA->getGlobal();
2180 DebugLoc dl = GA->getDebugLoc();
2182 SDValue Chain = DAG.getEntryNode();
2183 EVT PtrVT = getPointerTy();
2184 // Get the Thread Pointer
2185 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2187 if (model == TLSModel::InitialExec) {
2188 MachineFunction &MF = DAG.getMachineFunction();
2189 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2190 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2191 // Initial exec model.
2192 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2193 ARMConstantPoolValue *CPV =
2194 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2195 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2197 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2198 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2199 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2200 MachinePointerInfo::getConstantPool(),
2201 false, false, false, 0);
2202 Chain = Offset.getValue(1);
2204 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2205 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2207 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2208 MachinePointerInfo::getConstantPool(),
2209 false, false, false, 0);
2212 assert(model == TLSModel::LocalExec);
2213 ARMConstantPoolValue *CPV =
2214 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2215 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2216 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2217 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2218 MachinePointerInfo::getConstantPool(),
2219 false, false, false, 0);
2222 // The address of the thread local variable is the add of the thread
2223 // pointer with the offset of the variable.
2224 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2228 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2229 // TODO: implement the "local dynamic" model
2230 assert(Subtarget->isTargetELF() &&
2231 "TLS not implemented for non-ELF targets");
2232 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2234 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2237 case TLSModel::GeneralDynamic:
2238 case TLSModel::LocalDynamic:
2239 return LowerToTLSGeneralDynamicModel(GA, DAG);
2240 case TLSModel::InitialExec:
2241 case TLSModel::LocalExec:
2242 return LowerToTLSExecModels(GA, DAG, model);
2244 llvm_unreachable("bogus TLS model");
2247 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2248 SelectionDAG &DAG) const {
2249 EVT PtrVT = getPointerTy();
2250 DebugLoc dl = Op.getDebugLoc();
2251 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2252 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2253 if (RelocM == Reloc::PIC_) {
2254 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2255 ARMConstantPoolValue *CPV =
2256 ARMConstantPoolConstant::Create(GV,
2257 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2258 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2259 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2260 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2262 MachinePointerInfo::getConstantPool(),
2263 false, false, false, 0);
2264 SDValue Chain = Result.getValue(1);
2265 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2266 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2268 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2269 MachinePointerInfo::getGOT(),
2270 false, false, false, 0);
2274 // If we have T2 ops, we can materialize the address directly via movt/movw
2275 // pair. This is always cheaper.
2276 if (Subtarget->useMovt()) {
2278 // FIXME: Once remat is capable of dealing with instructions with register
2279 // operands, expand this into two nodes.
2280 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2281 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2283 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2284 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2285 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2286 MachinePointerInfo::getConstantPool(),
2287 false, false, false, 0);
2291 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2292 SelectionDAG &DAG) const {
2293 EVT PtrVT = getPointerTy();
2294 DebugLoc dl = Op.getDebugLoc();
2295 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2296 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2297 MachineFunction &MF = DAG.getMachineFunction();
2298 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2300 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2301 // update ARMFastISel::ARMMaterializeGV.
2302 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2304 // FIXME: Once remat is capable of dealing with instructions with register
2305 // operands, expand this into two nodes.
2306 if (RelocM == Reloc::Static)
2307 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2308 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2310 unsigned Wrapper = (RelocM == Reloc::PIC_)
2311 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2312 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2313 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2314 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2315 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2316 MachinePointerInfo::getGOT(),
2317 false, false, false, 0);
2321 unsigned ARMPCLabelIndex = 0;
2323 if (RelocM == Reloc::Static) {
2324 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2326 ARMPCLabelIndex = AFI->createPICLabelUId();
2327 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2328 ARMConstantPoolValue *CPV =
2329 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2331 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2333 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2335 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2336 MachinePointerInfo::getConstantPool(),
2337 false, false, false, 0);
2338 SDValue Chain = Result.getValue(1);
2340 if (RelocM == Reloc::PIC_) {
2341 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2342 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2345 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2346 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2347 false, false, false, 0);
2352 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2353 SelectionDAG &DAG) const {
2354 assert(Subtarget->isTargetELF() &&
2355 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2356 MachineFunction &MF = DAG.getMachineFunction();
2357 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2358 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2359 EVT PtrVT = getPointerTy();
2360 DebugLoc dl = Op.getDebugLoc();
2361 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2362 ARMConstantPoolValue *CPV =
2363 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2364 ARMPCLabelIndex, PCAdj);
2365 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2366 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2367 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2368 MachinePointerInfo::getConstantPool(),
2369 false, false, false, 0);
2370 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2371 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2375 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2376 DebugLoc dl = Op.getDebugLoc();
2377 SDValue Val = DAG.getConstant(0, MVT::i32);
2378 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2379 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2380 Op.getOperand(1), Val);
2384 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2385 DebugLoc dl = Op.getDebugLoc();
2386 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2387 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2391 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2392 const ARMSubtarget *Subtarget) const {
2393 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2394 DebugLoc dl = Op.getDebugLoc();
2396 default: return SDValue(); // Don't custom lower most intrinsics.
2397 case Intrinsic::arm_thread_pointer: {
2398 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2399 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2401 case Intrinsic::eh_sjlj_lsda: {
2402 MachineFunction &MF = DAG.getMachineFunction();
2403 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2404 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2405 EVT PtrVT = getPointerTy();
2406 DebugLoc dl = Op.getDebugLoc();
2407 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2409 unsigned PCAdj = (RelocM != Reloc::PIC_)
2410 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2411 ARMConstantPoolValue *CPV =
2412 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2413 ARMCP::CPLSDA, PCAdj);
2414 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2415 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2417 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2418 MachinePointerInfo::getConstantPool(),
2419 false, false, false, 0);
2421 if (RelocM == Reloc::PIC_) {
2422 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2423 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2427 case Intrinsic::arm_neon_vmulls:
2428 case Intrinsic::arm_neon_vmullu: {
2429 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2430 ? ARMISD::VMULLs : ARMISD::VMULLu;
2431 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2432 Op.getOperand(1), Op.getOperand(2));
2437 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2438 const ARMSubtarget *Subtarget) {
2439 DebugLoc dl = Op.getDebugLoc();
2440 if (!Subtarget->hasDataBarrier()) {
2441 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2442 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2444 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2445 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2446 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2447 DAG.getConstant(0, MVT::i32));
2450 SDValue Op5 = Op.getOperand(5);
2451 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2452 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2453 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2454 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2456 ARM_MB::MemBOpt DMBOpt;
2457 if (isDeviceBarrier)
2458 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2460 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2461 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2462 DAG.getConstant(DMBOpt, MVT::i32));
2466 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2467 const ARMSubtarget *Subtarget) {
2468 // FIXME: handle "fence singlethread" more efficiently.
2469 DebugLoc dl = Op.getDebugLoc();
2470 if (!Subtarget->hasDataBarrier()) {
2471 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2472 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2474 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2475 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2476 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2477 DAG.getConstant(0, MVT::i32));
2480 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2481 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2484 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2485 const ARMSubtarget *Subtarget) {
2486 // ARM pre v5TE and Thumb1 does not have preload instructions.
2487 if (!(Subtarget->isThumb2() ||
2488 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2489 // Just preserve the chain.
2490 return Op.getOperand(0);
2492 DebugLoc dl = Op.getDebugLoc();
2493 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2495 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2496 // ARMv7 with MP extension has PLDW.
2497 return Op.getOperand(0);
2499 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2500 if (Subtarget->isThumb()) {
2502 isRead = ~isRead & 1;
2503 isData = ~isData & 1;
2506 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2507 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2508 DAG.getConstant(isData, MVT::i32));
2511 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2512 MachineFunction &MF = DAG.getMachineFunction();
2513 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2515 // vastart just stores the address of the VarArgsFrameIndex slot into the
2516 // memory location argument.
2517 DebugLoc dl = Op.getDebugLoc();
2518 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2519 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2520 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2521 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2522 MachinePointerInfo(SV), false, false, 0);
2526 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2527 SDValue &Root, SelectionDAG &DAG,
2528 DebugLoc dl) const {
2529 MachineFunction &MF = DAG.getMachineFunction();
2530 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2532 const TargetRegisterClass *RC;
2533 if (AFI->isThumb1OnlyFunction())
2534 RC = &ARM::tGPRRegClass;
2536 RC = &ARM::GPRRegClass;
2538 // Transform the arguments stored in physical registers into virtual ones.
2539 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2540 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2543 if (NextVA.isMemLoc()) {
2544 MachineFrameInfo *MFI = MF.getFrameInfo();
2545 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2547 // Create load node to retrieve arguments from the stack.
2548 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2549 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2550 MachinePointerInfo::getFixedStack(FI),
2551 false, false, false, 0);
2553 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2554 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2557 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2561 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2562 unsigned &VARegSize, unsigned &VARegSaveSize)
2565 if (CCInfo.isFirstByValRegValid())
2566 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2568 unsigned int firstUnalloced;
2569 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2570 sizeof(GPRArgRegs) /
2571 sizeof(GPRArgRegs[0]));
2572 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2575 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2576 VARegSize = NumGPRs * 4;
2577 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2580 // The remaining GPRs hold either the beginning of variable-argument
2581 // data, or the beginning of an aggregate passed by value (usuall
2582 // byval). Either way, we allocate stack slots adjacent to the data
2583 // provided by our caller, and store the unallocated registers there.
2584 // If this is a variadic function, the va_list pointer will begin with
2585 // these values; otherwise, this reassembles a (byval) structure that
2586 // was split between registers and memory.
2588 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2589 DebugLoc dl, SDValue &Chain,
2590 const Value *OrigArg,
2591 unsigned OffsetFromOrigArg,
2593 bool ForceMutable) const {
2594 MachineFunction &MF = DAG.getMachineFunction();
2595 MachineFrameInfo *MFI = MF.getFrameInfo();
2596 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2597 unsigned firstRegToSaveIndex;
2598 if (CCInfo.isFirstByValRegValid())
2599 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2601 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2602 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2605 unsigned VARegSize, VARegSaveSize;
2606 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2607 if (VARegSaveSize) {
2608 // If this function is vararg, store any remaining integer argument regs
2609 // to their spots on the stack so that they may be loaded by deferencing
2610 // the result of va_next.
2611 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2612 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2613 ArgOffset + VARegSaveSize
2616 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2619 SmallVector<SDValue, 4> MemOps;
2620 for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2621 const TargetRegisterClass *RC;
2622 if (AFI->isThumb1OnlyFunction())
2623 RC = &ARM::tGPRRegClass;
2625 RC = &ARM::GPRRegClass;
2627 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2628 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2630 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2631 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2633 MemOps.push_back(Store);
2634 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2635 DAG.getConstant(4, getPointerTy()));
2637 if (!MemOps.empty())
2638 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2639 &MemOps[0], MemOps.size());
2641 // This will point to the next argument passed via stack.
2642 AFI->setVarArgsFrameIndex(
2643 MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2647 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2648 CallingConv::ID CallConv, bool isVarArg,
2649 const SmallVectorImpl<ISD::InputArg>
2651 DebugLoc dl, SelectionDAG &DAG,
2652 SmallVectorImpl<SDValue> &InVals)
2654 MachineFunction &MF = DAG.getMachineFunction();
2655 MachineFrameInfo *MFI = MF.getFrameInfo();
2657 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2659 // Assign locations to all of the incoming arguments.
2660 SmallVector<CCValAssign, 16> ArgLocs;
2661 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2662 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2663 CCInfo.AnalyzeFormalArguments(Ins,
2664 CCAssignFnForNode(CallConv, /* Return*/ false,
2667 SmallVector<SDValue, 16> ArgValues;
2668 int lastInsIndex = -1;
2670 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2671 unsigned CurArgIdx = 0;
2672 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2673 CCValAssign &VA = ArgLocs[i];
2674 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2675 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2676 // Arguments stored in registers.
2677 if (VA.isRegLoc()) {
2678 EVT RegVT = VA.getLocVT();
2680 if (VA.needsCustom()) {
2681 // f64 and vector types are split up into multiple registers or
2682 // combinations of registers and stack slots.
2683 if (VA.getLocVT() == MVT::v2f64) {
2684 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2686 VA = ArgLocs[++i]; // skip ahead to next loc
2688 if (VA.isMemLoc()) {
2689 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2690 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2691 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2692 MachinePointerInfo::getFixedStack(FI),
2693 false, false, false, 0);
2695 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2698 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2699 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2700 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2701 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2702 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2704 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2707 const TargetRegisterClass *RC;
2709 if (RegVT == MVT::f32)
2710 RC = &ARM::SPRRegClass;
2711 else if (RegVT == MVT::f64)
2712 RC = &ARM::DPRRegClass;
2713 else if (RegVT == MVT::v2f64)
2714 RC = &ARM::QPRRegClass;
2715 else if (RegVT == MVT::i32)
2716 RC = AFI->isThumb1OnlyFunction() ?
2717 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2718 (const TargetRegisterClass*)&ARM::GPRRegClass;
2720 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2722 // Transform the arguments in physical registers into virtual ones.
2723 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2724 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2727 // If this is an 8 or 16-bit value, it is really passed promoted
2728 // to 32 bits. Insert an assert[sz]ext to capture this, then
2729 // truncate to the right size.
2730 switch (VA.getLocInfo()) {
2731 default: llvm_unreachable("Unknown loc info!");
2732 case CCValAssign::Full: break;
2733 case CCValAssign::BCvt:
2734 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2736 case CCValAssign::SExt:
2737 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2738 DAG.getValueType(VA.getValVT()));
2739 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2741 case CCValAssign::ZExt:
2742 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2743 DAG.getValueType(VA.getValVT()));
2744 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2748 InVals.push_back(ArgValue);
2750 } else { // VA.isRegLoc()
2753 assert(VA.isMemLoc());
2754 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2756 int index = ArgLocs[i].getValNo();
2758 // Some Ins[] entries become multiple ArgLoc[] entries.
2759 // Process them only once.
2760 if (index != lastInsIndex)
2762 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2763 // FIXME: For now, all byval parameter objects are marked mutable.
2764 // This can be changed with more analysis.
2765 // In case of tail call optimization mark all arguments mutable.
2766 // Since they could be overwritten by lowering of arguments in case of
2768 if (Flags.isByVal()) {
2769 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2770 if (!AFI->getVarArgsFrameIndex()) {
2771 VarArgStyleRegisters(CCInfo, DAG,
2772 dl, Chain, CurOrigArg,
2773 Ins[VA.getValNo()].PartOffset,
2774 VA.getLocMemOffset(),
2775 true /*force mutable frames*/);
2776 int VAFrameIndex = AFI->getVarArgsFrameIndex();
2777 InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2779 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2780 VA.getLocMemOffset(), false);
2781 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2784 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2785 VA.getLocMemOffset(), true);
2787 // Create load nodes to retrieve arguments from the stack.
2788 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2789 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2790 MachinePointerInfo::getFixedStack(FI),
2791 false, false, false, 0));
2793 lastInsIndex = index;
2800 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2801 CCInfo.getNextStackOffset());
2806 /// isFloatingPointZero - Return true if this is +0.0.
2807 static bool isFloatingPointZero(SDValue Op) {
2808 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2809 return CFP->getValueAPF().isPosZero();
2810 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2811 // Maybe this has already been legalized into the constant pool?
2812 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2813 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2814 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2815 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2816 return CFP->getValueAPF().isPosZero();
2822 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2823 /// the given operands.
2825 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2826 SDValue &ARMcc, SelectionDAG &DAG,
2827 DebugLoc dl) const {
2828 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2829 unsigned C = RHSC->getZExtValue();
2830 if (!isLegalICmpImmediate(C)) {
2831 // Constant does not fit, try adjusting it by one?
2836 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2837 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2838 RHS = DAG.getConstant(C-1, MVT::i32);
2843 if (C != 0 && isLegalICmpImmediate(C-1)) {
2844 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2845 RHS = DAG.getConstant(C-1, MVT::i32);
2850 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2851 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2852 RHS = DAG.getConstant(C+1, MVT::i32);
2857 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2858 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2859 RHS = DAG.getConstant(C+1, MVT::i32);
2866 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2867 ARMISD::NodeType CompareType;
2870 CompareType = ARMISD::CMP;
2875 CompareType = ARMISD::CMPZ;
2878 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2879 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2882 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2884 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2885 DebugLoc dl) const {
2887 if (!isFloatingPointZero(RHS))
2888 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2890 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2891 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2894 /// duplicateCmp - Glue values can have only one use, so this function
2895 /// duplicates a comparison node.
2897 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2898 unsigned Opc = Cmp.getOpcode();
2899 DebugLoc DL = Cmp.getDebugLoc();
2900 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2901 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2903 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2904 Cmp = Cmp.getOperand(0);
2905 Opc = Cmp.getOpcode();
2906 if (Opc == ARMISD::CMPFP)
2907 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2909 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2910 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2912 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2915 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2916 SDValue Cond = Op.getOperand(0);
2917 SDValue SelectTrue = Op.getOperand(1);
2918 SDValue SelectFalse = Op.getOperand(2);
2919 DebugLoc dl = Op.getDebugLoc();
2923 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2924 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2926 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2927 const ConstantSDNode *CMOVTrue =
2928 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2929 const ConstantSDNode *CMOVFalse =
2930 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2932 if (CMOVTrue && CMOVFalse) {
2933 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2934 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2938 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2940 False = SelectFalse;
2941 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2946 if (True.getNode() && False.getNode()) {
2947 EVT VT = Op.getValueType();
2948 SDValue ARMcc = Cond.getOperand(2);
2949 SDValue CCR = Cond.getOperand(3);
2950 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2951 assert(True.getValueType() == VT);
2952 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2957 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2958 // undefined bits before doing a full-word comparison with zero.
2959 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2960 DAG.getConstant(1, Cond.getValueType()));
2962 return DAG.getSelectCC(dl, Cond,
2963 DAG.getConstant(0, Cond.getValueType()),
2964 SelectTrue, SelectFalse, ISD::SETNE);
2967 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2968 EVT VT = Op.getValueType();
2969 SDValue LHS = Op.getOperand(0);
2970 SDValue RHS = Op.getOperand(1);
2971 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2972 SDValue TrueVal = Op.getOperand(2);
2973 SDValue FalseVal = Op.getOperand(3);
2974 DebugLoc dl = Op.getDebugLoc();
2976 if (LHS.getValueType() == MVT::i32) {
2978 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2979 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2980 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2983 ARMCC::CondCodes CondCode, CondCode2;
2984 FPCCToARMCC(CC, CondCode, CondCode2);
2986 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2987 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2988 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2989 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2991 if (CondCode2 != ARMCC::AL) {
2992 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2993 // FIXME: Needs another CMP because flag can have but one use.
2994 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2995 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2996 Result, TrueVal, ARMcc2, CCR, Cmp2);
3001 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3002 /// to morph to an integer compare sequence.
3003 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3004 const ARMSubtarget *Subtarget) {
3005 SDNode *N = Op.getNode();
3006 if (!N->hasOneUse())
3007 // Otherwise it requires moving the value from fp to integer registers.
3009 if (!N->getNumValues())
3011 EVT VT = Op.getValueType();
3012 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3013 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3014 // vmrs are very slow, e.g. cortex-a8.
3017 if (isFloatingPointZero(Op)) {
3021 return ISD::isNormalLoad(N);
3024 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3025 if (isFloatingPointZero(Op))
3026 return DAG.getConstant(0, MVT::i32);
3028 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3029 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3030 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3031 Ld->isVolatile(), Ld->isNonTemporal(),
3032 Ld->isInvariant(), Ld->getAlignment());
3034 llvm_unreachable("Unknown VFP cmp argument!");
3037 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3038 SDValue &RetVal1, SDValue &RetVal2) {
3039 if (isFloatingPointZero(Op)) {
3040 RetVal1 = DAG.getConstant(0, MVT::i32);
3041 RetVal2 = DAG.getConstant(0, MVT::i32);
3045 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3046 SDValue Ptr = Ld->getBasePtr();
3047 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3048 Ld->getChain(), Ptr,
3049 Ld->getPointerInfo(),
3050 Ld->isVolatile(), Ld->isNonTemporal(),
3051 Ld->isInvariant(), Ld->getAlignment());
3053 EVT PtrType = Ptr.getValueType();
3054 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3055 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3056 PtrType, Ptr, DAG.getConstant(4, PtrType));
3057 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3058 Ld->getChain(), NewPtr,
3059 Ld->getPointerInfo().getWithOffset(4),
3060 Ld->isVolatile(), Ld->isNonTemporal(),
3061 Ld->isInvariant(), NewAlign);
3065 llvm_unreachable("Unknown VFP cmp argument!");
3068 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3069 /// f32 and even f64 comparisons to integer ones.
3071 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3072 SDValue Chain = Op.getOperand(0);
3073 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3074 SDValue LHS = Op.getOperand(2);
3075 SDValue RHS = Op.getOperand(3);
3076 SDValue Dest = Op.getOperand(4);
3077 DebugLoc dl = Op.getDebugLoc();
3079 bool LHSSeenZero = false;
3080 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3081 bool RHSSeenZero = false;
3082 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3083 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3084 // If unsafe fp math optimization is enabled and there are no other uses of
3085 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3086 // to an integer comparison.
3087 if (CC == ISD::SETOEQ)
3089 else if (CC == ISD::SETUNE)
3092 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3094 if (LHS.getValueType() == MVT::f32) {
3095 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3096 bitcastf32Toi32(LHS, DAG), Mask);
3097 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3098 bitcastf32Toi32(RHS, DAG), Mask);
3099 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3100 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3101 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3102 Chain, Dest, ARMcc, CCR, Cmp);
3107 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3108 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3109 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3110 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3111 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3112 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3113 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3114 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3115 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3121 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3122 SDValue Chain = Op.getOperand(0);
3123 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3124 SDValue LHS = Op.getOperand(2);
3125 SDValue RHS = Op.getOperand(3);
3126 SDValue Dest = Op.getOperand(4);
3127 DebugLoc dl = Op.getDebugLoc();
3129 if (LHS.getValueType() == MVT::i32) {
3131 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3132 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3133 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3134 Chain, Dest, ARMcc, CCR, Cmp);
3137 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3139 if (getTargetMachine().Options.UnsafeFPMath &&
3140 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3141 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3142 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3143 if (Result.getNode())
3147 ARMCC::CondCodes CondCode, CondCode2;
3148 FPCCToARMCC(CC, CondCode, CondCode2);
3150 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3151 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3152 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3153 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3154 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3155 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3156 if (CondCode2 != ARMCC::AL) {
3157 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3158 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3159 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3164 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3165 SDValue Chain = Op.getOperand(0);
3166 SDValue Table = Op.getOperand(1);
3167 SDValue Index = Op.getOperand(2);
3168 DebugLoc dl = Op.getDebugLoc();
3170 EVT PTy = getPointerTy();
3171 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3172 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3173 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3174 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3175 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3176 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3177 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3178 if (Subtarget->isThumb2()) {
3179 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3180 // which does another jump to the destination. This also makes it easier
3181 // to translate it to TBB / TBH later.
3182 // FIXME: This might not work if the function is extremely large.
3183 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3184 Addr, Op.getOperand(2), JTI, UId);
3186 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3187 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3188 MachinePointerInfo::getJumpTable(),
3189 false, false, false, 0);
3190 Chain = Addr.getValue(1);
3191 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3192 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3194 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3195 MachinePointerInfo::getJumpTable(),
3196 false, false, false, 0);
3197 Chain = Addr.getValue(1);
3198 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3202 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3203 EVT VT = Op.getValueType();
3204 DebugLoc dl = Op.getDebugLoc();
3206 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3207 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3209 return DAG.UnrollVectorOp(Op.getNode());
3212 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3213 "Invalid type for custom lowering!");
3214 if (VT != MVT::v4i16)
3215 return DAG.UnrollVectorOp(Op.getNode());
3217 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3218 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3221 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3222 EVT VT = Op.getValueType();
3224 return LowerVectorFP_TO_INT(Op, DAG);
3226 DebugLoc dl = Op.getDebugLoc();
3229 switch (Op.getOpcode()) {
3230 default: llvm_unreachable("Invalid opcode!");
3231 case ISD::FP_TO_SINT:
3232 Opc = ARMISD::FTOSI;
3234 case ISD::FP_TO_UINT:
3235 Opc = ARMISD::FTOUI;
3238 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3239 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3242 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3243 EVT VT = Op.getValueType();
3244 DebugLoc dl = Op.getDebugLoc();
3246 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3247 if (VT.getVectorElementType() == MVT::f32)
3249 return DAG.UnrollVectorOp(Op.getNode());
3252 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3253 "Invalid type for custom lowering!");
3254 if (VT != MVT::v4f32)
3255 return DAG.UnrollVectorOp(Op.getNode());
3259 switch (Op.getOpcode()) {
3260 default: llvm_unreachable("Invalid opcode!");
3261 case ISD::SINT_TO_FP:
3262 CastOpc = ISD::SIGN_EXTEND;
3263 Opc = ISD::SINT_TO_FP;
3265 case ISD::UINT_TO_FP:
3266 CastOpc = ISD::ZERO_EXTEND;
3267 Opc = ISD::UINT_TO_FP;
3271 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3272 return DAG.getNode(Opc, dl, VT, Op);
3275 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3276 EVT VT = Op.getValueType();
3278 return LowerVectorINT_TO_FP(Op, DAG);
3280 DebugLoc dl = Op.getDebugLoc();
3283 switch (Op.getOpcode()) {
3284 default: llvm_unreachable("Invalid opcode!");
3285 case ISD::SINT_TO_FP:
3286 Opc = ARMISD::SITOF;
3288 case ISD::UINT_TO_FP:
3289 Opc = ARMISD::UITOF;
3293 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3294 return DAG.getNode(Opc, dl, VT, Op);
3297 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3298 // Implement fcopysign with a fabs and a conditional fneg.
3299 SDValue Tmp0 = Op.getOperand(0);
3300 SDValue Tmp1 = Op.getOperand(1);
3301 DebugLoc dl = Op.getDebugLoc();
3302 EVT VT = Op.getValueType();
3303 EVT SrcVT = Tmp1.getValueType();
3304 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3305 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3306 bool UseNEON = !InGPR && Subtarget->hasNEON();
3309 // Use VBSL to copy the sign bit.
3310 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3311 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3312 DAG.getTargetConstant(EncodedVal, MVT::i32));
3313 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3315 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3316 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3317 DAG.getConstant(32, MVT::i32));
3318 else /*if (VT == MVT::f32)*/
3319 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3320 if (SrcVT == MVT::f32) {
3321 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3323 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3324 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3325 DAG.getConstant(32, MVT::i32));
3326 } else if (VT == MVT::f32)
3327 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3328 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3329 DAG.getConstant(32, MVT::i32));
3330 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3331 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3333 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3335 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3336 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3337 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3339 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3340 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3341 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3342 if (VT == MVT::f32) {
3343 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3344 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3345 DAG.getConstant(0, MVT::i32));
3347 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3353 // Bitcast operand 1 to i32.
3354 if (SrcVT == MVT::f64)
3355 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3356 &Tmp1, 1).getValue(1);
3357 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3359 // Or in the signbit with integer operations.
3360 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3361 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3362 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3363 if (VT == MVT::f32) {
3364 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3365 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3366 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3367 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3370 // f64: Or the high part with signbit and then combine two parts.
3371 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3373 SDValue Lo = Tmp0.getValue(0);
3374 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3375 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3376 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3379 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3380 MachineFunction &MF = DAG.getMachineFunction();
3381 MachineFrameInfo *MFI = MF.getFrameInfo();
3382 MFI->setReturnAddressIsTaken(true);
3384 EVT VT = Op.getValueType();
3385 DebugLoc dl = Op.getDebugLoc();
3386 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3388 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3389 SDValue Offset = DAG.getConstant(4, MVT::i32);
3390 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3391 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3392 MachinePointerInfo(), false, false, false, 0);
3395 // Return LR, which contains the return address. Mark it an implicit live-in.
3396 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3397 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3400 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3401 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3402 MFI->setFrameAddressIsTaken(true);
3404 EVT VT = Op.getValueType();
3405 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3406 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3407 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3408 ? ARM::R7 : ARM::R11;
3409 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3411 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3412 MachinePointerInfo(),
3413 false, false, false, 0);
3417 /// ExpandBITCAST - If the target supports VFP, this function is called to
3418 /// expand a bit convert where either the source or destination type is i64 to
3419 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3420 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3421 /// vectors), since the legalizer won't know what to do with that.
3422 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3423 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3424 DebugLoc dl = N->getDebugLoc();
3425 SDValue Op = N->getOperand(0);
3427 // This function is only supposed to be called for i64 types, either as the
3428 // source or destination of the bit convert.
3429 EVT SrcVT = Op.getValueType();
3430 EVT DstVT = N->getValueType(0);
3431 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3432 "ExpandBITCAST called for non-i64 type");
3434 // Turn i64->f64 into VMOVDRR.
3435 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3436 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3437 DAG.getConstant(0, MVT::i32));
3438 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3439 DAG.getConstant(1, MVT::i32));
3440 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3441 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3444 // Turn f64->i64 into VMOVRRD.
3445 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3446 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3447 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3448 // Merge the pieces into a single i64 value.
3449 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3455 /// getZeroVector - Returns a vector of specified type with all zero elements.
3456 /// Zero vectors are used to represent vector negation and in those cases
3457 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3458 /// not support i64 elements, so sometimes the zero vectors will need to be
3459 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3461 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3462 assert(VT.isVector() && "Expected a vector type");
3463 // The canonical modified immediate encoding of a zero vector is....0!
3464 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3465 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3466 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3467 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3470 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3471 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3472 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3473 SelectionDAG &DAG) const {
3474 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3475 EVT VT = Op.getValueType();
3476 unsigned VTBits = VT.getSizeInBits();
3477 DebugLoc dl = Op.getDebugLoc();
3478 SDValue ShOpLo = Op.getOperand(0);
3479 SDValue ShOpHi = Op.getOperand(1);
3480 SDValue ShAmt = Op.getOperand(2);
3482 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3484 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3486 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3487 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3488 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3489 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3490 DAG.getConstant(VTBits, MVT::i32));
3491 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3492 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3493 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3495 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3496 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3498 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3499 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3502 SDValue Ops[2] = { Lo, Hi };
3503 return DAG.getMergeValues(Ops, 2, dl);
3506 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3507 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3508 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3509 SelectionDAG &DAG) const {
3510 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3511 EVT VT = Op.getValueType();
3512 unsigned VTBits = VT.getSizeInBits();
3513 DebugLoc dl = Op.getDebugLoc();
3514 SDValue ShOpLo = Op.getOperand(0);
3515 SDValue ShOpHi = Op.getOperand(1);
3516 SDValue ShAmt = Op.getOperand(2);
3519 assert(Op.getOpcode() == ISD::SHL_PARTS);
3520 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3521 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3522 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3523 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3524 DAG.getConstant(VTBits, MVT::i32));
3525 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3526 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3528 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3529 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3530 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3532 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3533 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3536 SDValue Ops[2] = { Lo, Hi };
3537 return DAG.getMergeValues(Ops, 2, dl);
3540 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3541 SelectionDAG &DAG) const {
3542 // The rounding mode is in bits 23:22 of the FPSCR.
3543 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3544 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3545 // so that the shift + and get folded into a bitfield extract.
3546 DebugLoc dl = Op.getDebugLoc();
3547 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3548 DAG.getConstant(Intrinsic::arm_get_fpscr,
3550 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3551 DAG.getConstant(1U << 22, MVT::i32));
3552 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3553 DAG.getConstant(22, MVT::i32));
3554 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3555 DAG.getConstant(3, MVT::i32));
3558 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3559 const ARMSubtarget *ST) {
3560 EVT VT = N->getValueType(0);
3561 DebugLoc dl = N->getDebugLoc();
3563 if (!ST->hasV6T2Ops())
3566 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3567 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3570 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3571 /// for each 16-bit element from operand, repeated. The basic idea is to
3572 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3574 /// Trace for v4i16:
3575 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3576 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3577 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3578 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3579 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3580 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3581 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3582 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3583 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3584 EVT VT = N->getValueType(0);
3585 DebugLoc DL = N->getDebugLoc();
3587 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3588 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3589 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3590 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3591 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3592 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3595 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3596 /// bit-count for each 16-bit element from the operand. We need slightly
3597 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3598 /// 64/128-bit registers.
3600 /// Trace for v4i16:
3601 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3602 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3603 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3604 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3605 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3606 EVT VT = N->getValueType(0);
3607 DebugLoc DL = N->getDebugLoc();
3609 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3610 if (VT.is64BitVector()) {
3611 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3612 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3613 DAG.getIntPtrConstant(0));
3615 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3616 BitCounts, DAG.getIntPtrConstant(0));
3617 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3621 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3622 /// bit-count for each 32-bit element from the operand. The idea here is
3623 /// to split the vector into 16-bit elements, leverage the 16-bit count
3624 /// routine, and then combine the results.
3626 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3627 /// input = [v0 v1 ] (vi: 32-bit elements)
3628 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3629 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3630 /// vrev: N0 = [k1 k0 k3 k2 ]
3632 /// N1 =+[k1 k0 k3 k2 ]
3634 /// N2 =+[k1 k3 k0 k2 ]
3636 /// Extended =+[k1 k3 k0 k2 ]
3638 /// Extracted=+[k1 k3 ]
3640 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3641 EVT VT = N->getValueType(0);
3642 DebugLoc DL = N->getDebugLoc();
3644 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3646 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3647 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3648 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3649 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3650 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3652 if (VT.is64BitVector()) {
3653 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3654 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3655 DAG.getIntPtrConstant(0));
3657 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3658 DAG.getIntPtrConstant(0));
3659 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3663 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3664 const ARMSubtarget *ST) {
3665 EVT VT = N->getValueType(0);
3667 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3668 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3669 VT == MVT::v4i16 || VT == MVT::v8i16) &&
3670 "Unexpected type for custom ctpop lowering");
3672 if (VT.getVectorElementType() == MVT::i32)
3673 return lowerCTPOP32BitElements(N, DAG);
3675 return lowerCTPOP16BitElements(N, DAG);
3678 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3679 const ARMSubtarget *ST) {
3680 EVT VT = N->getValueType(0);
3681 DebugLoc dl = N->getDebugLoc();
3686 // Lower vector shifts on NEON to use VSHL.
3687 assert(ST->hasNEON() && "unexpected vector shift");
3689 // Left shifts translate directly to the vshiftu intrinsic.
3690 if (N->getOpcode() == ISD::SHL)
3691 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3692 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3693 N->getOperand(0), N->getOperand(1));
3695 assert((N->getOpcode() == ISD::SRA ||
3696 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3698 // NEON uses the same intrinsics for both left and right shifts. For
3699 // right shifts, the shift amounts are negative, so negate the vector of
3701 EVT ShiftVT = N->getOperand(1).getValueType();
3702 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3703 getZeroVector(ShiftVT, DAG, dl),
3705 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3706 Intrinsic::arm_neon_vshifts :
3707 Intrinsic::arm_neon_vshiftu);
3708 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3709 DAG.getConstant(vshiftInt, MVT::i32),
3710 N->getOperand(0), NegatedCount);
3713 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3714 const ARMSubtarget *ST) {
3715 EVT VT = N->getValueType(0);
3716 DebugLoc dl = N->getDebugLoc();
3718 // We can get here for a node like i32 = ISD::SHL i32, i64
3722 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3723 "Unknown shift to lower!");
3725 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3726 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3727 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3730 // If we are in thumb mode, we don't have RRX.
3731 if (ST->isThumb1Only()) return SDValue();
3733 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3734 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3735 DAG.getConstant(0, MVT::i32));
3736 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3737 DAG.getConstant(1, MVT::i32));
3739 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3740 // captures the result into a carry flag.
3741 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3742 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3744 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3745 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3747 // Merge the pieces into a single i64 value.
3748 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3751 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3752 SDValue TmpOp0, TmpOp1;
3753 bool Invert = false;
3757 SDValue Op0 = Op.getOperand(0);
3758 SDValue Op1 = Op.getOperand(1);
3759 SDValue CC = Op.getOperand(2);
3760 EVT VT = Op.getValueType();
3761 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3762 DebugLoc dl = Op.getDebugLoc();
3764 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3765 switch (SetCCOpcode) {
3766 default: llvm_unreachable("Illegal FP comparison");
3768 case ISD::SETNE: Invert = true; // Fallthrough
3770 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3772 case ISD::SETLT: Swap = true; // Fallthrough
3774 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3776 case ISD::SETLE: Swap = true; // Fallthrough
3778 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3779 case ISD::SETUGE: Swap = true; // Fallthrough
3780 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3781 case ISD::SETUGT: Swap = true; // Fallthrough
3782 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3783 case ISD::SETUEQ: Invert = true; // Fallthrough
3785 // Expand this to (OLT | OGT).
3789 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3790 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3792 case ISD::SETUO: Invert = true; // Fallthrough
3794 // Expand this to (OLT | OGE).
3798 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3799 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3803 // Integer comparisons.
3804 switch (SetCCOpcode) {
3805 default: llvm_unreachable("Illegal integer comparison");
3806 case ISD::SETNE: Invert = true;
3807 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3808 case ISD::SETLT: Swap = true;
3809 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3810 case ISD::SETLE: Swap = true;
3811 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3812 case ISD::SETULT: Swap = true;
3813 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3814 case ISD::SETULE: Swap = true;
3815 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3818 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3819 if (Opc == ARMISD::VCEQ) {
3822 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3824 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3827 // Ignore bitconvert.
3828 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3829 AndOp = AndOp.getOperand(0);
3831 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3833 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3834 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3841 std::swap(Op0, Op1);
3843 // If one of the operands is a constant vector zero, attempt to fold the
3844 // comparison to a specialized compare-against-zero form.
3846 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3848 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3849 if (Opc == ARMISD::VCGE)
3850 Opc = ARMISD::VCLEZ;
3851 else if (Opc == ARMISD::VCGT)
3852 Opc = ARMISD::VCLTZ;
3857 if (SingleOp.getNode()) {
3860 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3862 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3864 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3866 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3868 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3870 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3873 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3877 Result = DAG.getNOT(dl, Result, VT);
3882 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3883 /// valid vector constant for a NEON instruction with a "modified immediate"
3884 /// operand (e.g., VMOV). If so, return the encoded value.
3885 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3886 unsigned SplatBitSize, SelectionDAG &DAG,
3887 EVT &VT, bool is128Bits, NEONModImmType type) {
3888 unsigned OpCmode, Imm;
3890 // SplatBitSize is set to the smallest size that splats the vector, so a
3891 // zero vector will always have SplatBitSize == 8. However, NEON modified
3892 // immediate instructions others than VMOV do not support the 8-bit encoding
3893 // of a zero vector, and the default encoding of zero is supposed to be the
3898 switch (SplatBitSize) {
3900 if (type != VMOVModImm)
3902 // Any 1-byte value is OK. Op=0, Cmode=1110.
3903 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3906 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3910 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3911 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3912 if ((SplatBits & ~0xff) == 0) {
3913 // Value = 0x00nn: Op=x, Cmode=100x.
3918 if ((SplatBits & ~0xff00) == 0) {
3919 // Value = 0xnn00: Op=x, Cmode=101x.
3921 Imm = SplatBits >> 8;
3927 // NEON's 32-bit VMOV supports splat values where:
3928 // * only one byte is nonzero, or
3929 // * the least significant byte is 0xff and the second byte is nonzero, or
3930 // * the least significant 2 bytes are 0xff and the third is nonzero.
3931 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3932 if ((SplatBits & ~0xff) == 0) {
3933 // Value = 0x000000nn: Op=x, Cmode=000x.
3938 if ((SplatBits & ~0xff00) == 0) {
3939 // Value = 0x0000nn00: Op=x, Cmode=001x.
3941 Imm = SplatBits >> 8;
3944 if ((SplatBits & ~0xff0000) == 0) {
3945 // Value = 0x00nn0000: Op=x, Cmode=010x.
3947 Imm = SplatBits >> 16;
3950 if ((SplatBits & ~0xff000000) == 0) {
3951 // Value = 0xnn000000: Op=x, Cmode=011x.
3953 Imm = SplatBits >> 24;
3957 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3958 if (type == OtherModImm) return SDValue();
3960 if ((SplatBits & ~0xffff) == 0 &&
3961 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3962 // Value = 0x0000nnff: Op=x, Cmode=1100.
3964 Imm = SplatBits >> 8;
3969 if ((SplatBits & ~0xffffff) == 0 &&
3970 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3971 // Value = 0x00nnffff: Op=x, Cmode=1101.
3973 Imm = SplatBits >> 16;
3974 SplatBits |= 0xffff;
3978 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3979 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3980 // VMOV.I32. A (very) minor optimization would be to replicate the value
3981 // and fall through here to test for a valid 64-bit splat. But, then the
3982 // caller would also need to check and handle the change in size.
3986 if (type != VMOVModImm)
3988 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3989 uint64_t BitMask = 0xff;
3991 unsigned ImmMask = 1;
3993 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3994 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3997 } else if ((SplatBits & BitMask) != 0) {
4003 // Op=1, Cmode=1110.
4006 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4011 llvm_unreachable("unexpected size for isNEONModifiedImm");
4014 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4015 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4018 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4019 const ARMSubtarget *ST) const {
4020 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4023 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4024 assert(Op.getValueType() == MVT::f32 &&
4025 "ConstantFP custom lowering should only occur for f32.");
4027 // Try splatting with a VMOV.f32...
4028 APFloat FPVal = CFP->getValueAPF();
4029 int ImmVal = ARM_AM::getFP32Imm(FPVal);
4031 DebugLoc DL = Op.getDebugLoc();
4032 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4033 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4035 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4036 DAG.getConstant(0, MVT::i32));
4039 // If that fails, try a VMOV.i32
4041 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4042 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4044 if (NewVal != SDValue()) {
4045 DebugLoc DL = Op.getDebugLoc();
4046 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4048 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4050 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4051 DAG.getConstant(0, MVT::i32));
4054 // Finally, try a VMVN.i32
4055 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4057 if (NewVal != SDValue()) {
4058 DebugLoc DL = Op.getDebugLoc();
4059 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4060 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4062 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4063 DAG.getConstant(0, MVT::i32));
4069 // check if an VEXT instruction can handle the shuffle mask when the
4070 // vector sources of the shuffle are the same.
4071 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4072 unsigned NumElts = VT.getVectorNumElements();
4074 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4080 // If this is a VEXT shuffle, the immediate value is the index of the first
4081 // element. The other shuffle indices must be the successive elements after
4083 unsigned ExpectedElt = Imm;
4084 for (unsigned i = 1; i < NumElts; ++i) {
4085 // Increment the expected index. If it wraps around, just follow it
4086 // back to index zero and keep going.
4088 if (ExpectedElt == NumElts)
4091 if (M[i] < 0) continue; // ignore UNDEF indices
4092 if (ExpectedElt != static_cast<unsigned>(M[i]))
4100 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4101 bool &ReverseVEXT, unsigned &Imm) {
4102 unsigned NumElts = VT.getVectorNumElements();
4103 ReverseVEXT = false;
4105 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4111 // If this is a VEXT shuffle, the immediate value is the index of the first
4112 // element. The other shuffle indices must be the successive elements after
4114 unsigned ExpectedElt = Imm;
4115 for (unsigned i = 1; i < NumElts; ++i) {
4116 // Increment the expected index. If it wraps around, it may still be
4117 // a VEXT but the source vectors must be swapped.
4119 if (ExpectedElt == NumElts * 2) {
4124 if (M[i] < 0) continue; // ignore UNDEF indices
4125 if (ExpectedElt != static_cast<unsigned>(M[i]))
4129 // Adjust the index value if the source operands will be swapped.
4136 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4137 /// instruction with the specified blocksize. (The order of the elements
4138 /// within each block of the vector is reversed.)
4139 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4140 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4141 "Only possible block sizes for VREV are: 16, 32, 64");
4143 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4147 unsigned NumElts = VT.getVectorNumElements();
4148 unsigned BlockElts = M[0] + 1;
4149 // If the first shuffle index is UNDEF, be optimistic.
4151 BlockElts = BlockSize / EltSz;
4153 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4156 for (unsigned i = 0; i < NumElts; ++i) {
4157 if (M[i] < 0) continue; // ignore UNDEF indices
4158 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4165 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4166 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4167 // range, then 0 is placed into the resulting vector. So pretty much any mask
4168 // of 8 elements can work here.
4169 return VT == MVT::v8i8 && M.size() == 8;
4172 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4173 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4177 unsigned NumElts = VT.getVectorNumElements();
4178 WhichResult = (M[0] == 0 ? 0 : 1);
4179 for (unsigned i = 0; i < NumElts; i += 2) {
4180 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4181 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4187 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4188 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4189 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4190 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4191 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4195 unsigned NumElts = VT.getVectorNumElements();
4196 WhichResult = (M[0] == 0 ? 0 : 1);
4197 for (unsigned i = 0; i < NumElts; i += 2) {
4198 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4199 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4205 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4206 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4210 unsigned NumElts = VT.getVectorNumElements();
4211 WhichResult = (M[0] == 0 ? 0 : 1);
4212 for (unsigned i = 0; i != NumElts; ++i) {
4213 if (M[i] < 0) continue; // ignore UNDEF indices
4214 if ((unsigned) M[i] != 2 * i + WhichResult)
4218 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4219 if (VT.is64BitVector() && EltSz == 32)
4225 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4226 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4227 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4228 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4229 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4233 unsigned Half = VT.getVectorNumElements() / 2;
4234 WhichResult = (M[0] == 0 ? 0 : 1);
4235 for (unsigned j = 0; j != 2; ++j) {
4236 unsigned Idx = WhichResult;
4237 for (unsigned i = 0; i != Half; ++i) {
4238 int MIdx = M[i + j * Half];
4239 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4245 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4246 if (VT.is64BitVector() && EltSz == 32)
4252 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4253 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4257 unsigned NumElts = VT.getVectorNumElements();
4258 WhichResult = (M[0] == 0 ? 0 : 1);
4259 unsigned Idx = WhichResult * NumElts / 2;
4260 for (unsigned i = 0; i != NumElts; i += 2) {
4261 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4262 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4267 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4268 if (VT.is64BitVector() && EltSz == 32)
4274 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4275 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4276 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4277 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4278 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4282 unsigned NumElts = VT.getVectorNumElements();
4283 WhichResult = (M[0] == 0 ? 0 : 1);
4284 unsigned Idx = WhichResult * NumElts / 2;
4285 for (unsigned i = 0; i != NumElts; i += 2) {
4286 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4287 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4292 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4293 if (VT.is64BitVector() && EltSz == 32)
4299 // If N is an integer constant that can be moved into a register in one
4300 // instruction, return an SDValue of such a constant (will become a MOV
4301 // instruction). Otherwise return null.
4302 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4303 const ARMSubtarget *ST, DebugLoc dl) {
4305 if (!isa<ConstantSDNode>(N))
4307 Val = cast<ConstantSDNode>(N)->getZExtValue();
4309 if (ST->isThumb1Only()) {
4310 if (Val <= 255 || ~Val <= 255)
4311 return DAG.getConstant(Val, MVT::i32);
4313 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4314 return DAG.getConstant(Val, MVT::i32);
4319 // If this is a case we can't handle, return null and let the default
4320 // expansion code take care of it.
4321 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4322 const ARMSubtarget *ST) const {
4323 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4324 DebugLoc dl = Op.getDebugLoc();
4325 EVT VT = Op.getValueType();
4327 APInt SplatBits, SplatUndef;
4328 unsigned SplatBitSize;
4330 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4331 if (SplatBitSize <= 64) {
4332 // Check if an immediate VMOV works.
4334 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4335 SplatUndef.getZExtValue(), SplatBitSize,
4336 DAG, VmovVT, VT.is128BitVector(),
4338 if (Val.getNode()) {
4339 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4340 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4343 // Try an immediate VMVN.
4344 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4345 Val = isNEONModifiedImm(NegatedImm,
4346 SplatUndef.getZExtValue(), SplatBitSize,
4347 DAG, VmovVT, VT.is128BitVector(),
4349 if (Val.getNode()) {
4350 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4351 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4354 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4355 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4356 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4358 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4359 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4365 // Scan through the operands to see if only one value is used.
4367 // As an optimisation, even if more than one value is used it may be more
4368 // profitable to splat with one value then change some lanes.
4370 // Heuristically we decide to do this if the vector has a "dominant" value,
4371 // defined as splatted to more than half of the lanes.
4372 unsigned NumElts = VT.getVectorNumElements();
4373 bool isOnlyLowElement = true;
4374 bool usesOnlyOneValue = true;
4375 bool hasDominantValue = false;
4376 bool isConstant = true;
4378 // Map of the number of times a particular SDValue appears in the
4380 DenseMap<SDValue, unsigned> ValueCounts;
4382 for (unsigned i = 0; i < NumElts; ++i) {
4383 SDValue V = Op.getOperand(i);
4384 if (V.getOpcode() == ISD::UNDEF)
4387 isOnlyLowElement = false;
4388 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4391 ValueCounts.insert(std::make_pair(V, 0));
4392 unsigned &Count = ValueCounts[V];
4394 // Is this value dominant? (takes up more than half of the lanes)
4395 if (++Count > (NumElts / 2)) {
4396 hasDominantValue = true;
4400 if (ValueCounts.size() != 1)
4401 usesOnlyOneValue = false;
4402 if (!Value.getNode() && ValueCounts.size() > 0)
4403 Value = ValueCounts.begin()->first;
4405 if (ValueCounts.size() == 0)
4406 return DAG.getUNDEF(VT);
4408 if (isOnlyLowElement)
4409 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4411 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4413 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4414 // i32 and try again.
4415 if (hasDominantValue && EltSize <= 32) {
4419 // If we are VDUPing a value that comes directly from a vector, that will
4420 // cause an unnecessary move to and from a GPR, where instead we could
4421 // just use VDUPLANE.
4422 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4423 // We need to create a new undef vector to use for the VDUPLANE if the
4424 // size of the vector from which we get the value is different than the
4425 // size of the vector that we need to create. We will insert the element
4426 // such that the register coalescer will remove unnecessary copies.
4427 if (VT != Value->getOperand(0).getValueType()) {
4428 ConstantSDNode *constIndex;
4429 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4430 assert(constIndex && "The index is not a constant!");
4431 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4432 VT.getVectorNumElements();
4433 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4434 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4435 Value, DAG.getConstant(index, MVT::i32)),
4436 DAG.getConstant(index, MVT::i32));
4438 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4439 Value->getOperand(0), Value->getOperand(1));
4443 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4445 if (!usesOnlyOneValue) {
4446 // The dominant value was splatted as 'N', but we now have to insert
4447 // all differing elements.
4448 for (unsigned I = 0; I < NumElts; ++I) {
4449 if (Op.getOperand(I) == Value)
4451 SmallVector<SDValue, 3> Ops;
4453 Ops.push_back(Op.getOperand(I));
4454 Ops.push_back(DAG.getConstant(I, MVT::i32));
4455 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4460 if (VT.getVectorElementType().isFloatingPoint()) {
4461 SmallVector<SDValue, 8> Ops;
4462 for (unsigned i = 0; i < NumElts; ++i)
4463 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4465 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4466 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4467 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4469 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4471 if (usesOnlyOneValue) {
4472 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4473 if (isConstant && Val.getNode())
4474 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4478 // If all elements are constants and the case above didn't get hit, fall back
4479 // to the default expansion, which will generate a load from the constant
4484 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4486 SDValue shuffle = ReconstructShuffle(Op, DAG);
4487 if (shuffle != SDValue())
4491 // Vectors with 32- or 64-bit elements can be built by directly assigning
4492 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4493 // will be legalized.
4494 if (EltSize >= 32) {
4495 // Do the expansion with floating-point types, since that is what the VFP
4496 // registers are defined to use, and since i64 is not legal.
4497 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4498 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4499 SmallVector<SDValue, 8> Ops;
4500 for (unsigned i = 0; i < NumElts; ++i)
4501 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4502 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4503 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4509 // Gather data to see if the operation can be modelled as a
4510 // shuffle in combination with VEXTs.
4511 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4512 SelectionDAG &DAG) const {
4513 DebugLoc dl = Op.getDebugLoc();
4514 EVT VT = Op.getValueType();
4515 unsigned NumElts = VT.getVectorNumElements();
4517 SmallVector<SDValue, 2> SourceVecs;
4518 SmallVector<unsigned, 2> MinElts;
4519 SmallVector<unsigned, 2> MaxElts;
4521 for (unsigned i = 0; i < NumElts; ++i) {
4522 SDValue V = Op.getOperand(i);
4523 if (V.getOpcode() == ISD::UNDEF)
4525 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4526 // A shuffle can only come from building a vector from various
4527 // elements of other vectors.
4529 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4530 VT.getVectorElementType()) {
4531 // This code doesn't know how to handle shuffles where the vector
4532 // element types do not match (this happens because type legalization
4533 // promotes the return type of EXTRACT_VECTOR_ELT).
4534 // FIXME: It might be appropriate to extend this code to handle
4535 // mismatched types.
4539 // Record this extraction against the appropriate vector if possible...
4540 SDValue SourceVec = V.getOperand(0);
4541 // If the element number isn't a constant, we can't effectively
4542 // analyze what's going on.
4543 if (!isa<ConstantSDNode>(V.getOperand(1)))
4545 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4546 bool FoundSource = false;
4547 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4548 if (SourceVecs[j] == SourceVec) {
4549 if (MinElts[j] > EltNo)
4551 if (MaxElts[j] < EltNo)
4558 // Or record a new source if not...
4560 SourceVecs.push_back(SourceVec);
4561 MinElts.push_back(EltNo);
4562 MaxElts.push_back(EltNo);
4566 // Currently only do something sane when at most two source vectors
4568 if (SourceVecs.size() > 2)
4571 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4572 int VEXTOffsets[2] = {0, 0};
4574 // This loop extracts the usage patterns of the source vectors
4575 // and prepares appropriate SDValues for a shuffle if possible.
4576 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4577 if (SourceVecs[i].getValueType() == VT) {
4578 // No VEXT necessary
4579 ShuffleSrcs[i] = SourceVecs[i];
4582 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4583 // It probably isn't worth padding out a smaller vector just to
4584 // break it down again in a shuffle.
4588 // Since only 64-bit and 128-bit vectors are legal on ARM and
4589 // we've eliminated the other cases...
4590 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4591 "unexpected vector sizes in ReconstructShuffle");
4593 if (MaxElts[i] - MinElts[i] >= NumElts) {
4594 // Span too large for a VEXT to cope
4598 if (MinElts[i] >= NumElts) {
4599 // The extraction can just take the second half
4600 VEXTOffsets[i] = NumElts;
4601 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4603 DAG.getIntPtrConstant(NumElts));
4604 } else if (MaxElts[i] < NumElts) {
4605 // The extraction can just take the first half
4607 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4609 DAG.getIntPtrConstant(0));
4611 // An actual VEXT is needed
4612 VEXTOffsets[i] = MinElts[i];
4613 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4615 DAG.getIntPtrConstant(0));
4616 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4618 DAG.getIntPtrConstant(NumElts));
4619 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4620 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4624 SmallVector<int, 8> Mask;
4626 for (unsigned i = 0; i < NumElts; ++i) {
4627 SDValue Entry = Op.getOperand(i);
4628 if (Entry.getOpcode() == ISD::UNDEF) {
4633 SDValue ExtractVec = Entry.getOperand(0);
4634 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4635 .getOperand(1))->getSExtValue();
4636 if (ExtractVec == SourceVecs[0]) {
4637 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4639 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4643 // Final check before we try to produce nonsense...
4644 if (isShuffleMaskLegal(Mask, VT))
4645 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4651 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4652 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4653 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4654 /// are assumed to be legal.
4656 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4658 if (VT.getVectorNumElements() == 4 &&
4659 (VT.is128BitVector() || VT.is64BitVector())) {
4660 unsigned PFIndexes[4];
4661 for (unsigned i = 0; i != 4; ++i) {
4665 PFIndexes[i] = M[i];
4668 // Compute the index in the perfect shuffle table.
4669 unsigned PFTableIndex =
4670 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4671 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4672 unsigned Cost = (PFEntry >> 30);
4679 unsigned Imm, WhichResult;
4681 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4682 return (EltSize >= 32 ||
4683 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4684 isVREVMask(M, VT, 64) ||
4685 isVREVMask(M, VT, 32) ||
4686 isVREVMask(M, VT, 16) ||
4687 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4688 isVTBLMask(M, VT) ||
4689 isVTRNMask(M, VT, WhichResult) ||
4690 isVUZPMask(M, VT, WhichResult) ||
4691 isVZIPMask(M, VT, WhichResult) ||
4692 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4693 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4694 isVZIP_v_undef_Mask(M, VT, WhichResult));
4697 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4698 /// the specified operations to build the shuffle.
4699 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4700 SDValue RHS, SelectionDAG &DAG,
4702 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4703 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4704 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4707 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4716 OP_VUZPL, // VUZP, left result
4717 OP_VUZPR, // VUZP, right result
4718 OP_VZIPL, // VZIP, left result
4719 OP_VZIPR, // VZIP, right result
4720 OP_VTRNL, // VTRN, left result
4721 OP_VTRNR // VTRN, right result
4724 if (OpNum == OP_COPY) {
4725 if (LHSID == (1*9+2)*9+3) return LHS;
4726 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4730 SDValue OpLHS, OpRHS;
4731 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4732 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4733 EVT VT = OpLHS.getValueType();
4736 default: llvm_unreachable("Unknown shuffle opcode!");
4738 // VREV divides the vector in half and swaps within the half.
4739 if (VT.getVectorElementType() == MVT::i32 ||
4740 VT.getVectorElementType() == MVT::f32)
4741 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4742 // vrev <4 x i16> -> VREV32
4743 if (VT.getVectorElementType() == MVT::i16)
4744 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4745 // vrev <4 x i8> -> VREV16
4746 assert(VT.getVectorElementType() == MVT::i8);
4747 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4752 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4753 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4757 return DAG.getNode(ARMISD::VEXT, dl, VT,
4759 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4762 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4763 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4766 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4767 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4770 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4771 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4775 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4776 ArrayRef<int> ShuffleMask,
4777 SelectionDAG &DAG) {
4778 // Check to see if we can use the VTBL instruction.
4779 SDValue V1 = Op.getOperand(0);
4780 SDValue V2 = Op.getOperand(1);
4781 DebugLoc DL = Op.getDebugLoc();
4783 SmallVector<SDValue, 8> VTBLMask;
4784 for (ArrayRef<int>::iterator
4785 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4786 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4788 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4789 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4790 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4793 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4794 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4798 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4799 SDValue V1 = Op.getOperand(0);
4800 SDValue V2 = Op.getOperand(1);
4801 DebugLoc dl = Op.getDebugLoc();
4802 EVT VT = Op.getValueType();
4803 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4805 // Convert shuffles that are directly supported on NEON to target-specific
4806 // DAG nodes, instead of keeping them as shuffles and matching them again
4807 // during code selection. This is more efficient and avoids the possibility
4808 // of inconsistencies between legalization and selection.
4809 // FIXME: floating-point vectors should be canonicalized to integer vectors
4810 // of the same time so that they get CSEd properly.
4811 ArrayRef<int> ShuffleMask = SVN->getMask();
4813 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4814 if (EltSize <= 32) {
4815 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4816 int Lane = SVN->getSplatIndex();
4817 // If this is undef splat, generate it via "just" vdup, if possible.
4818 if (Lane == -1) Lane = 0;
4820 // Test if V1 is a SCALAR_TO_VECTOR.
4821 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4822 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4824 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4825 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4827 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4828 !isa<ConstantSDNode>(V1.getOperand(0))) {
4829 bool IsScalarToVector = true;
4830 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4831 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4832 IsScalarToVector = false;
4835 if (IsScalarToVector)
4836 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4838 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4839 DAG.getConstant(Lane, MVT::i32));
4844 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4847 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4848 DAG.getConstant(Imm, MVT::i32));
4851 if (isVREVMask(ShuffleMask, VT, 64))
4852 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4853 if (isVREVMask(ShuffleMask, VT, 32))
4854 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4855 if (isVREVMask(ShuffleMask, VT, 16))
4856 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4858 if (V2->getOpcode() == ISD::UNDEF &&
4859 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4860 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4861 DAG.getConstant(Imm, MVT::i32));
4864 // Check for Neon shuffles that modify both input vectors in place.
4865 // If both results are used, i.e., if there are two shuffles with the same
4866 // source operands and with masks corresponding to both results of one of
4867 // these operations, DAG memoization will ensure that a single node is
4868 // used for both shuffles.
4869 unsigned WhichResult;
4870 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4871 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4872 V1, V2).getValue(WhichResult);
4873 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4874 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4875 V1, V2).getValue(WhichResult);
4876 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4877 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4878 V1, V2).getValue(WhichResult);
4880 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4881 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4882 V1, V1).getValue(WhichResult);
4883 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4884 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4885 V1, V1).getValue(WhichResult);
4886 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4887 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4888 V1, V1).getValue(WhichResult);
4891 // If the shuffle is not directly supported and it has 4 elements, use
4892 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4893 unsigned NumElts = VT.getVectorNumElements();
4895 unsigned PFIndexes[4];
4896 for (unsigned i = 0; i != 4; ++i) {
4897 if (ShuffleMask[i] < 0)
4900 PFIndexes[i] = ShuffleMask[i];
4903 // Compute the index in the perfect shuffle table.
4904 unsigned PFTableIndex =
4905 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4906 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4907 unsigned Cost = (PFEntry >> 30);
4910 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4913 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4914 if (EltSize >= 32) {
4915 // Do the expansion with floating-point types, since that is what the VFP
4916 // registers are defined to use, and since i64 is not legal.
4917 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4918 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4919 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4920 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4921 SmallVector<SDValue, 8> Ops;
4922 for (unsigned i = 0; i < NumElts; ++i) {
4923 if (ShuffleMask[i] < 0)
4924 Ops.push_back(DAG.getUNDEF(EltVT));
4926 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4927 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4928 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4931 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4932 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4935 if (VT == MVT::v8i8) {
4936 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4937 if (NewOp.getNode())
4944 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4945 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4946 SDValue Lane = Op.getOperand(2);
4947 if (!isa<ConstantSDNode>(Lane))
4953 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4954 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4955 SDValue Lane = Op.getOperand(1);
4956 if (!isa<ConstantSDNode>(Lane))
4959 SDValue Vec = Op.getOperand(0);
4960 if (Op.getValueType() == MVT::i32 &&
4961 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4962 DebugLoc dl = Op.getDebugLoc();
4963 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4969 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4970 // The only time a CONCAT_VECTORS operation can have legal types is when
4971 // two 64-bit vectors are concatenated to a 128-bit vector.
4972 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4973 "unexpected CONCAT_VECTORS");
4974 DebugLoc dl = Op.getDebugLoc();
4975 SDValue Val = DAG.getUNDEF(MVT::v2f64);
4976 SDValue Op0 = Op.getOperand(0);
4977 SDValue Op1 = Op.getOperand(1);
4978 if (Op0.getOpcode() != ISD::UNDEF)
4979 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4980 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4981 DAG.getIntPtrConstant(0));
4982 if (Op1.getOpcode() != ISD::UNDEF)
4983 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4984 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4985 DAG.getIntPtrConstant(1));
4986 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4989 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4990 /// element has been zero/sign-extended, depending on the isSigned parameter,
4991 /// from an integer type half its size.
4992 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4994 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4995 EVT VT = N->getValueType(0);
4996 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4997 SDNode *BVN = N->getOperand(0).getNode();
4998 if (BVN->getValueType(0) != MVT::v4i32 ||
4999 BVN->getOpcode() != ISD::BUILD_VECTOR)
5001 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5002 unsigned HiElt = 1 - LoElt;
5003 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5004 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5005 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5006 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5007 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5010 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5011 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5014 if (Hi0->isNullValue() && Hi1->isNullValue())
5020 if (N->getOpcode() != ISD::BUILD_VECTOR)
5023 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5024 SDNode *Elt = N->getOperand(i).getNode();
5025 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5026 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5027 unsigned HalfSize = EltSize / 2;
5029 if (!isIntN(HalfSize, C->getSExtValue()))
5032 if (!isUIntN(HalfSize, C->getZExtValue()))
5043 /// isSignExtended - Check if a node is a vector value that is sign-extended
5044 /// or a constant BUILD_VECTOR with sign-extended elements.
5045 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5046 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5048 if (isExtendedBUILD_VECTOR(N, DAG, true))
5053 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5054 /// or a constant BUILD_VECTOR with zero-extended elements.
5055 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5056 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5058 if (isExtendedBUILD_VECTOR(N, DAG, false))
5063 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5064 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5065 /// We insert the required extension here to get the vector to fill a D register.
5066 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5069 unsigned ExtOpcode) {
5070 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5071 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5072 // 64-bits we need to insert a new extension so that it will be 64-bits.
5073 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5074 if (OrigTy.getSizeInBits() >= 64)
5077 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5078 MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5080 switch (OrigSimpleTy) {
5081 default: llvm_unreachable("Unexpected Orig Vector Type");
5090 return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5093 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5094 /// does not do any sign/zero extension. If the original vector is less
5095 /// than 64 bits, an appropriate extension will be added after the load to
5096 /// reach a total size of 64 bits. We have to add the extension separately
5097 /// because ARM does not have a sign/zero extending load for vectors.
5098 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5099 SDValue NonExtendingLoad =
5100 DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5101 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5102 LD->isNonTemporal(), LD->isInvariant(),
5103 LD->getAlignment());
5105 switch (LD->getExtensionType()) {
5106 default: llvm_unreachable("Unexpected LoadExtType");
5108 case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5109 case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5111 MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5112 MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5113 return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5114 MemType, ExtType, ExtOp);
5117 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5118 /// extending load, or BUILD_VECTOR with extended elements, return the
5119 /// unextended value. The unextended vector should be 64 bits so that it can
5120 /// be used as an operand to a VMULL instruction. If the original vector size
5121 /// before extension is less than 64 bits we add a an extension to resize
5122 /// the vector to 64 bits.
5123 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5124 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5125 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5126 N->getOperand(0)->getValueType(0),
5130 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5131 return SkipLoadExtensionForVMULL(LD, DAG);
5133 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5134 // have been legalized as a BITCAST from v4i32.
5135 if (N->getOpcode() == ISD::BITCAST) {
5136 SDNode *BVN = N->getOperand(0).getNode();
5137 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5138 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5139 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5140 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5141 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5143 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5144 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5145 EVT VT = N->getValueType(0);
5146 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5147 unsigned NumElts = VT.getVectorNumElements();
5148 MVT TruncVT = MVT::getIntegerVT(EltSize);
5149 SmallVector<SDValue, 8> Ops;
5150 for (unsigned i = 0; i != NumElts; ++i) {
5151 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5152 const APInt &CInt = C->getAPIntValue();
5153 // Element types smaller than 32 bits are not legal, so use i32 elements.
5154 // The values are implicitly truncated so sext vs. zext doesn't matter.
5155 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5157 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5158 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5161 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5162 unsigned Opcode = N->getOpcode();
5163 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5164 SDNode *N0 = N->getOperand(0).getNode();
5165 SDNode *N1 = N->getOperand(1).getNode();
5166 return N0->hasOneUse() && N1->hasOneUse() &&
5167 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5172 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5173 unsigned Opcode = N->getOpcode();
5174 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5175 SDNode *N0 = N->getOperand(0).getNode();
5176 SDNode *N1 = N->getOperand(1).getNode();
5177 return N0->hasOneUse() && N1->hasOneUse() &&
5178 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5183 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5184 // Multiplications are only custom-lowered for 128-bit vectors so that
5185 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5186 EVT VT = Op.getValueType();
5187 assert(VT.is128BitVector() && VT.isInteger() &&
5188 "unexpected type for custom-lowering ISD::MUL");
5189 SDNode *N0 = Op.getOperand(0).getNode();
5190 SDNode *N1 = Op.getOperand(1).getNode();
5191 unsigned NewOpc = 0;
5193 bool isN0SExt = isSignExtended(N0, DAG);
5194 bool isN1SExt = isSignExtended(N1, DAG);
5195 if (isN0SExt && isN1SExt)
5196 NewOpc = ARMISD::VMULLs;
5198 bool isN0ZExt = isZeroExtended(N0, DAG);
5199 bool isN1ZExt = isZeroExtended(N1, DAG);
5200 if (isN0ZExt && isN1ZExt)
5201 NewOpc = ARMISD::VMULLu;
5202 else if (isN1SExt || isN1ZExt) {
5203 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5204 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5205 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5206 NewOpc = ARMISD::VMULLs;
5208 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5209 NewOpc = ARMISD::VMULLu;
5211 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5213 NewOpc = ARMISD::VMULLu;
5219 if (VT == MVT::v2i64)
5220 // Fall through to expand this. It is not legal.
5223 // Other vector multiplications are legal.
5228 // Legalize to a VMULL instruction.
5229 DebugLoc DL = Op.getDebugLoc();
5231 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5233 Op0 = SkipExtensionForVMULL(N0, DAG);
5234 assert(Op0.getValueType().is64BitVector() &&
5235 Op1.getValueType().is64BitVector() &&
5236 "unexpected types for extended operands to VMULL");
5237 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5240 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5241 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5248 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5249 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5250 EVT Op1VT = Op1.getValueType();
5251 return DAG.getNode(N0->getOpcode(), DL, VT,
5252 DAG.getNode(NewOpc, DL, VT,
5253 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5254 DAG.getNode(NewOpc, DL, VT,
5255 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5259 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5261 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5262 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5263 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5264 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5265 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5266 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5267 // Get reciprocal estimate.
5268 // float4 recip = vrecpeq_f32(yf);
5269 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5270 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5271 // Because char has a smaller range than uchar, we can actually get away
5272 // without any newton steps. This requires that we use a weird bias
5273 // of 0xb000, however (again, this has been exhaustively tested).
5274 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5275 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5276 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5277 Y = DAG.getConstant(0xb000, MVT::i32);
5278 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5279 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5280 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5281 // Convert back to short.
5282 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5283 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5288 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5290 // Convert to float.
5291 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5292 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5293 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5294 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5295 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5296 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5298 // Use reciprocal estimate and one refinement step.
5299 // float4 recip = vrecpeq_f32(yf);
5300 // recip *= vrecpsq_f32(yf, recip);
5301 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5302 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5303 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5304 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5306 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5307 // Because short has a smaller range than ushort, we can actually get away
5308 // with only a single newton step. This requires that we use a weird bias
5309 // of 89, however (again, this has been exhaustively tested).
5310 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5311 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5312 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5313 N1 = DAG.getConstant(0x89, MVT::i32);
5314 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5315 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5316 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5317 // Convert back to integer and return.
5318 // return vmovn_s32(vcvt_s32_f32(result));
5319 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5320 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5324 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5325 EVT VT = Op.getValueType();
5326 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5327 "unexpected type for custom-lowering ISD::SDIV");
5329 DebugLoc dl = Op.getDebugLoc();
5330 SDValue N0 = Op.getOperand(0);
5331 SDValue N1 = Op.getOperand(1);
5334 if (VT == MVT::v8i8) {
5335 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5336 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5338 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5339 DAG.getIntPtrConstant(4));
5340 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5341 DAG.getIntPtrConstant(4));
5342 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5343 DAG.getIntPtrConstant(0));
5344 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5345 DAG.getIntPtrConstant(0));
5347 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5348 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5350 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5351 N0 = LowerCONCAT_VECTORS(N0, DAG);
5353 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5356 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5359 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5360 EVT VT = Op.getValueType();
5361 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5362 "unexpected type for custom-lowering ISD::UDIV");
5364 DebugLoc dl = Op.getDebugLoc();
5365 SDValue N0 = Op.getOperand(0);
5366 SDValue N1 = Op.getOperand(1);
5369 if (VT == MVT::v8i8) {
5370 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5371 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5373 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5374 DAG.getIntPtrConstant(4));
5375 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5376 DAG.getIntPtrConstant(4));
5377 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5378 DAG.getIntPtrConstant(0));
5379 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5380 DAG.getIntPtrConstant(0));
5382 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5383 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5385 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5386 N0 = LowerCONCAT_VECTORS(N0, DAG);
5388 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5389 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5394 // v4i16 sdiv ... Convert to float.
5395 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5396 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5397 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5398 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5399 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5400 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5402 // Use reciprocal estimate and two refinement steps.
5403 // float4 recip = vrecpeq_f32(yf);
5404 // recip *= vrecpsq_f32(yf, recip);
5405 // recip *= vrecpsq_f32(yf, recip);
5406 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5407 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5408 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5409 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5411 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5412 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5413 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5415 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5416 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5417 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5418 // and that it will never cause us to return an answer too large).
5419 // float4 result = as_float4(as_int4(xf*recip) + 2);
5420 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5421 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5422 N1 = DAG.getConstant(2, MVT::i32);
5423 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5424 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5425 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5426 // Convert back to integer and return.
5427 // return vmovn_u32(vcvt_s32_f32(result));
5428 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5429 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5433 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5434 EVT VT = Op.getNode()->getValueType(0);
5435 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5438 bool ExtraOp = false;
5439 switch (Op.getOpcode()) {
5440 default: llvm_unreachable("Invalid code");
5441 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5442 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5443 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5444 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5448 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5450 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5451 Op.getOperand(1), Op.getOperand(2));
5454 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5455 // Monotonic load/store is legal for all targets
5456 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5459 // Aquire/Release load/store is not legal for targets without a
5460 // dmb or equivalent available.
5466 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5467 SelectionDAG &DAG, unsigned NewOp) {
5468 DebugLoc dl = Node->getDebugLoc();
5469 assert (Node->getValueType(0) == MVT::i64 &&
5470 "Only know how to expand i64 atomics");
5472 SmallVector<SDValue, 6> Ops;
5473 Ops.push_back(Node->getOperand(0)); // Chain
5474 Ops.push_back(Node->getOperand(1)); // Ptr
5476 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5477 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5478 // High part of Val1
5479 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5480 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5481 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5482 // High part of Val1
5483 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5484 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5485 // High part of Val2
5486 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5487 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5489 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5491 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5492 cast<MemSDNode>(Node)->getMemOperand());
5493 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5494 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5495 Results.push_back(Result.getValue(2));
5498 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5499 switch (Op.getOpcode()) {
5500 default: llvm_unreachable("Don't know how to custom lower this!");
5501 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5502 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5503 case ISD::GlobalAddress:
5504 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5505 LowerGlobalAddressELF(Op, DAG);
5506 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5507 case ISD::SELECT: return LowerSELECT(Op, DAG);
5508 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5509 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5510 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5511 case ISD::VASTART: return LowerVASTART(Op, DAG);
5512 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5513 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5514 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5515 case ISD::SINT_TO_FP:
5516 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5517 case ISD::FP_TO_SINT:
5518 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5519 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5520 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5521 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5522 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5523 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5524 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5525 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5527 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5530 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5531 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5532 case ISD::SRL_PARTS:
5533 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5534 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5535 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5536 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5537 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5538 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5539 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5540 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5541 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5542 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5543 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5544 case ISD::MUL: return LowerMUL(Op, DAG);
5545 case ISD::SDIV: return LowerSDIV(Op, DAG);
5546 case ISD::UDIV: return LowerUDIV(Op, DAG);
5550 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5551 case ISD::ATOMIC_LOAD:
5552 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5556 /// ReplaceNodeResults - Replace the results of node with an illegal result
5557 /// type with new values built out of custom code.
5558 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5559 SmallVectorImpl<SDValue>&Results,
5560 SelectionDAG &DAG) const {
5562 switch (N->getOpcode()) {
5564 llvm_unreachable("Don't know how to custom expand this!");
5566 Res = ExpandBITCAST(N, DAG);
5570 Res = Expand64BitShift(N, DAG, Subtarget);
5572 case ISD::ATOMIC_LOAD_ADD:
5573 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5575 case ISD::ATOMIC_LOAD_AND:
5576 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5578 case ISD::ATOMIC_LOAD_NAND:
5579 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5581 case ISD::ATOMIC_LOAD_OR:
5582 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5584 case ISD::ATOMIC_LOAD_SUB:
5585 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5587 case ISD::ATOMIC_LOAD_XOR:
5588 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5590 case ISD::ATOMIC_SWAP:
5591 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5593 case ISD::ATOMIC_CMP_SWAP:
5594 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5596 case ISD::ATOMIC_LOAD_MIN:
5597 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5599 case ISD::ATOMIC_LOAD_UMIN:
5600 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5602 case ISD::ATOMIC_LOAD_MAX:
5603 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5605 case ISD::ATOMIC_LOAD_UMAX:
5606 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5610 Results.push_back(Res);
5613 //===----------------------------------------------------------------------===//
5614 // ARM Scheduler Hooks
5615 //===----------------------------------------------------------------------===//
5618 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5619 MachineBasicBlock *BB,
5620 unsigned Size) const {
5621 unsigned dest = MI->getOperand(0).getReg();
5622 unsigned ptr = MI->getOperand(1).getReg();
5623 unsigned oldval = MI->getOperand(2).getReg();
5624 unsigned newval = MI->getOperand(3).getReg();
5625 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5626 DebugLoc dl = MI->getDebugLoc();
5627 bool isThumb2 = Subtarget->isThumb2();
5629 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5630 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5631 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5632 (const TargetRegisterClass*)&ARM::GPRRegClass);
5635 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5636 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5637 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5640 unsigned ldrOpc, strOpc;
5642 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5644 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5645 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5648 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5649 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5652 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5653 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5657 MachineFunction *MF = BB->getParent();
5658 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5659 MachineFunction::iterator It = BB;
5660 ++It; // insert the new blocks after the current block
5662 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5663 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5664 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5665 MF->insert(It, loop1MBB);
5666 MF->insert(It, loop2MBB);
5667 MF->insert(It, exitMBB);
5669 // Transfer the remainder of BB and its successor edges to exitMBB.
5670 exitMBB->splice(exitMBB->begin(), BB,
5671 llvm::next(MachineBasicBlock::iterator(MI)),
5673 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5677 // fallthrough --> loop1MBB
5678 BB->addSuccessor(loop1MBB);
5681 // ldrex dest, [ptr]
5685 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5686 if (ldrOpc == ARM::t2LDREX)
5688 AddDefaultPred(MIB);
5689 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5690 .addReg(dest).addReg(oldval));
5691 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5692 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5693 BB->addSuccessor(loop2MBB);
5694 BB->addSuccessor(exitMBB);
5697 // strex scratch, newval, [ptr]
5701 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5702 if (strOpc == ARM::t2STREX)
5704 AddDefaultPred(MIB);
5705 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5706 .addReg(scratch).addImm(0));
5707 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5708 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5709 BB->addSuccessor(loop1MBB);
5710 BB->addSuccessor(exitMBB);
5716 MI->eraseFromParent(); // The instruction is gone now.
5722 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5723 unsigned Size, unsigned BinOpcode) const {
5724 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5725 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5727 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5728 MachineFunction *MF = BB->getParent();
5729 MachineFunction::iterator It = BB;
5732 unsigned dest = MI->getOperand(0).getReg();
5733 unsigned ptr = MI->getOperand(1).getReg();
5734 unsigned incr = MI->getOperand(2).getReg();
5735 DebugLoc dl = MI->getDebugLoc();
5736 bool isThumb2 = Subtarget->isThumb2();
5738 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5740 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5741 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5744 unsigned ldrOpc, strOpc;
5746 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5748 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5749 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5752 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5753 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5756 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5757 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5761 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5762 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5763 MF->insert(It, loopMBB);
5764 MF->insert(It, exitMBB);
5766 // Transfer the remainder of BB and its successor edges to exitMBB.
5767 exitMBB->splice(exitMBB->begin(), BB,
5768 llvm::next(MachineBasicBlock::iterator(MI)),
5770 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5772 const TargetRegisterClass *TRC = isThumb2 ?
5773 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5774 (const TargetRegisterClass*)&ARM::GPRRegClass;
5775 unsigned scratch = MRI.createVirtualRegister(TRC);
5776 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5780 // fallthrough --> loopMBB
5781 BB->addSuccessor(loopMBB);
5785 // <binop> scratch2, dest, incr
5786 // strex scratch, scratch2, ptr
5789 // fallthrough --> exitMBB
5791 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5792 if (ldrOpc == ARM::t2LDREX)
5794 AddDefaultPred(MIB);
5796 // operand order needs to go the other way for NAND
5797 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5798 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5799 addReg(incr).addReg(dest)).addReg(0);
5801 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5802 addReg(dest).addReg(incr)).addReg(0);
5805 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5806 if (strOpc == ARM::t2STREX)
5808 AddDefaultPred(MIB);
5809 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5810 .addReg(scratch).addImm(0));
5811 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5812 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5814 BB->addSuccessor(loopMBB);
5815 BB->addSuccessor(exitMBB);
5821 MI->eraseFromParent(); // The instruction is gone now.
5827 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5828 MachineBasicBlock *BB,
5831 ARMCC::CondCodes Cond) const {
5832 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5834 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5835 MachineFunction *MF = BB->getParent();
5836 MachineFunction::iterator It = BB;
5839 unsigned dest = MI->getOperand(0).getReg();
5840 unsigned ptr = MI->getOperand(1).getReg();
5841 unsigned incr = MI->getOperand(2).getReg();
5842 unsigned oldval = dest;
5843 DebugLoc dl = MI->getDebugLoc();
5844 bool isThumb2 = Subtarget->isThumb2();
5846 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5848 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5849 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5852 unsigned ldrOpc, strOpc, extendOpc;
5854 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5856 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5857 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5858 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5861 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5862 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5863 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5866 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5867 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5872 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5873 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5874 MF->insert(It, loopMBB);
5875 MF->insert(It, exitMBB);
5877 // Transfer the remainder of BB and its successor edges to exitMBB.
5878 exitMBB->splice(exitMBB->begin(), BB,
5879 llvm::next(MachineBasicBlock::iterator(MI)),
5881 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5883 const TargetRegisterClass *TRC = isThumb2 ?
5884 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5885 (const TargetRegisterClass*)&ARM::GPRRegClass;
5886 unsigned scratch = MRI.createVirtualRegister(TRC);
5887 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5891 // fallthrough --> loopMBB
5892 BB->addSuccessor(loopMBB);
5896 // (sign extend dest, if required)
5898 // cmov.cond scratch2, incr, dest
5899 // strex scratch, scratch2, ptr
5902 // fallthrough --> exitMBB
5904 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5905 if (ldrOpc == ARM::t2LDREX)
5907 AddDefaultPred(MIB);
5909 // Sign extend the value, if necessary.
5910 if (signExtend && extendOpc) {
5911 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5912 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5917 // Build compare and cmov instructions.
5918 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5919 .addReg(oldval).addReg(incr));
5920 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5921 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5923 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5924 if (strOpc == ARM::t2STREX)
5926 AddDefaultPred(MIB);
5927 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5928 .addReg(scratch).addImm(0));
5929 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5930 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5932 BB->addSuccessor(loopMBB);
5933 BB->addSuccessor(exitMBB);
5939 MI->eraseFromParent(); // The instruction is gone now.
5945 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5946 unsigned Op1, unsigned Op2,
5947 bool NeedsCarry, bool IsCmpxchg,
5948 bool IsMinMax, ARMCC::CondCodes CC) const {
5949 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5950 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5952 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5953 MachineFunction *MF = BB->getParent();
5954 MachineFunction::iterator It = BB;
5957 unsigned destlo = MI->getOperand(0).getReg();
5958 unsigned desthi = MI->getOperand(1).getReg();
5959 unsigned ptr = MI->getOperand(2).getReg();
5960 unsigned vallo = MI->getOperand(3).getReg();
5961 unsigned valhi = MI->getOperand(4).getReg();
5962 DebugLoc dl = MI->getDebugLoc();
5963 bool isThumb2 = Subtarget->isThumb2();
5965 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5967 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5968 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5969 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5972 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5973 MachineBasicBlock *contBB = 0, *cont2BB = 0;
5974 if (IsCmpxchg || IsMinMax)
5975 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5977 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5978 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5980 MF->insert(It, loopMBB);
5981 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
5982 if (IsCmpxchg) MF->insert(It, cont2BB);
5983 MF->insert(It, exitMBB);
5985 // Transfer the remainder of BB and its successor edges to exitMBB.
5986 exitMBB->splice(exitMBB->begin(), BB,
5987 llvm::next(MachineBasicBlock::iterator(MI)),
5989 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5991 const TargetRegisterClass *TRC = isThumb2 ?
5992 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5993 (const TargetRegisterClass*)&ARM::GPRRegClass;
5994 unsigned storesuccess = MRI.createVirtualRegister(TRC);
5998 // fallthrough --> loopMBB
5999 BB->addSuccessor(loopMBB);
6002 // ldrexd r2, r3, ptr
6003 // <binopa> r0, r2, incr
6004 // <binopb> r1, r3, incr
6005 // strexd storesuccess, r0, r1, ptr
6006 // cmp storesuccess, #0
6008 // fallthrough --> exitMBB
6013 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6014 .addReg(destlo, RegState::Define)
6015 .addReg(desthi, RegState::Define)
6018 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6019 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6020 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6021 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6022 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6023 .addReg(GPRPair0, 0, ARM::gsub_0);
6024 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6025 .addReg(GPRPair0, 0, ARM::gsub_1);
6028 unsigned StoreLo, StoreHi;
6031 for (unsigned i = 0; i < 2; i++) {
6032 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6034 .addReg(i == 0 ? destlo : desthi)
6035 .addReg(i == 0 ? vallo : valhi));
6036 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6037 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6038 BB->addSuccessor(exitMBB);
6039 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6040 BB = (i == 0 ? contBB : cont2BB);
6043 // Copy to physregs for strexd
6044 StoreLo = MI->getOperand(5).getReg();
6045 StoreHi = MI->getOperand(6).getReg();
6047 // Perform binary operation
6048 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6049 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6050 .addReg(destlo).addReg(vallo))
6051 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6052 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6053 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6054 .addReg(desthi).addReg(valhi))
6055 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6060 // Copy to physregs for strexd
6065 // Compare and branch to exit block.
6066 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6067 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6068 BB->addSuccessor(exitMBB);
6069 BB->addSuccessor(contBB);
6077 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6078 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6080 // Marshal a pair...
6081 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6082 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6083 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6084 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6085 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6088 .addImm(ARM::gsub_0);
6089 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6092 .addImm(ARM::gsub_1);
6095 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6096 .addReg(StorePair).addReg(ptr));
6099 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6100 .addReg(storesuccess).addImm(0));
6101 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6102 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6104 BB->addSuccessor(loopMBB);
6105 BB->addSuccessor(exitMBB);
6111 MI->eraseFromParent(); // The instruction is gone now.
6116 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6117 /// registers the function context.
6118 void ARMTargetLowering::
6119 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6120 MachineBasicBlock *DispatchBB, int FI) const {
6121 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6122 DebugLoc dl = MI->getDebugLoc();
6123 MachineFunction *MF = MBB->getParent();
6124 MachineRegisterInfo *MRI = &MF->getRegInfo();
6125 MachineConstantPool *MCP = MF->getConstantPool();
6126 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6127 const Function *F = MF->getFunction();
6129 bool isThumb = Subtarget->isThumb();
6130 bool isThumb2 = Subtarget->isThumb2();
6132 unsigned PCLabelId = AFI->createPICLabelUId();
6133 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6134 ARMConstantPoolValue *CPV =
6135 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6136 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6138 const TargetRegisterClass *TRC = isThumb ?
6139 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6140 (const TargetRegisterClass*)&ARM::GPRRegClass;
6142 // Grab constant pool and fixed stack memory operands.
6143 MachineMemOperand *CPMMO =
6144 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6145 MachineMemOperand::MOLoad, 4, 4);
6147 MachineMemOperand *FIMMOSt =
6148 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6149 MachineMemOperand::MOStore, 4, 4);
6151 // Load the address of the dispatch MBB into the jump buffer.
6153 // Incoming value: jbuf
6154 // ldr.n r5, LCPI1_1
6157 // str r5, [$jbuf, #+4] ; &jbuf[1]
6158 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6159 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6160 .addConstantPoolIndex(CPI)
6161 .addMemOperand(CPMMO));
6162 // Set the low bit because of thumb mode.
6163 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6165 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6166 .addReg(NewVReg1, RegState::Kill)
6168 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6169 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6170 .addReg(NewVReg2, RegState::Kill)
6172 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6173 .addReg(NewVReg3, RegState::Kill)
6175 .addImm(36) // &jbuf[1] :: pc
6176 .addMemOperand(FIMMOSt));
6177 } else if (isThumb) {
6178 // Incoming value: jbuf
6179 // ldr.n r1, LCPI1_4
6183 // add r2, $jbuf, #+4 ; &jbuf[1]
6185 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6186 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6187 .addConstantPoolIndex(CPI)
6188 .addMemOperand(CPMMO));
6189 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6190 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6191 .addReg(NewVReg1, RegState::Kill)
6193 // Set the low bit because of thumb mode.
6194 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6195 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6196 .addReg(ARM::CPSR, RegState::Define)
6198 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6199 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6200 .addReg(ARM::CPSR, RegState::Define)
6201 .addReg(NewVReg2, RegState::Kill)
6202 .addReg(NewVReg3, RegState::Kill));
6203 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6204 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6206 .addImm(36)); // &jbuf[1] :: pc
6207 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6208 .addReg(NewVReg4, RegState::Kill)
6209 .addReg(NewVReg5, RegState::Kill)
6211 .addMemOperand(FIMMOSt));
6213 // Incoming value: jbuf
6216 // str r1, [$jbuf, #+4] ; &jbuf[1]
6217 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6218 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6219 .addConstantPoolIndex(CPI)
6221 .addMemOperand(CPMMO));
6222 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6223 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6224 .addReg(NewVReg1, RegState::Kill)
6225 .addImm(PCLabelId));
6226 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6227 .addReg(NewVReg2, RegState::Kill)
6229 .addImm(36) // &jbuf[1] :: pc
6230 .addMemOperand(FIMMOSt));
6234 MachineBasicBlock *ARMTargetLowering::
6235 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6236 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6237 DebugLoc dl = MI->getDebugLoc();
6238 MachineFunction *MF = MBB->getParent();
6239 MachineRegisterInfo *MRI = &MF->getRegInfo();
6240 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6241 MachineFrameInfo *MFI = MF->getFrameInfo();
6242 int FI = MFI->getFunctionContextIndex();
6244 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6245 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6246 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6248 // Get a mapping of the call site numbers to all of the landing pads they're
6250 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6251 unsigned MaxCSNum = 0;
6252 MachineModuleInfo &MMI = MF->getMMI();
6253 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6255 if (!BB->isLandingPad()) continue;
6257 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6259 for (MachineBasicBlock::iterator
6260 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6261 if (!II->isEHLabel()) continue;
6263 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6264 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6266 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6267 for (SmallVectorImpl<unsigned>::iterator
6268 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6269 CSI != CSE; ++CSI) {
6270 CallSiteNumToLPad[*CSI].push_back(BB);
6271 MaxCSNum = std::max(MaxCSNum, *CSI);
6277 // Get an ordered list of the machine basic blocks for the jump table.
6278 std::vector<MachineBasicBlock*> LPadList;
6279 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6280 LPadList.reserve(CallSiteNumToLPad.size());
6281 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6282 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6283 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6284 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6285 LPadList.push_back(*II);
6286 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6290 assert(!LPadList.empty() &&
6291 "No landing pad destinations for the dispatch jump table!");
6293 // Create the jump table and associated information.
6294 MachineJumpTableInfo *JTI =
6295 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6296 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6297 unsigned UId = AFI->createJumpTableUId();
6299 // Create the MBBs for the dispatch code.
6301 // Shove the dispatch's address into the return slot in the function context.
6302 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6303 DispatchBB->setIsLandingPad();
6305 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6306 unsigned trap_opcode;
6307 if (Subtarget->isThumb()) {
6308 trap_opcode = ARM::tTRAP;
6310 if (Subtarget->useNaClTrap())
6311 trap_opcode = ARM::TRAPNaCl;
6313 trap_opcode = ARM::TRAP;
6315 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6316 DispatchBB->addSuccessor(TrapBB);
6318 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6319 DispatchBB->addSuccessor(DispContBB);
6322 MF->insert(MF->end(), DispatchBB);
6323 MF->insert(MF->end(), DispContBB);
6324 MF->insert(MF->end(), TrapBB);
6326 // Insert code into the entry block that creates and registers the function
6328 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6330 MachineMemOperand *FIMMOLd =
6331 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6332 MachineMemOperand::MOLoad |
6333 MachineMemOperand::MOVolatile, 4, 4);
6335 MachineInstrBuilder MIB;
6336 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6338 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6339 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6341 // Add a register mask with no preserved registers. This results in all
6342 // registers being marked as clobbered.
6343 MIB.addRegMask(RI.getNoPreservedMask());
6345 unsigned NumLPads = LPadList.size();
6346 if (Subtarget->isThumb2()) {
6347 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6348 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6351 .addMemOperand(FIMMOLd));
6353 if (NumLPads < 256) {
6354 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6356 .addImm(LPadList.size()));
6358 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6359 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6360 .addImm(NumLPads & 0xFFFF));
6362 unsigned VReg2 = VReg1;
6363 if ((NumLPads & 0xFFFF0000) != 0) {
6364 VReg2 = MRI->createVirtualRegister(TRC);
6365 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6367 .addImm(NumLPads >> 16));
6370 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6375 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6380 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6381 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6382 .addJumpTableIndex(MJTI)
6385 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6388 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6389 .addReg(NewVReg3, RegState::Kill)
6391 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6393 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6394 .addReg(NewVReg4, RegState::Kill)
6396 .addJumpTableIndex(MJTI)
6398 } else if (Subtarget->isThumb()) {
6399 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6400 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6403 .addMemOperand(FIMMOLd));
6405 if (NumLPads < 256) {
6406 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6410 MachineConstantPool *ConstantPool = MF->getConstantPool();
6411 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6412 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6414 // MachineConstantPool wants an explicit alignment.
6415 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6417 Align = getDataLayout()->getTypeAllocSize(C->getType());
6418 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6420 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6421 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6422 .addReg(VReg1, RegState::Define)
6423 .addConstantPoolIndex(Idx));
6424 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6429 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6434 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6435 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6436 .addReg(ARM::CPSR, RegState::Define)
6440 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6441 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6442 .addJumpTableIndex(MJTI)
6445 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6446 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6447 .addReg(ARM::CPSR, RegState::Define)
6448 .addReg(NewVReg2, RegState::Kill)
6451 MachineMemOperand *JTMMOLd =
6452 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6453 MachineMemOperand::MOLoad, 4, 4);
6455 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6456 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6457 .addReg(NewVReg4, RegState::Kill)
6459 .addMemOperand(JTMMOLd));
6461 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6462 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6463 .addReg(ARM::CPSR, RegState::Define)
6464 .addReg(NewVReg5, RegState::Kill)
6467 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6468 .addReg(NewVReg6, RegState::Kill)
6469 .addJumpTableIndex(MJTI)
6472 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6473 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6476 .addMemOperand(FIMMOLd));
6478 if (NumLPads < 256) {
6479 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6482 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6483 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6484 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6485 .addImm(NumLPads & 0xFFFF));
6487 unsigned VReg2 = VReg1;
6488 if ((NumLPads & 0xFFFF0000) != 0) {
6489 VReg2 = MRI->createVirtualRegister(TRC);
6490 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6492 .addImm(NumLPads >> 16));
6495 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6499 MachineConstantPool *ConstantPool = MF->getConstantPool();
6500 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6501 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6503 // MachineConstantPool wants an explicit alignment.
6504 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6506 Align = getDataLayout()->getTypeAllocSize(C->getType());
6507 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6509 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6510 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6511 .addReg(VReg1, RegState::Define)
6512 .addConstantPoolIndex(Idx)
6514 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6516 .addReg(VReg1, RegState::Kill));
6519 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6524 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6526 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6528 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6529 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6530 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6531 .addJumpTableIndex(MJTI)
6534 MachineMemOperand *JTMMOLd =
6535 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6536 MachineMemOperand::MOLoad, 4, 4);
6537 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6539 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6540 .addReg(NewVReg3, RegState::Kill)
6543 .addMemOperand(JTMMOLd));
6545 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6546 .addReg(NewVReg5, RegState::Kill)
6548 .addJumpTableIndex(MJTI)
6552 // Add the jump table entries as successors to the MBB.
6553 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6554 for (std::vector<MachineBasicBlock*>::iterator
6555 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6556 MachineBasicBlock *CurMBB = *I;
6557 if (SeenMBBs.insert(CurMBB))
6558 DispContBB->addSuccessor(CurMBB);
6561 // N.B. the order the invoke BBs are processed in doesn't matter here.
6562 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6563 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6564 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6565 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6566 MachineBasicBlock *BB = *I;
6568 // Remove the landing pad successor from the invoke block and replace it
6569 // with the new dispatch block.
6570 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6572 while (!Successors.empty()) {
6573 MachineBasicBlock *SMBB = Successors.pop_back_val();
6574 if (SMBB->isLandingPad()) {
6575 BB->removeSuccessor(SMBB);
6576 MBBLPads.push_back(SMBB);
6580 BB->addSuccessor(DispatchBB);
6582 // Find the invoke call and mark all of the callee-saved registers as
6583 // 'implicit defined' so that they're spilled. This prevents code from
6584 // moving instructions to before the EH block, where they will never be
6586 for (MachineBasicBlock::reverse_iterator
6587 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6588 if (!II->isCall()) continue;
6590 DenseMap<unsigned, bool> DefRegs;
6591 for (MachineInstr::mop_iterator
6592 OI = II->operands_begin(), OE = II->operands_end();
6594 if (!OI->isReg()) continue;
6595 DefRegs[OI->getReg()] = true;
6598 MachineInstrBuilder MIB(*MF, &*II);
6600 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6601 unsigned Reg = SavedRegs[i];
6602 if (Subtarget->isThumb2() &&
6603 !ARM::tGPRRegClass.contains(Reg) &&
6604 !ARM::hGPRRegClass.contains(Reg))
6606 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6608 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6611 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6618 // Mark all former landing pads as non-landing pads. The dispatch is the only
6620 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6621 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6622 (*I)->setIsLandingPad(false);
6624 // The instruction is gone now.
6625 MI->eraseFromParent();
6631 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6632 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6633 E = MBB->succ_end(); I != E; ++I)
6636 llvm_unreachable("Expecting a BB with two successors!");
6639 MachineBasicBlock *ARMTargetLowering::
6640 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6641 // This pseudo instruction has 3 operands: dst, src, size
6642 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6643 // Otherwise, we will generate unrolled scalar copies.
6644 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6645 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6646 MachineFunction::iterator It = BB;
6649 unsigned dest = MI->getOperand(0).getReg();
6650 unsigned src = MI->getOperand(1).getReg();
6651 unsigned SizeVal = MI->getOperand(2).getImm();
6652 unsigned Align = MI->getOperand(3).getImm();
6653 DebugLoc dl = MI->getDebugLoc();
6655 bool isThumb2 = Subtarget->isThumb2();
6656 MachineFunction *MF = BB->getParent();
6657 MachineRegisterInfo &MRI = MF->getRegInfo();
6658 unsigned ldrOpc, strOpc, UnitSize = 0;
6660 const TargetRegisterClass *TRC = isThumb2 ?
6661 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6662 (const TargetRegisterClass*)&ARM::GPRRegClass;
6663 const TargetRegisterClass *TRC_Vec = 0;
6666 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6667 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6669 } else if (Align & 2) {
6670 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6671 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6674 // Check whether we can use NEON instructions.
6675 if (!MF->getFunction()->getAttributes().
6676 hasAttribute(AttributeSet::FunctionIndex,
6677 Attribute::NoImplicitFloat) &&
6678 Subtarget->hasNEON()) {
6679 if ((Align % 16 == 0) && SizeVal >= 16) {
6680 ldrOpc = ARM::VLD1q32wb_fixed;
6681 strOpc = ARM::VST1q32wb_fixed;
6683 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6685 else if ((Align % 8 == 0) && SizeVal >= 8) {
6686 ldrOpc = ARM::VLD1d32wb_fixed;
6687 strOpc = ARM::VST1d32wb_fixed;
6689 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6692 // Can't use NEON instructions.
6693 if (UnitSize == 0) {
6694 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6695 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6700 unsigned BytesLeft = SizeVal % UnitSize;
6701 unsigned LoopSize = SizeVal - BytesLeft;
6703 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6704 // Use LDR and STR to copy.
6705 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6706 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6707 unsigned srcIn = src;
6708 unsigned destIn = dest;
6709 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6710 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6711 unsigned srcOut = MRI.createVirtualRegister(TRC);
6712 unsigned destOut = MRI.createVirtualRegister(TRC);
6713 if (UnitSize >= 8) {
6714 AddDefaultPred(BuildMI(*BB, MI, dl,
6715 TII->get(ldrOpc), scratch)
6716 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6718 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6719 .addReg(destIn).addImm(0).addReg(scratch));
6720 } else if (isThumb2) {
6721 AddDefaultPred(BuildMI(*BB, MI, dl,
6722 TII->get(ldrOpc), scratch)
6723 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6725 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6726 .addReg(scratch).addReg(destIn)
6729 AddDefaultPred(BuildMI(*BB, MI, dl,
6730 TII->get(ldrOpc), scratch)
6731 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6734 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6735 .addReg(scratch).addReg(destIn)
6736 .addReg(0).addImm(UnitSize));
6742 // Handle the leftover bytes with LDRB and STRB.
6743 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6744 // [destOut] = STRB_POST(scratch, destIn, 1)
6745 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6746 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6747 for (unsigned i = 0; i < BytesLeft; i++) {
6748 unsigned scratch = MRI.createVirtualRegister(TRC);
6749 unsigned srcOut = MRI.createVirtualRegister(TRC);
6750 unsigned destOut = MRI.createVirtualRegister(TRC);
6752 AddDefaultPred(BuildMI(*BB, MI, dl,
6753 TII->get(ldrOpc),scratch)
6754 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6756 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6757 .addReg(scratch).addReg(destIn)
6758 .addReg(0).addImm(1));
6760 AddDefaultPred(BuildMI(*BB, MI, dl,
6761 TII->get(ldrOpc),scratch)
6762 .addReg(srcOut, RegState::Define).addReg(srcIn)
6763 .addReg(0).addImm(1));
6765 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6766 .addReg(scratch).addReg(destIn)
6767 .addReg(0).addImm(1));
6772 MI->eraseFromParent(); // The instruction is gone now.
6776 // Expand the pseudo op to a loop.
6779 // movw varEnd, # --> with thumb2
6781 // ldrcp varEnd, idx --> without thumb2
6782 // fallthrough --> loopMBB
6784 // PHI varPhi, varEnd, varLoop
6785 // PHI srcPhi, src, srcLoop
6786 // PHI destPhi, dst, destLoop
6787 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6788 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6789 // subs varLoop, varPhi, #UnitSize
6791 // fallthrough --> exitMBB
6793 // epilogue to handle left-over bytes
6794 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6795 // [destOut] = STRB_POST(scratch, destLoop, 1)
6796 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6797 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6798 MF->insert(It, loopMBB);
6799 MF->insert(It, exitMBB);
6801 // Transfer the remainder of BB and its successor edges to exitMBB.
6802 exitMBB->splice(exitMBB->begin(), BB,
6803 llvm::next(MachineBasicBlock::iterator(MI)),
6805 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6807 // Load an immediate to varEnd.
6808 unsigned varEnd = MRI.createVirtualRegister(TRC);
6810 unsigned VReg1 = varEnd;
6811 if ((LoopSize & 0xFFFF0000) != 0)
6812 VReg1 = MRI.createVirtualRegister(TRC);
6813 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6814 .addImm(LoopSize & 0xFFFF));
6816 if ((LoopSize & 0xFFFF0000) != 0)
6817 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6819 .addImm(LoopSize >> 16));
6821 MachineConstantPool *ConstantPool = MF->getConstantPool();
6822 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6823 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6825 // MachineConstantPool wants an explicit alignment.
6826 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6828 Align = getDataLayout()->getTypeAllocSize(C->getType());
6829 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6831 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6832 .addReg(varEnd, RegState::Define)
6833 .addConstantPoolIndex(Idx)
6836 BB->addSuccessor(loopMBB);
6838 // Generate the loop body:
6839 // varPhi = PHI(varLoop, varEnd)
6840 // srcPhi = PHI(srcLoop, src)
6841 // destPhi = PHI(destLoop, dst)
6842 MachineBasicBlock *entryBB = BB;
6844 unsigned varLoop = MRI.createVirtualRegister(TRC);
6845 unsigned varPhi = MRI.createVirtualRegister(TRC);
6846 unsigned srcLoop = MRI.createVirtualRegister(TRC);
6847 unsigned srcPhi = MRI.createVirtualRegister(TRC);
6848 unsigned destLoop = MRI.createVirtualRegister(TRC);
6849 unsigned destPhi = MRI.createVirtualRegister(TRC);
6851 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6852 .addReg(varLoop).addMBB(loopMBB)
6853 .addReg(varEnd).addMBB(entryBB);
6854 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6855 .addReg(srcLoop).addMBB(loopMBB)
6856 .addReg(src).addMBB(entryBB);
6857 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6858 .addReg(destLoop).addMBB(loopMBB)
6859 .addReg(dest).addMBB(entryBB);
6861 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6862 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6863 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6864 if (UnitSize >= 8) {
6865 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6866 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6868 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6869 .addReg(destPhi).addImm(0).addReg(scratch));
6870 } else if (isThumb2) {
6871 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6872 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6874 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6875 .addReg(scratch).addReg(destPhi)
6878 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6879 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6882 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6883 .addReg(scratch).addReg(destPhi)
6884 .addReg(0).addImm(UnitSize));
6887 // Decrement loop variable by UnitSize.
6888 MachineInstrBuilder MIB = BuildMI(BB, dl,
6889 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6890 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6891 MIB->getOperand(5).setReg(ARM::CPSR);
6892 MIB->getOperand(5).setIsDef(true);
6894 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6895 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6897 // loopMBB can loop back to loopMBB or fall through to exitMBB.
6898 BB->addSuccessor(loopMBB);
6899 BB->addSuccessor(exitMBB);
6901 // Add epilogue to handle BytesLeft.
6903 MachineInstr *StartOfExit = exitMBB->begin();
6904 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6905 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6907 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6908 // [destOut] = STRB_POST(scratch, destLoop, 1)
6909 unsigned srcIn = srcLoop;
6910 unsigned destIn = destLoop;
6911 for (unsigned i = 0; i < BytesLeft; i++) {
6912 unsigned scratch = MRI.createVirtualRegister(TRC);
6913 unsigned srcOut = MRI.createVirtualRegister(TRC);
6914 unsigned destOut = MRI.createVirtualRegister(TRC);
6916 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6917 TII->get(ldrOpc),scratch)
6918 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6920 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6921 .addReg(scratch).addReg(destIn)
6924 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6925 TII->get(ldrOpc),scratch)
6926 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6928 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6929 .addReg(scratch).addReg(destIn)
6930 .addReg(0).addImm(1));
6936 MI->eraseFromParent(); // The instruction is gone now.
6941 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6942 MachineBasicBlock *BB) const {
6943 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6944 DebugLoc dl = MI->getDebugLoc();
6945 bool isThumb2 = Subtarget->isThumb2();
6946 switch (MI->getOpcode()) {
6949 llvm_unreachable("Unexpected instr type to insert");
6951 // The Thumb2 pre-indexed stores have the same MI operands, they just
6952 // define them differently in the .td files from the isel patterns, so
6953 // they need pseudos.
6954 case ARM::t2STR_preidx:
6955 MI->setDesc(TII->get(ARM::t2STR_PRE));
6957 case ARM::t2STRB_preidx:
6958 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6960 case ARM::t2STRH_preidx:
6961 MI->setDesc(TII->get(ARM::t2STRH_PRE));
6964 case ARM::STRi_preidx:
6965 case ARM::STRBi_preidx: {
6966 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6967 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6968 // Decode the offset.
6969 unsigned Offset = MI->getOperand(4).getImm();
6970 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6971 Offset = ARM_AM::getAM2Offset(Offset);
6975 MachineMemOperand *MMO = *MI->memoperands_begin();
6976 BuildMI(*BB, MI, dl, TII->get(NewOpc))
6977 .addOperand(MI->getOperand(0)) // Rn_wb
6978 .addOperand(MI->getOperand(1)) // Rt
6979 .addOperand(MI->getOperand(2)) // Rn
6980 .addImm(Offset) // offset (skip GPR==zero_reg)
6981 .addOperand(MI->getOperand(5)) // pred
6982 .addOperand(MI->getOperand(6))
6983 .addMemOperand(MMO);
6984 MI->eraseFromParent();
6987 case ARM::STRr_preidx:
6988 case ARM::STRBr_preidx:
6989 case ARM::STRH_preidx: {
6991 switch (MI->getOpcode()) {
6992 default: llvm_unreachable("unexpected opcode!");
6993 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6994 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6995 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6997 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6998 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6999 MIB.addOperand(MI->getOperand(i));
7000 MI->eraseFromParent();
7003 case ARM::ATOMIC_LOAD_ADD_I8:
7004 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7005 case ARM::ATOMIC_LOAD_ADD_I16:
7006 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7007 case ARM::ATOMIC_LOAD_ADD_I32:
7008 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7010 case ARM::ATOMIC_LOAD_AND_I8:
7011 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7012 case ARM::ATOMIC_LOAD_AND_I16:
7013 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7014 case ARM::ATOMIC_LOAD_AND_I32:
7015 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7017 case ARM::ATOMIC_LOAD_OR_I8:
7018 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7019 case ARM::ATOMIC_LOAD_OR_I16:
7020 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7021 case ARM::ATOMIC_LOAD_OR_I32:
7022 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7024 case ARM::ATOMIC_LOAD_XOR_I8:
7025 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7026 case ARM::ATOMIC_LOAD_XOR_I16:
7027 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7028 case ARM::ATOMIC_LOAD_XOR_I32:
7029 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7031 case ARM::ATOMIC_LOAD_NAND_I8:
7032 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7033 case ARM::ATOMIC_LOAD_NAND_I16:
7034 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7035 case ARM::ATOMIC_LOAD_NAND_I32:
7036 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7038 case ARM::ATOMIC_LOAD_SUB_I8:
7039 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7040 case ARM::ATOMIC_LOAD_SUB_I16:
7041 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7042 case ARM::ATOMIC_LOAD_SUB_I32:
7043 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7045 case ARM::ATOMIC_LOAD_MIN_I8:
7046 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7047 case ARM::ATOMIC_LOAD_MIN_I16:
7048 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7049 case ARM::ATOMIC_LOAD_MIN_I32:
7050 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7052 case ARM::ATOMIC_LOAD_MAX_I8:
7053 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7054 case ARM::ATOMIC_LOAD_MAX_I16:
7055 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7056 case ARM::ATOMIC_LOAD_MAX_I32:
7057 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7059 case ARM::ATOMIC_LOAD_UMIN_I8:
7060 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7061 case ARM::ATOMIC_LOAD_UMIN_I16:
7062 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7063 case ARM::ATOMIC_LOAD_UMIN_I32:
7064 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7066 case ARM::ATOMIC_LOAD_UMAX_I8:
7067 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7068 case ARM::ATOMIC_LOAD_UMAX_I16:
7069 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7070 case ARM::ATOMIC_LOAD_UMAX_I32:
7071 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7073 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7074 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7075 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7077 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7078 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7079 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7082 case ARM::ATOMADD6432:
7083 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7084 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7085 /*NeedsCarry*/ true);
7086 case ARM::ATOMSUB6432:
7087 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7088 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7089 /*NeedsCarry*/ true);
7090 case ARM::ATOMOR6432:
7091 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7092 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7093 case ARM::ATOMXOR6432:
7094 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7095 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7096 case ARM::ATOMAND6432:
7097 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7098 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7099 case ARM::ATOMSWAP6432:
7100 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7101 case ARM::ATOMCMPXCHG6432:
7102 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7103 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7104 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7105 case ARM::ATOMMIN6432:
7106 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7107 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7108 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7109 /*IsMinMax*/ true, ARMCC::LT);
7110 case ARM::ATOMMAX6432:
7111 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7112 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7113 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7114 /*IsMinMax*/ true, ARMCC::GE);
7115 case ARM::ATOMUMIN6432:
7116 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7117 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7118 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7119 /*IsMinMax*/ true, ARMCC::LO);
7120 case ARM::ATOMUMAX6432:
7121 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7122 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7123 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7124 /*IsMinMax*/ true, ARMCC::HS);
7126 case ARM::tMOVCCr_pseudo: {
7127 // To "insert" a SELECT_CC instruction, we actually have to insert the
7128 // diamond control-flow pattern. The incoming instruction knows the
7129 // destination vreg to set, the condition code register to branch on, the
7130 // true/false values to select between, and a branch opcode to use.
7131 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7132 MachineFunction::iterator It = BB;
7138 // cmpTY ccX, r1, r2
7140 // fallthrough --> copy0MBB
7141 MachineBasicBlock *thisMBB = BB;
7142 MachineFunction *F = BB->getParent();
7143 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7144 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7145 F->insert(It, copy0MBB);
7146 F->insert(It, sinkMBB);
7148 // Transfer the remainder of BB and its successor edges to sinkMBB.
7149 sinkMBB->splice(sinkMBB->begin(), BB,
7150 llvm::next(MachineBasicBlock::iterator(MI)),
7152 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7154 BB->addSuccessor(copy0MBB);
7155 BB->addSuccessor(sinkMBB);
7157 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7158 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7161 // %FalseValue = ...
7162 // # fallthrough to sinkMBB
7165 // Update machine-CFG edges
7166 BB->addSuccessor(sinkMBB);
7169 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7172 BuildMI(*BB, BB->begin(), dl,
7173 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7174 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7175 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7177 MI->eraseFromParent(); // The pseudo instruction is gone now.
7182 case ARM::BCCZi64: {
7183 // If there is an unconditional branch to the other successor, remove it.
7184 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7186 // Compare both parts that make up the double comparison separately for
7188 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7190 unsigned LHS1 = MI->getOperand(1).getReg();
7191 unsigned LHS2 = MI->getOperand(2).getReg();
7193 AddDefaultPred(BuildMI(BB, dl,
7194 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7195 .addReg(LHS1).addImm(0));
7196 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7197 .addReg(LHS2).addImm(0)
7198 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7200 unsigned RHS1 = MI->getOperand(3).getReg();
7201 unsigned RHS2 = MI->getOperand(4).getReg();
7202 AddDefaultPred(BuildMI(BB, dl,
7203 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7204 .addReg(LHS1).addReg(RHS1));
7205 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7206 .addReg(LHS2).addReg(RHS2)
7207 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7210 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7211 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7212 if (MI->getOperand(0).getImm() == ARMCC::NE)
7213 std::swap(destMBB, exitMBB);
7215 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7216 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7218 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7220 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7222 MI->eraseFromParent(); // The pseudo instruction is gone now.
7226 case ARM::Int_eh_sjlj_setjmp:
7227 case ARM::Int_eh_sjlj_setjmp_nofp:
7228 case ARM::tInt_eh_sjlj_setjmp:
7229 case ARM::t2Int_eh_sjlj_setjmp:
7230 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7231 EmitSjLjDispatchBlock(MI, BB);
7236 // To insert an ABS instruction, we have to insert the
7237 // diamond control-flow pattern. The incoming instruction knows the
7238 // source vreg to test against 0, the destination vreg to set,
7239 // the condition code register to branch on, the
7240 // true/false values to select between, and a branch opcode to use.
7245 // BCC (branch to SinkBB if V0 >= 0)
7246 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7247 // SinkBB: V1 = PHI(V2, V3)
7248 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7249 MachineFunction::iterator BBI = BB;
7251 MachineFunction *Fn = BB->getParent();
7252 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7253 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7254 Fn->insert(BBI, RSBBB);
7255 Fn->insert(BBI, SinkBB);
7257 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7258 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7259 bool isThumb2 = Subtarget->isThumb2();
7260 MachineRegisterInfo &MRI = Fn->getRegInfo();
7261 // In Thumb mode S must not be specified if source register is the SP or
7262 // PC and if destination register is the SP, so restrict register class
7263 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7264 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7265 (const TargetRegisterClass*)&ARM::GPRRegClass);
7267 // Transfer the remainder of BB and its successor edges to sinkMBB.
7268 SinkBB->splice(SinkBB->begin(), BB,
7269 llvm::next(MachineBasicBlock::iterator(MI)),
7271 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7273 BB->addSuccessor(RSBBB);
7274 BB->addSuccessor(SinkBB);
7276 // fall through to SinkMBB
7277 RSBBB->addSuccessor(SinkBB);
7279 // insert a cmp at the end of BB
7280 AddDefaultPred(BuildMI(BB, dl,
7281 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7282 .addReg(ABSSrcReg).addImm(0));
7284 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7286 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7287 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7289 // insert rsbri in RSBBB
7290 // Note: BCC and rsbri will be converted into predicated rsbmi
7291 // by if-conversion pass
7292 BuildMI(*RSBBB, RSBBB->begin(), dl,
7293 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7294 .addReg(ABSSrcReg, RegState::Kill)
7295 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7297 // insert PHI in SinkBB,
7298 // reuse ABSDstReg to not change uses of ABS instruction
7299 BuildMI(*SinkBB, SinkBB->begin(), dl,
7300 TII->get(ARM::PHI), ABSDstReg)
7301 .addReg(NewRsbDstReg).addMBB(RSBBB)
7302 .addReg(ABSSrcReg).addMBB(BB);
7304 // remove ABS instruction
7305 MI->eraseFromParent();
7307 // return last added BB
7310 case ARM::COPY_STRUCT_BYVAL_I32:
7312 return EmitStructByval(MI, BB);
7316 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7317 SDNode *Node) const {
7318 if (!MI->hasPostISelHook()) {
7319 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7320 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7324 const MCInstrDesc *MCID = &MI->getDesc();
7325 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7326 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7327 // operand is still set to noreg. If needed, set the optional operand's
7328 // register to CPSR, and remove the redundant implicit def.
7330 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7332 // Rename pseudo opcodes.
7333 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7335 const ARMBaseInstrInfo *TII =
7336 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7337 MCID = &TII->get(NewOpc);
7339 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7340 "converted opcode should be the same except for cc_out");
7344 // Add the optional cc_out operand
7345 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7347 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7349 // Any ARM instruction that sets the 's' bit should specify an optional
7350 // "cc_out" operand in the last operand position.
7351 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7352 assert(!NewOpc && "Optional cc_out operand required");
7355 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7356 // since we already have an optional CPSR def.
7357 bool definesCPSR = false;
7358 bool deadCPSR = false;
7359 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7361 const MachineOperand &MO = MI->getOperand(i);
7362 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7366 MI->RemoveOperand(i);
7371 assert(!NewOpc && "Optional cc_out operand required");
7374 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7376 assert(!MI->getOperand(ccOutIdx).getReg() &&
7377 "expect uninitialized optional cc_out operand");
7381 // If this instruction was defined with an optional CPSR def and its dag node
7382 // had a live implicit CPSR def, then activate the optional CPSR def.
7383 MachineOperand &MO = MI->getOperand(ccOutIdx);
7384 MO.setReg(ARM::CPSR);
7388 //===----------------------------------------------------------------------===//
7389 // ARM Optimization Hooks
7390 //===----------------------------------------------------------------------===//
7392 // Helper function that checks if N is a null or all ones constant.
7393 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7394 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7397 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7400 // Return true if N is conditionally 0 or all ones.
7401 // Detects these expressions where cc is an i1 value:
7403 // (select cc 0, y) [AllOnes=0]
7404 // (select cc y, 0) [AllOnes=0]
7405 // (zext cc) [AllOnes=0]
7406 // (sext cc) [AllOnes=0/1]
7407 // (select cc -1, y) [AllOnes=1]
7408 // (select cc y, -1) [AllOnes=1]
7410 // Invert is set when N is the null/all ones constant when CC is false.
7411 // OtherOp is set to the alternative value of N.
7412 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7413 SDValue &CC, bool &Invert,
7415 SelectionDAG &DAG) {
7416 switch (N->getOpcode()) {
7417 default: return false;
7419 CC = N->getOperand(0);
7420 SDValue N1 = N->getOperand(1);
7421 SDValue N2 = N->getOperand(2);
7422 if (isZeroOrAllOnes(N1, AllOnes)) {
7427 if (isZeroOrAllOnes(N2, AllOnes)) {
7434 case ISD::ZERO_EXTEND:
7435 // (zext cc) can never be the all ones value.
7439 case ISD::SIGN_EXTEND: {
7440 EVT VT = N->getValueType(0);
7441 CC = N->getOperand(0);
7442 if (CC.getValueType() != MVT::i1)
7446 // When looking for an AllOnes constant, N is an sext, and the 'other'
7448 OtherOp = DAG.getConstant(0, VT);
7449 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7450 // When looking for a 0 constant, N can be zext or sext.
7451 OtherOp = DAG.getConstant(1, VT);
7453 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7459 // Combine a constant select operand into its use:
7461 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7462 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7463 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7464 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7465 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7467 // The transform is rejected if the select doesn't have a constant operand that
7468 // is null, or all ones when AllOnes is set.
7470 // Also recognize sext/zext from i1:
7472 // (add (zext cc), x) -> (select cc (add x, 1), x)
7473 // (add (sext cc), x) -> (select cc (add x, -1), x)
7475 // These transformations eventually create predicated instructions.
7477 // @param N The node to transform.
7478 // @param Slct The N operand that is a select.
7479 // @param OtherOp The other N operand (x above).
7480 // @param DCI Context.
7481 // @param AllOnes Require the select constant to be all ones instead of null.
7482 // @returns The new node, or SDValue() on failure.
7484 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7485 TargetLowering::DAGCombinerInfo &DCI,
7486 bool AllOnes = false) {
7487 SelectionDAG &DAG = DCI.DAG;
7488 EVT VT = N->getValueType(0);
7489 SDValue NonConstantVal;
7492 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7493 NonConstantVal, DAG))
7496 // Slct is now know to be the desired identity constant when CC is true.
7497 SDValue TrueVal = OtherOp;
7498 SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7499 OtherOp, NonConstantVal);
7500 // Unless SwapSelectOps says CC should be false.
7502 std::swap(TrueVal, FalseVal);
7504 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7505 CCOp, TrueVal, FalseVal);
7508 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7510 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7511 TargetLowering::DAGCombinerInfo &DCI) {
7512 SDValue N0 = N->getOperand(0);
7513 SDValue N1 = N->getOperand(1);
7514 if (N0.getNode()->hasOneUse()) {
7515 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7516 if (Result.getNode())
7519 if (N1.getNode()->hasOneUse()) {
7520 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7521 if (Result.getNode())
7527 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7528 // (only after legalization).
7529 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7530 TargetLowering::DAGCombinerInfo &DCI,
7531 const ARMSubtarget *Subtarget) {
7533 // Only perform optimization if after legalize, and if NEON is available. We
7534 // also expected both operands to be BUILD_VECTORs.
7535 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7536 || N0.getOpcode() != ISD::BUILD_VECTOR
7537 || N1.getOpcode() != ISD::BUILD_VECTOR)
7540 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7541 EVT VT = N->getValueType(0);
7542 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7545 // Check that the vector operands are of the right form.
7546 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7547 // operands, where N is the size of the formed vector.
7548 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7549 // index such that we have a pair wise add pattern.
7551 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7552 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7554 SDValue Vec = N0->getOperand(0)->getOperand(0);
7555 SDNode *V = Vec.getNode();
7556 unsigned nextIndex = 0;
7558 // For each operands to the ADD which are BUILD_VECTORs,
7559 // check to see if each of their operands are an EXTRACT_VECTOR with
7560 // the same vector and appropriate index.
7561 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7562 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7563 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7565 SDValue ExtVec0 = N0->getOperand(i);
7566 SDValue ExtVec1 = N1->getOperand(i);
7568 // First operand is the vector, verify its the same.
7569 if (V != ExtVec0->getOperand(0).getNode() ||
7570 V != ExtVec1->getOperand(0).getNode())
7573 // Second is the constant, verify its correct.
7574 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7575 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7577 // For the constant, we want to see all the even or all the odd.
7578 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7579 || C1->getZExtValue() != nextIndex+1)
7588 // Create VPADDL node.
7589 SelectionDAG &DAG = DCI.DAG;
7590 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7592 // Build operand list.
7593 SmallVector<SDValue, 8> Ops;
7594 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7595 TLI.getPointerTy()));
7597 // Input is the vector.
7600 // Get widened type and narrowed type.
7602 unsigned numElem = VT.getVectorNumElements();
7603 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7604 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7605 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7606 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7608 llvm_unreachable("Invalid vector element type for padd optimization.");
7611 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7612 widenType, &Ops[0], Ops.size());
7613 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7616 static SDValue findMUL_LOHI(SDValue V) {
7617 if (V->getOpcode() == ISD::UMUL_LOHI ||
7618 V->getOpcode() == ISD::SMUL_LOHI)
7623 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7624 TargetLowering::DAGCombinerInfo &DCI,
7625 const ARMSubtarget *Subtarget) {
7627 if (Subtarget->isThumb1Only()) return SDValue();
7629 // Only perform the checks after legalize when the pattern is available.
7630 if (DCI.isBeforeLegalize()) return SDValue();
7632 // Look for multiply add opportunities.
7633 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7634 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7635 // a glue link from the first add to the second add.
7636 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7637 // a S/UMLAL instruction.
7640 // \ / \ [no multiline comment]
7646 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7647 SDValue AddcOp0 = AddcNode->getOperand(0);
7648 SDValue AddcOp1 = AddcNode->getOperand(1);
7650 // Check if the two operands are from the same mul_lohi node.
7651 if (AddcOp0.getNode() == AddcOp1.getNode())
7654 assert(AddcNode->getNumValues() == 2 &&
7655 AddcNode->getValueType(0) == MVT::i32 &&
7656 AddcNode->getValueType(1) == MVT::Glue &&
7657 "Expect ADDC with two result values: i32, glue");
7659 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7660 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7661 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7662 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7663 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7666 // Look for the glued ADDE.
7667 SDNode* AddeNode = AddcNode->getGluedUser();
7668 if (AddeNode == NULL)
7671 // Make sure it is really an ADDE.
7672 if (AddeNode->getOpcode() != ISD::ADDE)
7675 assert(AddeNode->getNumOperands() == 3 &&
7676 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7677 "ADDE node has the wrong inputs");
7679 // Check for the triangle shape.
7680 SDValue AddeOp0 = AddeNode->getOperand(0);
7681 SDValue AddeOp1 = AddeNode->getOperand(1);
7683 // Make sure that the ADDE operands are not coming from the same node.
7684 if (AddeOp0.getNode() == AddeOp1.getNode())
7687 // Find the MUL_LOHI node walking up ADDE's operands.
7688 bool IsLeftOperandMUL = false;
7689 SDValue MULOp = findMUL_LOHI(AddeOp0);
7690 if (MULOp == SDValue())
7691 MULOp = findMUL_LOHI(AddeOp1);
7693 IsLeftOperandMUL = true;
7694 if (MULOp == SDValue())
7697 // Figure out the right opcode.
7698 unsigned Opc = MULOp->getOpcode();
7699 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7701 // Figure out the high and low input values to the MLAL node.
7702 SDValue* HiMul = &MULOp;
7703 SDValue* HiAdd = NULL;
7704 SDValue* LoMul = NULL;
7705 SDValue* LowAdd = NULL;
7707 if (IsLeftOperandMUL)
7713 if (AddcOp0->getOpcode() == Opc) {
7717 if (AddcOp1->getOpcode() == Opc) {
7725 if (LoMul->getNode() != HiMul->getNode())
7728 // Create the merged node.
7729 SelectionDAG &DAG = DCI.DAG;
7731 // Build operand list.
7732 SmallVector<SDValue, 8> Ops;
7733 Ops.push_back(LoMul->getOperand(0));
7734 Ops.push_back(LoMul->getOperand(1));
7735 Ops.push_back(*LowAdd);
7736 Ops.push_back(*HiAdd);
7738 SDValue MLALNode = DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7739 DAG.getVTList(MVT::i32, MVT::i32),
7740 &Ops[0], Ops.size());
7742 // Replace the ADDs' nodes uses by the MLA node's values.
7743 SDValue HiMLALResult(MLALNode.getNode(), 1);
7744 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7746 SDValue LoMLALResult(MLALNode.getNode(), 0);
7747 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7749 // Return original node to notify the driver to stop replacing.
7750 SDValue resNode(AddcNode, 0);
7754 /// PerformADDCCombine - Target-specific dag combine transform from
7755 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7756 static SDValue PerformADDCCombine(SDNode *N,
7757 TargetLowering::DAGCombinerInfo &DCI,
7758 const ARMSubtarget *Subtarget) {
7760 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7764 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7765 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7766 /// called with the default operands, and if that fails, with commuted
7768 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7769 TargetLowering::DAGCombinerInfo &DCI,
7770 const ARMSubtarget *Subtarget){
7772 // Attempt to create vpaddl for this add.
7773 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7774 if (Result.getNode())
7777 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7778 if (N0.getNode()->hasOneUse()) {
7779 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7780 if (Result.getNode()) return Result;
7785 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7787 static SDValue PerformADDCombine(SDNode *N,
7788 TargetLowering::DAGCombinerInfo &DCI,
7789 const ARMSubtarget *Subtarget) {
7790 SDValue N0 = N->getOperand(0);
7791 SDValue N1 = N->getOperand(1);
7793 // First try with the default operand order.
7794 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7795 if (Result.getNode())
7798 // If that didn't work, try again with the operands commuted.
7799 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7802 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7804 static SDValue PerformSUBCombine(SDNode *N,
7805 TargetLowering::DAGCombinerInfo &DCI) {
7806 SDValue N0 = N->getOperand(0);
7807 SDValue N1 = N->getOperand(1);
7809 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7810 if (N1.getNode()->hasOneUse()) {
7811 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7812 if (Result.getNode()) return Result;
7818 /// PerformVMULCombine
7819 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7820 /// special multiplier accumulator forwarding.
7826 static SDValue PerformVMULCombine(SDNode *N,
7827 TargetLowering::DAGCombinerInfo &DCI,
7828 const ARMSubtarget *Subtarget) {
7829 if (!Subtarget->hasVMLxForwarding())
7832 SelectionDAG &DAG = DCI.DAG;
7833 SDValue N0 = N->getOperand(0);
7834 SDValue N1 = N->getOperand(1);
7835 unsigned Opcode = N0.getOpcode();
7836 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7837 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7838 Opcode = N1.getOpcode();
7839 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7840 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7845 EVT VT = N->getValueType(0);
7846 DebugLoc DL = N->getDebugLoc();
7847 SDValue N00 = N0->getOperand(0);
7848 SDValue N01 = N0->getOperand(1);
7849 return DAG.getNode(Opcode, DL, VT,
7850 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7851 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7854 static SDValue PerformMULCombine(SDNode *N,
7855 TargetLowering::DAGCombinerInfo &DCI,
7856 const ARMSubtarget *Subtarget) {
7857 SelectionDAG &DAG = DCI.DAG;
7859 if (Subtarget->isThumb1Only())
7862 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7865 EVT VT = N->getValueType(0);
7866 if (VT.is64BitVector() || VT.is128BitVector())
7867 return PerformVMULCombine(N, DCI, Subtarget);
7871 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7875 int64_t MulAmt = C->getSExtValue();
7876 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7878 ShiftAmt = ShiftAmt & (32 - 1);
7879 SDValue V = N->getOperand(0);
7880 DebugLoc DL = N->getDebugLoc();
7883 MulAmt >>= ShiftAmt;
7886 if (isPowerOf2_32(MulAmt - 1)) {
7887 // (mul x, 2^N + 1) => (add (shl x, N), x)
7888 Res = DAG.getNode(ISD::ADD, DL, VT,
7890 DAG.getNode(ISD::SHL, DL, VT,
7892 DAG.getConstant(Log2_32(MulAmt - 1),
7894 } else if (isPowerOf2_32(MulAmt + 1)) {
7895 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7896 Res = DAG.getNode(ISD::SUB, DL, VT,
7897 DAG.getNode(ISD::SHL, DL, VT,
7899 DAG.getConstant(Log2_32(MulAmt + 1),
7905 uint64_t MulAmtAbs = -MulAmt;
7906 if (isPowerOf2_32(MulAmtAbs + 1)) {
7907 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7908 Res = DAG.getNode(ISD::SUB, DL, VT,
7910 DAG.getNode(ISD::SHL, DL, VT,
7912 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7914 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7915 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7916 Res = DAG.getNode(ISD::ADD, DL, VT,
7918 DAG.getNode(ISD::SHL, DL, VT,
7920 DAG.getConstant(Log2_32(MulAmtAbs-1),
7922 Res = DAG.getNode(ISD::SUB, DL, VT,
7923 DAG.getConstant(0, MVT::i32),Res);
7930 Res = DAG.getNode(ISD::SHL, DL, VT,
7931 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7933 // Do not add new nodes to DAG combiner worklist.
7934 DCI.CombineTo(N, Res, false);
7938 static SDValue PerformANDCombine(SDNode *N,
7939 TargetLowering::DAGCombinerInfo &DCI,
7940 const ARMSubtarget *Subtarget) {
7942 // Attempt to use immediate-form VBIC
7943 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7944 DebugLoc dl = N->getDebugLoc();
7945 EVT VT = N->getValueType(0);
7946 SelectionDAG &DAG = DCI.DAG;
7948 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7951 APInt SplatBits, SplatUndef;
7952 unsigned SplatBitSize;
7955 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7956 if (SplatBitSize <= 64) {
7958 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7959 SplatUndef.getZExtValue(), SplatBitSize,
7960 DAG, VbicVT, VT.is128BitVector(),
7962 if (Val.getNode()) {
7964 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7965 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7966 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7971 if (!Subtarget->isThumb1Only()) {
7972 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7973 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7974 if (Result.getNode())
7981 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7982 static SDValue PerformORCombine(SDNode *N,
7983 TargetLowering::DAGCombinerInfo &DCI,
7984 const ARMSubtarget *Subtarget) {
7985 // Attempt to use immediate-form VORR
7986 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7987 DebugLoc dl = N->getDebugLoc();
7988 EVT VT = N->getValueType(0);
7989 SelectionDAG &DAG = DCI.DAG;
7991 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7994 APInt SplatBits, SplatUndef;
7995 unsigned SplatBitSize;
7997 if (BVN && Subtarget->hasNEON() &&
7998 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7999 if (SplatBitSize <= 64) {
8001 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8002 SplatUndef.getZExtValue(), SplatBitSize,
8003 DAG, VorrVT, VT.is128BitVector(),
8005 if (Val.getNode()) {
8007 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8008 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8009 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8014 if (!Subtarget->isThumb1Only()) {
8015 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8016 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8017 if (Result.getNode())
8021 // The code below optimizes (or (and X, Y), Z).
8022 // The AND operand needs to have a single user to make these optimizations
8024 SDValue N0 = N->getOperand(0);
8025 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8027 SDValue N1 = N->getOperand(1);
8029 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8030 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8031 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8033 unsigned SplatBitSize;
8036 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8038 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8039 HasAnyUndefs) && !HasAnyUndefs) {
8040 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8042 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8043 HasAnyUndefs) && !HasAnyUndefs &&
8044 SplatBits0 == ~SplatBits1) {
8045 // Canonicalize the vector type to make instruction selection simpler.
8046 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8047 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8048 N0->getOperand(1), N0->getOperand(0),
8050 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8055 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8058 // BFI is only available on V6T2+
8059 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8062 DebugLoc DL = N->getDebugLoc();
8063 // 1) or (and A, mask), val => ARMbfi A, val, mask
8064 // iff (val & mask) == val
8066 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8067 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8068 // && mask == ~mask2
8069 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8070 // && ~mask == mask2
8071 // (i.e., copy a bitfield value into another bitfield of the same width)
8076 SDValue N00 = N0.getOperand(0);
8078 // The value and the mask need to be constants so we can verify this is
8079 // actually a bitfield set. If the mask is 0xffff, we can do better
8080 // via a movt instruction, so don't use BFI in that case.
8081 SDValue MaskOp = N0.getOperand(1);
8082 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8085 unsigned Mask = MaskC->getZExtValue();
8089 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8090 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8092 unsigned Val = N1C->getZExtValue();
8093 if ((Val & ~Mask) != Val)
8096 if (ARM::isBitFieldInvertedMask(Mask)) {
8097 Val >>= CountTrailingZeros_32(~Mask);
8099 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8100 DAG.getConstant(Val, MVT::i32),
8101 DAG.getConstant(Mask, MVT::i32));
8103 // Do not add new nodes to DAG combiner worklist.
8104 DCI.CombineTo(N, Res, false);
8107 } else if (N1.getOpcode() == ISD::AND) {
8108 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8109 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8112 unsigned Mask2 = N11C->getZExtValue();
8114 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8116 if (ARM::isBitFieldInvertedMask(Mask) &&
8118 // The pack halfword instruction works better for masks that fit it,
8119 // so use that when it's available.
8120 if (Subtarget->hasT2ExtractPack() &&
8121 (Mask == 0xffff || Mask == 0xffff0000))
8124 unsigned amt = CountTrailingZeros_32(Mask2);
8125 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8126 DAG.getConstant(amt, MVT::i32));
8127 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8128 DAG.getConstant(Mask, MVT::i32));
8129 // Do not add new nodes to DAG combiner worklist.
8130 DCI.CombineTo(N, Res, false);
8132 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8134 // The pack halfword instruction works better for masks that fit it,
8135 // so use that when it's available.
8136 if (Subtarget->hasT2ExtractPack() &&
8137 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8140 unsigned lsb = CountTrailingZeros_32(Mask);
8141 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8142 DAG.getConstant(lsb, MVT::i32));
8143 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8144 DAG.getConstant(Mask2, MVT::i32));
8145 // Do not add new nodes to DAG combiner worklist.
8146 DCI.CombineTo(N, Res, false);
8151 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8152 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8153 ARM::isBitFieldInvertedMask(~Mask)) {
8154 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8155 // where lsb(mask) == #shamt and masked bits of B are known zero.
8156 SDValue ShAmt = N00.getOperand(1);
8157 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8158 unsigned LSB = CountTrailingZeros_32(Mask);
8162 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8163 DAG.getConstant(~Mask, MVT::i32));
8165 // Do not add new nodes to DAG combiner worklist.
8166 DCI.CombineTo(N, Res, false);
8172 static SDValue PerformXORCombine(SDNode *N,
8173 TargetLowering::DAGCombinerInfo &DCI,
8174 const ARMSubtarget *Subtarget) {
8175 EVT VT = N->getValueType(0);
8176 SelectionDAG &DAG = DCI.DAG;
8178 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8181 if (!Subtarget->isThumb1Only()) {
8182 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8183 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8184 if (Result.getNode())
8191 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8192 /// the bits being cleared by the AND are not demanded by the BFI.
8193 static SDValue PerformBFICombine(SDNode *N,
8194 TargetLowering::DAGCombinerInfo &DCI) {
8195 SDValue N1 = N->getOperand(1);
8196 if (N1.getOpcode() == ISD::AND) {
8197 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8200 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8201 unsigned LSB = CountTrailingZeros_32(~InvMask);
8202 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8203 unsigned Mask = (1 << Width)-1;
8204 unsigned Mask2 = N11C->getZExtValue();
8205 if ((Mask & (~Mask2)) == 0)
8206 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8207 N->getOperand(0), N1.getOperand(0),
8213 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8214 /// ARMISD::VMOVRRD.
8215 static SDValue PerformVMOVRRDCombine(SDNode *N,
8216 TargetLowering::DAGCombinerInfo &DCI) {
8217 // vmovrrd(vmovdrr x, y) -> x,y
8218 SDValue InDouble = N->getOperand(0);
8219 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8220 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8222 // vmovrrd(load f64) -> (load i32), (load i32)
8223 SDNode *InNode = InDouble.getNode();
8224 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8225 InNode->getValueType(0) == MVT::f64 &&
8226 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8227 !cast<LoadSDNode>(InNode)->isVolatile()) {
8228 // TODO: Should this be done for non-FrameIndex operands?
8229 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8231 SelectionDAG &DAG = DCI.DAG;
8232 DebugLoc DL = LD->getDebugLoc();
8233 SDValue BasePtr = LD->getBasePtr();
8234 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8235 LD->getPointerInfo(), LD->isVolatile(),
8236 LD->isNonTemporal(), LD->isInvariant(),
8237 LD->getAlignment());
8239 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8240 DAG.getConstant(4, MVT::i32));
8241 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8242 LD->getPointerInfo(), LD->isVolatile(),
8243 LD->isNonTemporal(), LD->isInvariant(),
8244 std::min(4U, LD->getAlignment() / 2));
8246 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8247 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8248 DCI.RemoveFromWorklist(LD);
8256 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8257 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8258 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8259 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8260 SDValue Op0 = N->getOperand(0);
8261 SDValue Op1 = N->getOperand(1);
8262 if (Op0.getOpcode() == ISD::BITCAST)
8263 Op0 = Op0.getOperand(0);
8264 if (Op1.getOpcode() == ISD::BITCAST)
8265 Op1 = Op1.getOperand(0);
8266 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8267 Op0.getNode() == Op1.getNode() &&
8268 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8269 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8270 N->getValueType(0), Op0.getOperand(0));
8274 /// PerformSTORECombine - Target-specific dag combine xforms for
8276 static SDValue PerformSTORECombine(SDNode *N,
8277 TargetLowering::DAGCombinerInfo &DCI) {
8278 StoreSDNode *St = cast<StoreSDNode>(N);
8279 if (St->isVolatile())
8282 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8283 // pack all of the elements in one place. Next, store to memory in fewer
8285 SDValue StVal = St->getValue();
8286 EVT VT = StVal.getValueType();
8287 if (St->isTruncatingStore() && VT.isVector()) {
8288 SelectionDAG &DAG = DCI.DAG;
8289 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8290 EVT StVT = St->getMemoryVT();
8291 unsigned NumElems = VT.getVectorNumElements();
8292 assert(StVT != VT && "Cannot truncate to the same type");
8293 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8294 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8296 // From, To sizes and ElemCount must be pow of two
8297 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8299 // We are going to use the original vector elt for storing.
8300 // Accumulated smaller vector elements must be a multiple of the store size.
8301 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8303 unsigned SizeRatio = FromEltSz / ToEltSz;
8304 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8306 // Create a type on which we perform the shuffle.
8307 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8308 NumElems*SizeRatio);
8309 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8311 DebugLoc DL = St->getDebugLoc();
8312 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8313 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8314 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8316 // Can't shuffle using an illegal type.
8317 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8319 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8320 DAG.getUNDEF(WideVec.getValueType()),
8322 // At this point all of the data is stored at the bottom of the
8323 // register. We now need to save it to mem.
8325 // Find the largest store unit
8326 MVT StoreType = MVT::i8;
8327 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8328 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8329 MVT Tp = (MVT::SimpleValueType)tp;
8330 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8333 // Didn't find a legal store type.
8334 if (!TLI.isTypeLegal(StoreType))
8337 // Bitcast the original vector into a vector of store-size units
8338 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8339 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8340 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8341 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8342 SmallVector<SDValue, 8> Chains;
8343 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8344 TLI.getPointerTy());
8345 SDValue BasePtr = St->getBasePtr();
8347 // Perform one or more big stores into memory.
8348 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8349 for (unsigned I = 0; I < E; I++) {
8350 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8351 StoreType, ShuffWide,
8352 DAG.getIntPtrConstant(I));
8353 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8354 St->getPointerInfo(), St->isVolatile(),
8355 St->isNonTemporal(), St->getAlignment());
8356 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8358 Chains.push_back(Ch);
8360 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8364 if (!ISD::isNormalStore(St))
8367 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8368 // ARM stores of arguments in the same cache line.
8369 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8370 StVal.getNode()->hasOneUse()) {
8371 SelectionDAG &DAG = DCI.DAG;
8372 DebugLoc DL = St->getDebugLoc();
8373 SDValue BasePtr = St->getBasePtr();
8374 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8375 StVal.getNode()->getOperand(0), BasePtr,
8376 St->getPointerInfo(), St->isVolatile(),
8377 St->isNonTemporal(), St->getAlignment());
8379 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8380 DAG.getConstant(4, MVT::i32));
8381 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8382 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8383 St->isNonTemporal(),
8384 std::min(4U, St->getAlignment() / 2));
8387 if (StVal.getValueType() != MVT::i64 ||
8388 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8391 // Bitcast an i64 store extracted from a vector to f64.
8392 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8393 SelectionDAG &DAG = DCI.DAG;
8394 DebugLoc dl = StVal.getDebugLoc();
8395 SDValue IntVec = StVal.getOperand(0);
8396 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8397 IntVec.getValueType().getVectorNumElements());
8398 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8399 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8400 Vec, StVal.getOperand(1));
8401 dl = N->getDebugLoc();
8402 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8403 // Make the DAGCombiner fold the bitcasts.
8404 DCI.AddToWorklist(Vec.getNode());
8405 DCI.AddToWorklist(ExtElt.getNode());
8406 DCI.AddToWorklist(V.getNode());
8407 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8408 St->getPointerInfo(), St->isVolatile(),
8409 St->isNonTemporal(), St->getAlignment(),
8413 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8414 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8415 /// i64 vector to have f64 elements, since the value can then be loaded
8416 /// directly into a VFP register.
8417 static bool hasNormalLoadOperand(SDNode *N) {
8418 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8419 for (unsigned i = 0; i < NumElts; ++i) {
8420 SDNode *Elt = N->getOperand(i).getNode();
8421 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8427 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8428 /// ISD::BUILD_VECTOR.
8429 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8430 TargetLowering::DAGCombinerInfo &DCI){
8431 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8432 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8433 // into a pair of GPRs, which is fine when the value is used as a scalar,
8434 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8435 SelectionDAG &DAG = DCI.DAG;
8436 if (N->getNumOperands() == 2) {
8437 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8442 // Load i64 elements as f64 values so that type legalization does not split
8443 // them up into i32 values.
8444 EVT VT = N->getValueType(0);
8445 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8447 DebugLoc dl = N->getDebugLoc();
8448 SmallVector<SDValue, 8> Ops;
8449 unsigned NumElts = VT.getVectorNumElements();
8450 for (unsigned i = 0; i < NumElts; ++i) {
8451 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8453 // Make the DAGCombiner fold the bitcast.
8454 DCI.AddToWorklist(V.getNode());
8456 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8457 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8458 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8461 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8462 /// ISD::INSERT_VECTOR_ELT.
8463 static SDValue PerformInsertEltCombine(SDNode *N,
8464 TargetLowering::DAGCombinerInfo &DCI) {
8465 // Bitcast an i64 load inserted into a vector to f64.
8466 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8467 EVT VT = N->getValueType(0);
8468 SDNode *Elt = N->getOperand(1).getNode();
8469 if (VT.getVectorElementType() != MVT::i64 ||
8470 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8473 SelectionDAG &DAG = DCI.DAG;
8474 DebugLoc dl = N->getDebugLoc();
8475 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8476 VT.getVectorNumElements());
8477 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8478 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8479 // Make the DAGCombiner fold the bitcasts.
8480 DCI.AddToWorklist(Vec.getNode());
8481 DCI.AddToWorklist(V.getNode());
8482 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8483 Vec, V, N->getOperand(2));
8484 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8487 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8488 /// ISD::VECTOR_SHUFFLE.
8489 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8490 // The LLVM shufflevector instruction does not require the shuffle mask
8491 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8492 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8493 // operands do not match the mask length, they are extended by concatenating
8494 // them with undef vectors. That is probably the right thing for other
8495 // targets, but for NEON it is better to concatenate two double-register
8496 // size vector operands into a single quad-register size vector. Do that
8497 // transformation here:
8498 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8499 // shuffle(concat(v1, v2), undef)
8500 SDValue Op0 = N->getOperand(0);
8501 SDValue Op1 = N->getOperand(1);
8502 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8503 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8504 Op0.getNumOperands() != 2 ||
8505 Op1.getNumOperands() != 2)
8507 SDValue Concat0Op1 = Op0.getOperand(1);
8508 SDValue Concat1Op1 = Op1.getOperand(1);
8509 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8510 Concat1Op1.getOpcode() != ISD::UNDEF)
8512 // Skip the transformation if any of the types are illegal.
8513 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8514 EVT VT = N->getValueType(0);
8515 if (!TLI.isTypeLegal(VT) ||
8516 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8517 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8520 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8521 Op0.getOperand(0), Op1.getOperand(0));
8522 // Translate the shuffle mask.
8523 SmallVector<int, 16> NewMask;
8524 unsigned NumElts = VT.getVectorNumElements();
8525 unsigned HalfElts = NumElts/2;
8526 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8527 for (unsigned n = 0; n < NumElts; ++n) {
8528 int MaskElt = SVN->getMaskElt(n);
8530 if (MaskElt < (int)HalfElts)
8532 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8533 NewElt = HalfElts + MaskElt - NumElts;
8534 NewMask.push_back(NewElt);
8536 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8537 DAG.getUNDEF(VT), NewMask.data());
8540 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8541 /// NEON load/store intrinsics to merge base address updates.
8542 static SDValue CombineBaseUpdate(SDNode *N,
8543 TargetLowering::DAGCombinerInfo &DCI) {
8544 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8547 SelectionDAG &DAG = DCI.DAG;
8548 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8549 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8550 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8551 SDValue Addr = N->getOperand(AddrOpIdx);
8553 // Search for a use of the address operand that is an increment.
8554 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8555 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8557 if (User->getOpcode() != ISD::ADD ||
8558 UI.getUse().getResNo() != Addr.getResNo())
8561 // Check that the add is independent of the load/store. Otherwise, folding
8562 // it would create a cycle.
8563 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8566 // Find the new opcode for the updating load/store.
8568 bool isLaneOp = false;
8569 unsigned NewOpc = 0;
8570 unsigned NumVecs = 0;
8572 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8574 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8575 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8577 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8579 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8581 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8583 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8584 NumVecs = 2; isLaneOp = true; break;
8585 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8586 NumVecs = 3; isLaneOp = true; break;
8587 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8588 NumVecs = 4; isLaneOp = true; break;
8589 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8590 NumVecs = 1; isLoad = false; break;
8591 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8592 NumVecs = 2; isLoad = false; break;
8593 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8594 NumVecs = 3; isLoad = false; break;
8595 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8596 NumVecs = 4; isLoad = false; break;
8597 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8598 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8599 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8600 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8601 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8602 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8606 switch (N->getOpcode()) {
8607 default: llvm_unreachable("unexpected opcode for Neon base update");
8608 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8609 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8610 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8614 // Find the size of memory referenced by the load/store.
8617 VecTy = N->getValueType(0);
8619 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8620 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8622 NumBytes /= VecTy.getVectorNumElements();
8624 // If the increment is a constant, it must match the memory ref size.
8625 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8626 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8627 uint64_t IncVal = CInc->getZExtValue();
8628 if (IncVal != NumBytes)
8630 } else if (NumBytes >= 3 * 16) {
8631 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8632 // separate instructions that make it harder to use a non-constant update.
8636 // Create the new updating load/store node.
8638 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8640 for (n = 0; n < NumResultVecs; ++n)
8642 Tys[n++] = MVT::i32;
8643 Tys[n] = MVT::Other;
8644 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8645 SmallVector<SDValue, 8> Ops;
8646 Ops.push_back(N->getOperand(0)); // incoming chain
8647 Ops.push_back(N->getOperand(AddrOpIdx));
8649 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8650 Ops.push_back(N->getOperand(i));
8652 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8653 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8654 Ops.data(), Ops.size(),
8655 MemInt->getMemoryVT(),
8656 MemInt->getMemOperand());
8659 std::vector<SDValue> NewResults;
8660 for (unsigned i = 0; i < NumResultVecs; ++i) {
8661 NewResults.push_back(SDValue(UpdN.getNode(), i));
8663 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8664 DCI.CombineTo(N, NewResults);
8665 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8672 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8673 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8674 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8676 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8677 SelectionDAG &DAG = DCI.DAG;
8678 EVT VT = N->getValueType(0);
8679 // vldN-dup instructions only support 64-bit vectors for N > 1.
8680 if (!VT.is64BitVector())
8683 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8684 SDNode *VLD = N->getOperand(0).getNode();
8685 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8687 unsigned NumVecs = 0;
8688 unsigned NewOpc = 0;
8689 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8690 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8692 NewOpc = ARMISD::VLD2DUP;
8693 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8695 NewOpc = ARMISD::VLD3DUP;
8696 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8698 NewOpc = ARMISD::VLD4DUP;
8703 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8704 // numbers match the load.
8705 unsigned VLDLaneNo =
8706 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8707 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8709 // Ignore uses of the chain result.
8710 if (UI.getUse().getResNo() == NumVecs)
8713 if (User->getOpcode() != ARMISD::VDUPLANE ||
8714 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8718 // Create the vldN-dup node.
8721 for (n = 0; n < NumVecs; ++n)
8723 Tys[n] = MVT::Other;
8724 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8725 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8726 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8727 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8728 Ops, 2, VLDMemInt->getMemoryVT(),
8729 VLDMemInt->getMemOperand());
8732 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8734 unsigned ResNo = UI.getUse().getResNo();
8735 // Ignore uses of the chain result.
8736 if (ResNo == NumVecs)
8739 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8742 // Now the vldN-lane intrinsic is dead except for its chain result.
8743 // Update uses of the chain.
8744 std::vector<SDValue> VLDDupResults;
8745 for (unsigned n = 0; n < NumVecs; ++n)
8746 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8747 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8748 DCI.CombineTo(VLD, VLDDupResults);
8753 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8754 /// ARMISD::VDUPLANE.
8755 static SDValue PerformVDUPLANECombine(SDNode *N,
8756 TargetLowering::DAGCombinerInfo &DCI) {
8757 SDValue Op = N->getOperand(0);
8759 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8760 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8761 if (CombineVLDDUP(N, DCI))
8762 return SDValue(N, 0);
8764 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8765 // redundant. Ignore bit_converts for now; element sizes are checked below.
8766 while (Op.getOpcode() == ISD::BITCAST)
8767 Op = Op.getOperand(0);
8768 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8771 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8772 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8773 // The canonical VMOV for a zero vector uses a 32-bit element size.
8774 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8776 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8778 EVT VT = N->getValueType(0);
8779 if (EltSize > VT.getVectorElementType().getSizeInBits())
8782 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8785 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8786 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8787 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8791 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8793 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8798 APFloat APF = C->getValueAPF();
8799 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8800 != APFloat::opOK || !isExact)
8803 c0 = (I == 0) ? cN : c0;
8804 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8811 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8812 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8813 /// when the VMUL has a constant operand that is a power of 2.
8815 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8816 /// vmul.f32 d16, d17, d16
8817 /// vcvt.s32.f32 d16, d16
8819 /// vcvt.s32.f32 d16, d16, #3
8820 static SDValue PerformVCVTCombine(SDNode *N,
8821 TargetLowering::DAGCombinerInfo &DCI,
8822 const ARMSubtarget *Subtarget) {
8823 SelectionDAG &DAG = DCI.DAG;
8824 SDValue Op = N->getOperand(0);
8826 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8827 Op.getOpcode() != ISD::FMUL)
8831 SDValue N0 = Op->getOperand(0);
8832 SDValue ConstVec = Op->getOperand(1);
8833 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8835 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8836 !isConstVecPow2(ConstVec, isSigned, C))
8839 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8840 Intrinsic::arm_neon_vcvtfp2fxu;
8841 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8843 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8844 DAG.getConstant(Log2_64(C), MVT::i32));
8847 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8848 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8849 /// when the VDIV has a constant operand that is a power of 2.
8851 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8852 /// vcvt.f32.s32 d16, d16
8853 /// vdiv.f32 d16, d17, d16
8855 /// vcvt.f32.s32 d16, d16, #3
8856 static SDValue PerformVDIVCombine(SDNode *N,
8857 TargetLowering::DAGCombinerInfo &DCI,
8858 const ARMSubtarget *Subtarget) {
8859 SelectionDAG &DAG = DCI.DAG;
8860 SDValue Op = N->getOperand(0);
8861 unsigned OpOpcode = Op.getNode()->getOpcode();
8863 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8864 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8868 SDValue ConstVec = N->getOperand(1);
8869 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8871 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8872 !isConstVecPow2(ConstVec, isSigned, C))
8875 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8876 Intrinsic::arm_neon_vcvtfxu2fp;
8877 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8879 DAG.getConstant(IntrinsicOpcode, MVT::i32),
8880 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8883 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8884 /// operand of a vector shift operation, where all the elements of the
8885 /// build_vector must have the same constant integer value.
8886 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8887 // Ignore bit_converts.
8888 while (Op.getOpcode() == ISD::BITCAST)
8889 Op = Op.getOperand(0);
8890 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8891 APInt SplatBits, SplatUndef;
8892 unsigned SplatBitSize;
8894 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8895 HasAnyUndefs, ElementBits) ||
8896 SplatBitSize > ElementBits)
8898 Cnt = SplatBits.getSExtValue();
8902 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8903 /// operand of a vector shift left operation. That value must be in the range:
8904 /// 0 <= Value < ElementBits for a left shift; or
8905 /// 0 <= Value <= ElementBits for a long left shift.
8906 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8907 assert(VT.isVector() && "vector shift count is not a vector type");
8908 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8909 if (! getVShiftImm(Op, ElementBits, Cnt))
8911 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8914 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8915 /// operand of a vector shift right operation. For a shift opcode, the value
8916 /// is positive, but for an intrinsic the value count must be negative. The
8917 /// absolute value must be in the range:
8918 /// 1 <= |Value| <= ElementBits for a right shift; or
8919 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8920 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8922 assert(VT.isVector() && "vector shift count is not a vector type");
8923 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8924 if (! getVShiftImm(Op, ElementBits, Cnt))
8928 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8931 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8932 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8933 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8936 // Don't do anything for most intrinsics.
8939 // Vector shifts: check for immediate versions and lower them.
8940 // Note: This is done during DAG combining instead of DAG legalizing because
8941 // the build_vectors for 64-bit vector element shift counts are generally
8942 // not legal, and it is hard to see their values after they get legalized to
8943 // loads from a constant pool.
8944 case Intrinsic::arm_neon_vshifts:
8945 case Intrinsic::arm_neon_vshiftu:
8946 case Intrinsic::arm_neon_vshiftls:
8947 case Intrinsic::arm_neon_vshiftlu:
8948 case Intrinsic::arm_neon_vshiftn:
8949 case Intrinsic::arm_neon_vrshifts:
8950 case Intrinsic::arm_neon_vrshiftu:
8951 case Intrinsic::arm_neon_vrshiftn:
8952 case Intrinsic::arm_neon_vqshifts:
8953 case Intrinsic::arm_neon_vqshiftu:
8954 case Intrinsic::arm_neon_vqshiftsu:
8955 case Intrinsic::arm_neon_vqshiftns:
8956 case Intrinsic::arm_neon_vqshiftnu:
8957 case Intrinsic::arm_neon_vqshiftnsu:
8958 case Intrinsic::arm_neon_vqrshiftns:
8959 case Intrinsic::arm_neon_vqrshiftnu:
8960 case Intrinsic::arm_neon_vqrshiftnsu: {
8961 EVT VT = N->getOperand(1).getValueType();
8963 unsigned VShiftOpc = 0;
8966 case Intrinsic::arm_neon_vshifts:
8967 case Intrinsic::arm_neon_vshiftu:
8968 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8969 VShiftOpc = ARMISD::VSHL;
8972 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8973 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8974 ARMISD::VSHRs : ARMISD::VSHRu);
8979 case Intrinsic::arm_neon_vshiftls:
8980 case Intrinsic::arm_neon_vshiftlu:
8981 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8983 llvm_unreachable("invalid shift count for vshll intrinsic");
8985 case Intrinsic::arm_neon_vrshifts:
8986 case Intrinsic::arm_neon_vrshiftu:
8987 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8991 case Intrinsic::arm_neon_vqshifts:
8992 case Intrinsic::arm_neon_vqshiftu:
8993 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8997 case Intrinsic::arm_neon_vqshiftsu:
8998 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9000 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9002 case Intrinsic::arm_neon_vshiftn:
9003 case Intrinsic::arm_neon_vrshiftn:
9004 case Intrinsic::arm_neon_vqshiftns:
9005 case Intrinsic::arm_neon_vqshiftnu:
9006 case Intrinsic::arm_neon_vqshiftnsu:
9007 case Intrinsic::arm_neon_vqrshiftns:
9008 case Intrinsic::arm_neon_vqrshiftnu:
9009 case Intrinsic::arm_neon_vqrshiftnsu:
9010 // Narrowing shifts require an immediate right shift.
9011 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9013 llvm_unreachable("invalid shift count for narrowing vector shift "
9017 llvm_unreachable("unhandled vector shift");
9021 case Intrinsic::arm_neon_vshifts:
9022 case Intrinsic::arm_neon_vshiftu:
9023 // Opcode already set above.
9025 case Intrinsic::arm_neon_vshiftls:
9026 case Intrinsic::arm_neon_vshiftlu:
9027 if (Cnt == VT.getVectorElementType().getSizeInBits())
9028 VShiftOpc = ARMISD::VSHLLi;
9030 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9031 ARMISD::VSHLLs : ARMISD::VSHLLu);
9033 case Intrinsic::arm_neon_vshiftn:
9034 VShiftOpc = ARMISD::VSHRN; break;
9035 case Intrinsic::arm_neon_vrshifts:
9036 VShiftOpc = ARMISD::VRSHRs; break;
9037 case Intrinsic::arm_neon_vrshiftu:
9038 VShiftOpc = ARMISD::VRSHRu; break;
9039 case Intrinsic::arm_neon_vrshiftn:
9040 VShiftOpc = ARMISD::VRSHRN; break;
9041 case Intrinsic::arm_neon_vqshifts:
9042 VShiftOpc = ARMISD::VQSHLs; break;
9043 case Intrinsic::arm_neon_vqshiftu:
9044 VShiftOpc = ARMISD::VQSHLu; break;
9045 case Intrinsic::arm_neon_vqshiftsu:
9046 VShiftOpc = ARMISD::VQSHLsu; break;
9047 case Intrinsic::arm_neon_vqshiftns:
9048 VShiftOpc = ARMISD::VQSHRNs; break;
9049 case Intrinsic::arm_neon_vqshiftnu:
9050 VShiftOpc = ARMISD::VQSHRNu; break;
9051 case Intrinsic::arm_neon_vqshiftnsu:
9052 VShiftOpc = ARMISD::VQSHRNsu; break;
9053 case Intrinsic::arm_neon_vqrshiftns:
9054 VShiftOpc = ARMISD::VQRSHRNs; break;
9055 case Intrinsic::arm_neon_vqrshiftnu:
9056 VShiftOpc = ARMISD::VQRSHRNu; break;
9057 case Intrinsic::arm_neon_vqrshiftnsu:
9058 VShiftOpc = ARMISD::VQRSHRNsu; break;
9061 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9062 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9065 case Intrinsic::arm_neon_vshiftins: {
9066 EVT VT = N->getOperand(1).getValueType();
9068 unsigned VShiftOpc = 0;
9070 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9071 VShiftOpc = ARMISD::VSLI;
9072 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9073 VShiftOpc = ARMISD::VSRI;
9075 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9078 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9079 N->getOperand(1), N->getOperand(2),
9080 DAG.getConstant(Cnt, MVT::i32));
9083 case Intrinsic::arm_neon_vqrshifts:
9084 case Intrinsic::arm_neon_vqrshiftu:
9085 // No immediate versions of these to check for.
9092 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9093 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9094 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9095 /// vector element shift counts are generally not legal, and it is hard to see
9096 /// their values after they get legalized to loads from a constant pool.
9097 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9098 const ARMSubtarget *ST) {
9099 EVT VT = N->getValueType(0);
9100 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9101 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9102 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9103 SDValue N1 = N->getOperand(1);
9104 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9105 SDValue N0 = N->getOperand(0);
9106 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9107 DAG.MaskedValueIsZero(N0.getOperand(0),
9108 APInt::getHighBitsSet(32, 16)))
9109 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9113 // Nothing to be done for scalar shifts.
9114 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9115 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9118 assert(ST->hasNEON() && "unexpected vector shift");
9121 switch (N->getOpcode()) {
9122 default: llvm_unreachable("unexpected shift opcode");
9125 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9126 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9127 DAG.getConstant(Cnt, MVT::i32));
9132 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9133 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9134 ARMISD::VSHRs : ARMISD::VSHRu);
9135 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9136 DAG.getConstant(Cnt, MVT::i32));
9142 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9143 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9144 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9145 const ARMSubtarget *ST) {
9146 SDValue N0 = N->getOperand(0);
9148 // Check for sign- and zero-extensions of vector extract operations of 8-
9149 // and 16-bit vector elements. NEON supports these directly. They are
9150 // handled during DAG combining because type legalization will promote them
9151 // to 32-bit types and it is messy to recognize the operations after that.
9152 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9153 SDValue Vec = N0.getOperand(0);
9154 SDValue Lane = N0.getOperand(1);
9155 EVT VT = N->getValueType(0);
9156 EVT EltVT = N0.getValueType();
9157 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9159 if (VT == MVT::i32 &&
9160 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9161 TLI.isTypeLegal(Vec.getValueType()) &&
9162 isa<ConstantSDNode>(Lane)) {
9165 switch (N->getOpcode()) {
9166 default: llvm_unreachable("unexpected opcode");
9167 case ISD::SIGN_EXTEND:
9168 Opc = ARMISD::VGETLANEs;
9170 case ISD::ZERO_EXTEND:
9171 case ISD::ANY_EXTEND:
9172 Opc = ARMISD::VGETLANEu;
9175 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9182 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9183 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9184 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9185 const ARMSubtarget *ST) {
9186 // If the target supports NEON, try to use vmax/vmin instructions for f32
9187 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9188 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9189 // a NaN; only do the transformation when it matches that behavior.
9191 // For now only do this when using NEON for FP operations; if using VFP, it
9192 // is not obvious that the benefit outweighs the cost of switching to the
9194 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9195 N->getValueType(0) != MVT::f32)
9198 SDValue CondLHS = N->getOperand(0);
9199 SDValue CondRHS = N->getOperand(1);
9200 SDValue LHS = N->getOperand(2);
9201 SDValue RHS = N->getOperand(3);
9202 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9204 unsigned Opcode = 0;
9206 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9207 IsReversed = false; // x CC y ? x : y
9208 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9209 IsReversed = true ; // x CC y ? y : x
9223 // If LHS is NaN, an ordered comparison will be false and the result will
9224 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9225 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9226 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9227 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9229 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9230 // will return -0, so vmin can only be used for unsafe math or if one of
9231 // the operands is known to be nonzero.
9232 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9233 !DAG.getTarget().Options.UnsafeFPMath &&
9234 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9236 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9245 // If LHS is NaN, an ordered comparison will be false and the result will
9246 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9247 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9248 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9249 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9251 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9252 // will return +0, so vmax can only be used for unsafe math or if one of
9253 // the operands is known to be nonzero.
9254 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9255 !DAG.getTarget().Options.UnsafeFPMath &&
9256 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9258 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9264 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9267 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9269 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9270 SDValue Cmp = N->getOperand(4);
9271 if (Cmp.getOpcode() != ARMISD::CMPZ)
9272 // Only looking at EQ and NE cases.
9275 EVT VT = N->getValueType(0);
9276 DebugLoc dl = N->getDebugLoc();
9277 SDValue LHS = Cmp.getOperand(0);
9278 SDValue RHS = Cmp.getOperand(1);
9279 SDValue FalseVal = N->getOperand(0);
9280 SDValue TrueVal = N->getOperand(1);
9281 SDValue ARMcc = N->getOperand(2);
9282 ARMCC::CondCodes CC =
9283 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9301 /// FIXME: Turn this into a target neutral optimization?
9303 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9304 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9305 N->getOperand(3), Cmp);
9306 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9308 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9309 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9310 N->getOperand(3), NewCmp);
9313 if (Res.getNode()) {
9314 APInt KnownZero, KnownOne;
9315 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9316 // Capture demanded bits information that would be otherwise lost.
9317 if (KnownZero == 0xfffffffe)
9318 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9319 DAG.getValueType(MVT::i1));
9320 else if (KnownZero == 0xffffff00)
9321 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9322 DAG.getValueType(MVT::i8));
9323 else if (KnownZero == 0xffff0000)
9324 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9325 DAG.getValueType(MVT::i16));
9331 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9332 DAGCombinerInfo &DCI) const {
9333 switch (N->getOpcode()) {
9335 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9336 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9337 case ISD::SUB: return PerformSUBCombine(N, DCI);
9338 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9339 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9340 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9341 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9342 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9343 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9344 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9345 case ISD::STORE: return PerformSTORECombine(N, DCI);
9346 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9347 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9348 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9349 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9350 case ISD::FP_TO_SINT:
9351 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9352 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9353 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9356 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9357 case ISD::SIGN_EXTEND:
9358 case ISD::ZERO_EXTEND:
9359 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9360 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9361 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9362 case ARMISD::VLD2DUP:
9363 case ARMISD::VLD3DUP:
9364 case ARMISD::VLD4DUP:
9365 return CombineBaseUpdate(N, DCI);
9366 case ISD::INTRINSIC_VOID:
9367 case ISD::INTRINSIC_W_CHAIN:
9368 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9369 case Intrinsic::arm_neon_vld1:
9370 case Intrinsic::arm_neon_vld2:
9371 case Intrinsic::arm_neon_vld3:
9372 case Intrinsic::arm_neon_vld4:
9373 case Intrinsic::arm_neon_vld2lane:
9374 case Intrinsic::arm_neon_vld3lane:
9375 case Intrinsic::arm_neon_vld4lane:
9376 case Intrinsic::arm_neon_vst1:
9377 case Intrinsic::arm_neon_vst2:
9378 case Intrinsic::arm_neon_vst3:
9379 case Intrinsic::arm_neon_vst4:
9380 case Intrinsic::arm_neon_vst2lane:
9381 case Intrinsic::arm_neon_vst3lane:
9382 case Intrinsic::arm_neon_vst4lane:
9383 return CombineBaseUpdate(N, DCI);
9391 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9393 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9396 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9397 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9398 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9400 switch (VT.getSimpleVT().SimpleTy) {
9406 // Unaligned access can use (for example) LRDB, LRDH, LDR
9407 if (AllowsUnaligned) {
9409 *Fast = Subtarget->hasV7Ops();
9416 // For any little-endian targets with neon, we can support unaligned ld/st
9417 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9418 // A big-endian target may also explictly support unaligned accesses
9419 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9429 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9430 unsigned AlignCheck) {
9431 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9432 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9435 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9436 unsigned DstAlign, unsigned SrcAlign,
9437 bool IsMemset, bool ZeroMemset,
9439 MachineFunction &MF) const {
9440 const Function *F = MF.getFunction();
9442 // See if we can use NEON instructions for this...
9443 if ((!IsMemset || ZeroMemset) &&
9444 Subtarget->hasNEON() &&
9445 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9446 Attribute::NoImplicitFloat)) {
9449 (memOpAlign(SrcAlign, DstAlign, 16) ||
9450 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9452 } else if (Size >= 8 &&
9453 (memOpAlign(SrcAlign, DstAlign, 8) ||
9454 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9459 // Lowering to i32/i16 if the size permits.
9465 // Let the target-independent logic figure it out.
9469 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9470 if (Val.getOpcode() != ISD::LOAD)
9473 EVT VT1 = Val.getValueType();
9474 if (!VT1.isSimple() || !VT1.isInteger() ||
9475 !VT2.isSimple() || !VT2.isInteger())
9478 switch (VT1.getSimpleVT().SimpleTy) {
9483 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9490 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9495 switch (VT.getSimpleVT().SimpleTy) {
9496 default: return false;
9511 if ((V & (Scale - 1)) != 0)
9514 return V == (V & ((1LL << 5) - 1));
9517 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9518 const ARMSubtarget *Subtarget) {
9525 switch (VT.getSimpleVT().SimpleTy) {
9526 default: return false;
9531 // + imm12 or - imm8
9533 return V == (V & ((1LL << 8) - 1));
9534 return V == (V & ((1LL << 12) - 1));
9537 // Same as ARM mode. FIXME: NEON?
9538 if (!Subtarget->hasVFP2())
9543 return V == (V & ((1LL << 8) - 1));
9547 /// isLegalAddressImmediate - Return true if the integer value can be used
9548 /// as the offset of the target addressing mode for load / store of the
9550 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9551 const ARMSubtarget *Subtarget) {
9558 if (Subtarget->isThumb1Only())
9559 return isLegalT1AddressImmediate(V, VT);
9560 else if (Subtarget->isThumb2())
9561 return isLegalT2AddressImmediate(V, VT, Subtarget);
9566 switch (VT.getSimpleVT().SimpleTy) {
9567 default: return false;
9572 return V == (V & ((1LL << 12) - 1));
9575 return V == (V & ((1LL << 8) - 1));
9578 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9583 return V == (V & ((1LL << 8) - 1));
9587 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9589 int Scale = AM.Scale;
9593 switch (VT.getSimpleVT().SimpleTy) {
9594 default: return false;
9603 return Scale == 2 || Scale == 4 || Scale == 8;
9606 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9610 // Note, we allow "void" uses (basically, uses that aren't loads or
9611 // stores), because arm allows folding a scale into many arithmetic
9612 // operations. This should be made more precise and revisited later.
9614 // Allow r << imm, but the imm has to be a multiple of two.
9615 if (Scale & 1) return false;
9616 return isPowerOf2_32(Scale);
9620 /// isLegalAddressingMode - Return true if the addressing mode represented
9621 /// by AM is legal for this target, for a load/store of the specified type.
9622 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9624 EVT VT = getValueType(Ty, true);
9625 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9628 // Can never fold addr of global into load/store.
9633 case 0: // no scale reg, must be "r+i" or "r", or "i".
9636 if (Subtarget->isThumb1Only())
9640 // ARM doesn't support any R+R*scale+imm addr modes.
9647 if (Subtarget->isThumb2())
9648 return isLegalT2ScaledAddressingMode(AM, VT);
9650 int Scale = AM.Scale;
9651 switch (VT.getSimpleVT().SimpleTy) {
9652 default: return false;
9656 if (Scale < 0) Scale = -Scale;
9660 return isPowerOf2_32(Scale & ~1);
9664 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9669 // Note, we allow "void" uses (basically, uses that aren't loads or
9670 // stores), because arm allows folding a scale into many arithmetic
9671 // operations. This should be made more precise and revisited later.
9673 // Allow r << imm, but the imm has to be a multiple of two.
9674 if (Scale & 1) return false;
9675 return isPowerOf2_32(Scale);
9681 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9682 /// icmp immediate, that is the target has icmp instructions which can compare
9683 /// a register against the immediate without having to materialize the
9684 /// immediate into a register.
9685 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9686 // Thumb2 and ARM modes can use cmn for negative immediates.
9687 if (!Subtarget->isThumb())
9688 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9689 if (Subtarget->isThumb2())
9690 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9691 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9692 return Imm >= 0 && Imm <= 255;
9695 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9696 /// *or sub* immediate, that is the target has add or sub instructions which can
9697 /// add a register with the immediate without having to materialize the
9698 /// immediate into a register.
9699 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9700 // Same encoding for add/sub, just flip the sign.
9701 int64_t AbsImm = llvm::abs64(Imm);
9702 if (!Subtarget->isThumb())
9703 return ARM_AM::getSOImmVal(AbsImm) != -1;
9704 if (Subtarget->isThumb2())
9705 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9706 // Thumb1 only has 8-bit unsigned immediate.
9707 return AbsImm >= 0 && AbsImm <= 255;
9710 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9711 bool isSEXTLoad, SDValue &Base,
9712 SDValue &Offset, bool &isInc,
9713 SelectionDAG &DAG) {
9714 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9717 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9719 Base = Ptr->getOperand(0);
9720 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9721 int RHSC = (int)RHS->getZExtValue();
9722 if (RHSC < 0 && RHSC > -256) {
9723 assert(Ptr->getOpcode() == ISD::ADD);
9725 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9729 isInc = (Ptr->getOpcode() == ISD::ADD);
9730 Offset = Ptr->getOperand(1);
9732 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9734 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9735 int RHSC = (int)RHS->getZExtValue();
9736 if (RHSC < 0 && RHSC > -0x1000) {
9737 assert(Ptr->getOpcode() == ISD::ADD);
9739 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9740 Base = Ptr->getOperand(0);
9745 if (Ptr->getOpcode() == ISD::ADD) {
9747 ARM_AM::ShiftOpc ShOpcVal=
9748 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9749 if (ShOpcVal != ARM_AM::no_shift) {
9750 Base = Ptr->getOperand(1);
9751 Offset = Ptr->getOperand(0);
9753 Base = Ptr->getOperand(0);
9754 Offset = Ptr->getOperand(1);
9759 isInc = (Ptr->getOpcode() == ISD::ADD);
9760 Base = Ptr->getOperand(0);
9761 Offset = Ptr->getOperand(1);
9765 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9769 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9770 bool isSEXTLoad, SDValue &Base,
9771 SDValue &Offset, bool &isInc,
9772 SelectionDAG &DAG) {
9773 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9776 Base = Ptr->getOperand(0);
9777 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9778 int RHSC = (int)RHS->getZExtValue();
9779 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9780 assert(Ptr->getOpcode() == ISD::ADD);
9782 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9784 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9785 isInc = Ptr->getOpcode() == ISD::ADD;
9786 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9794 /// getPreIndexedAddressParts - returns true by value, base pointer and
9795 /// offset pointer and addressing mode by reference if the node's address
9796 /// can be legally represented as pre-indexed load / store address.
9798 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9800 ISD::MemIndexedMode &AM,
9801 SelectionDAG &DAG) const {
9802 if (Subtarget->isThumb1Only())
9807 bool isSEXTLoad = false;
9808 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9809 Ptr = LD->getBasePtr();
9810 VT = LD->getMemoryVT();
9811 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9812 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9813 Ptr = ST->getBasePtr();
9814 VT = ST->getMemoryVT();
9819 bool isLegal = false;
9820 if (Subtarget->isThumb2())
9821 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9822 Offset, isInc, DAG);
9824 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9825 Offset, isInc, DAG);
9829 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9833 /// getPostIndexedAddressParts - returns true by value, base pointer and
9834 /// offset pointer and addressing mode by reference if this node can be
9835 /// combined with a load / store to form a post-indexed load / store.
9836 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9839 ISD::MemIndexedMode &AM,
9840 SelectionDAG &DAG) const {
9841 if (Subtarget->isThumb1Only())
9846 bool isSEXTLoad = false;
9847 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9848 VT = LD->getMemoryVT();
9849 Ptr = LD->getBasePtr();
9850 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9851 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9852 VT = ST->getMemoryVT();
9853 Ptr = ST->getBasePtr();
9858 bool isLegal = false;
9859 if (Subtarget->isThumb2())
9860 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9863 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9869 // Swap base ptr and offset to catch more post-index load / store when
9870 // it's legal. In Thumb2 mode, offset must be an immediate.
9871 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9872 !Subtarget->isThumb2())
9873 std::swap(Base, Offset);
9875 // Post-indexed load / store update the base pointer.
9880 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9884 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9887 const SelectionDAG &DAG,
9888 unsigned Depth) const {
9889 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9890 switch (Op.getOpcode()) {
9892 case ARMISD::CMOV: {
9893 // Bits are known zero/one if known on the LHS and RHS.
9894 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9895 if (KnownZero == 0 && KnownOne == 0) return;
9897 APInt KnownZeroRHS, KnownOneRHS;
9898 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9899 KnownZero &= KnownZeroRHS;
9900 KnownOne &= KnownOneRHS;
9906 //===----------------------------------------------------------------------===//
9907 // ARM Inline Assembly Support
9908 //===----------------------------------------------------------------------===//
9910 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9911 // Looking for "rev" which is V6+.
9912 if (!Subtarget->hasV6Ops())
9915 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9916 std::string AsmStr = IA->getAsmString();
9917 SmallVector<StringRef, 4> AsmPieces;
9918 SplitString(AsmStr, AsmPieces, ";\n");
9920 switch (AsmPieces.size()) {
9921 default: return false;
9923 AsmStr = AsmPieces[0];
9925 SplitString(AsmStr, AsmPieces, " \t,");
9928 if (AsmPieces.size() == 3 &&
9929 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9930 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9931 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9932 if (Ty && Ty->getBitWidth() == 32)
9933 return IntrinsicLowering::LowerToByteSwap(CI);
9941 /// getConstraintType - Given a constraint letter, return the type of
9942 /// constraint it is for this target.
9943 ARMTargetLowering::ConstraintType
9944 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9945 if (Constraint.size() == 1) {
9946 switch (Constraint[0]) {
9948 case 'l': return C_RegisterClass;
9949 case 'w': return C_RegisterClass;
9950 case 'h': return C_RegisterClass;
9951 case 'x': return C_RegisterClass;
9952 case 't': return C_RegisterClass;
9953 case 'j': return C_Other; // Constant for movw.
9954 // An address with a single base register. Due to the way we
9955 // currently handle addresses it is the same as an 'r' memory constraint.
9956 case 'Q': return C_Memory;
9958 } else if (Constraint.size() == 2) {
9959 switch (Constraint[0]) {
9961 // All 'U+' constraints are addresses.
9962 case 'U': return C_Memory;
9965 return TargetLowering::getConstraintType(Constraint);
9968 /// Examine constraint type and operand type and determine a weight value.
9969 /// This object must already have been set up with the operand type
9970 /// and the current alternative constraint selected.
9971 TargetLowering::ConstraintWeight
9972 ARMTargetLowering::getSingleConstraintMatchWeight(
9973 AsmOperandInfo &info, const char *constraint) const {
9974 ConstraintWeight weight = CW_Invalid;
9975 Value *CallOperandVal = info.CallOperandVal;
9976 // If we don't have a value, we can't do a match,
9977 // but allow it at the lowest weight.
9978 if (CallOperandVal == NULL)
9980 Type *type = CallOperandVal->getType();
9981 // Look at the constraint type.
9982 switch (*constraint) {
9984 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9987 if (type->isIntegerTy()) {
9988 if (Subtarget->isThumb())
9989 weight = CW_SpecificReg;
9991 weight = CW_Register;
9995 if (type->isFloatingPointTy())
9996 weight = CW_Register;
10002 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10004 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10006 if (Constraint.size() == 1) {
10007 // GCC ARM Constraint Letters
10008 switch (Constraint[0]) {
10009 case 'l': // Low regs or general regs.
10010 if (Subtarget->isThumb())
10011 return RCPair(0U, &ARM::tGPRRegClass);
10012 return RCPair(0U, &ARM::GPRRegClass);
10013 case 'h': // High regs or no regs.
10014 if (Subtarget->isThumb())
10015 return RCPair(0U, &ARM::hGPRRegClass);
10018 return RCPair(0U, &ARM::GPRRegClass);
10020 if (VT == MVT::f32)
10021 return RCPair(0U, &ARM::SPRRegClass);
10022 if (VT.getSizeInBits() == 64)
10023 return RCPair(0U, &ARM::DPRRegClass);
10024 if (VT.getSizeInBits() == 128)
10025 return RCPair(0U, &ARM::QPRRegClass);
10028 if (VT == MVT::f32)
10029 return RCPair(0U, &ARM::SPR_8RegClass);
10030 if (VT.getSizeInBits() == 64)
10031 return RCPair(0U, &ARM::DPR_8RegClass);
10032 if (VT.getSizeInBits() == 128)
10033 return RCPair(0U, &ARM::QPR_8RegClass);
10036 if (VT == MVT::f32)
10037 return RCPair(0U, &ARM::SPRRegClass);
10041 if (StringRef("{cc}").equals_lower(Constraint))
10042 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10044 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10047 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10048 /// vector. If it is invalid, don't add anything to Ops.
10049 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10050 std::string &Constraint,
10051 std::vector<SDValue>&Ops,
10052 SelectionDAG &DAG) const {
10053 SDValue Result(0, 0);
10055 // Currently only support length 1 constraints.
10056 if (Constraint.length() != 1) return;
10058 char ConstraintLetter = Constraint[0];
10059 switch (ConstraintLetter) {
10062 case 'I': case 'J': case 'K': case 'L':
10063 case 'M': case 'N': case 'O':
10064 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10068 int64_t CVal64 = C->getSExtValue();
10069 int CVal = (int) CVal64;
10070 // None of these constraints allow values larger than 32 bits. Check
10071 // that the value fits in an int.
10072 if (CVal != CVal64)
10075 switch (ConstraintLetter) {
10077 // Constant suitable for movw, must be between 0 and
10079 if (Subtarget->hasV6T2Ops())
10080 if (CVal >= 0 && CVal <= 65535)
10084 if (Subtarget->isThumb1Only()) {
10085 // This must be a constant between 0 and 255, for ADD
10087 if (CVal >= 0 && CVal <= 255)
10089 } else if (Subtarget->isThumb2()) {
10090 // A constant that can be used as an immediate value in a
10091 // data-processing instruction.
10092 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10095 // A constant that can be used as an immediate value in a
10096 // data-processing instruction.
10097 if (ARM_AM::getSOImmVal(CVal) != -1)
10103 if (Subtarget->isThumb()) { // FIXME thumb2
10104 // This must be a constant between -255 and -1, for negated ADD
10105 // immediates. This can be used in GCC with an "n" modifier that
10106 // prints the negated value, for use with SUB instructions. It is
10107 // not useful otherwise but is implemented for compatibility.
10108 if (CVal >= -255 && CVal <= -1)
10111 // This must be a constant between -4095 and 4095. It is not clear
10112 // what this constraint is intended for. Implemented for
10113 // compatibility with GCC.
10114 if (CVal >= -4095 && CVal <= 4095)
10120 if (Subtarget->isThumb1Only()) {
10121 // A 32-bit value where only one byte has a nonzero value. Exclude
10122 // zero to match GCC. This constraint is used by GCC internally for
10123 // constants that can be loaded with a move/shift combination.
10124 // It is not useful otherwise but is implemented for compatibility.
10125 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10127 } else if (Subtarget->isThumb2()) {
10128 // A constant whose bitwise inverse can be used as an immediate
10129 // value in a data-processing instruction. This can be used in GCC
10130 // with a "B" modifier that prints the inverted value, for use with
10131 // BIC and MVN instructions. It is not useful otherwise but is
10132 // implemented for compatibility.
10133 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10136 // A constant whose bitwise inverse can be used as an immediate
10137 // value in a data-processing instruction. This can be used in GCC
10138 // with a "B" modifier that prints the inverted value, for use with
10139 // BIC and MVN instructions. It is not useful otherwise but is
10140 // implemented for compatibility.
10141 if (ARM_AM::getSOImmVal(~CVal) != -1)
10147 if (Subtarget->isThumb1Only()) {
10148 // This must be a constant between -7 and 7,
10149 // for 3-operand ADD/SUB immediate instructions.
10150 if (CVal >= -7 && CVal < 7)
10152 } else if (Subtarget->isThumb2()) {
10153 // A constant whose negation can be used as an immediate value in a
10154 // data-processing instruction. This can be used in GCC with an "n"
10155 // modifier that prints the negated value, for use with SUB
10156 // instructions. It is not useful otherwise but is implemented for
10158 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10161 // A constant whose negation can be used as an immediate value in a
10162 // data-processing instruction. This can be used in GCC with an "n"
10163 // modifier that prints the negated value, for use with SUB
10164 // instructions. It is not useful otherwise but is implemented for
10166 if (ARM_AM::getSOImmVal(-CVal) != -1)
10172 if (Subtarget->isThumb()) { // FIXME thumb2
10173 // This must be a multiple of 4 between 0 and 1020, for
10174 // ADD sp + immediate.
10175 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10178 // A power of two or a constant between 0 and 32. This is used in
10179 // GCC for the shift amount on shifted register operands, but it is
10180 // useful in general for any shift amounts.
10181 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10187 if (Subtarget->isThumb()) { // FIXME thumb2
10188 // This must be a constant between 0 and 31, for shift amounts.
10189 if (CVal >= 0 && CVal <= 31)
10195 if (Subtarget->isThumb()) { // FIXME thumb2
10196 // This must be a multiple of 4 between -508 and 508, for
10197 // ADD/SUB sp = sp + immediate.
10198 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10203 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10207 if (Result.getNode()) {
10208 Ops.push_back(Result);
10211 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10215 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10216 // The ARM target isn't yet aware of offsets.
10220 bool ARM::isBitFieldInvertedMask(unsigned v) {
10221 if (v == 0xffffffff)
10223 // there can be 1's on either or both "outsides", all the "inside"
10224 // bits must be 0's
10225 unsigned int lsb = 0, msb = 31;
10226 while (v & (1 << msb)) --msb;
10227 while (v & (1 << lsb)) ++lsb;
10228 for (unsigned int i = lsb; i <= msb; ++i) {
10235 /// isFPImmLegal - Returns true if the target can instruction select the
10236 /// specified FP immediate natively. If false, the legalizer will
10237 /// materialize the FP immediate as a load from a constant pool.
10238 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10239 if (!Subtarget->hasVFP3())
10241 if (VT == MVT::f32)
10242 return ARM_AM::getFP32Imm(Imm) != -1;
10243 if (VT == MVT::f64)
10244 return ARM_AM::getFP64Imm(Imm) != -1;
10248 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10249 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10250 /// specified in the intrinsic calls.
10251 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10253 unsigned Intrinsic) const {
10254 switch (Intrinsic) {
10255 case Intrinsic::arm_neon_vld1:
10256 case Intrinsic::arm_neon_vld2:
10257 case Intrinsic::arm_neon_vld3:
10258 case Intrinsic::arm_neon_vld4:
10259 case Intrinsic::arm_neon_vld2lane:
10260 case Intrinsic::arm_neon_vld3lane:
10261 case Intrinsic::arm_neon_vld4lane: {
10262 Info.opc = ISD::INTRINSIC_W_CHAIN;
10263 // Conservatively set memVT to the entire set of vectors loaded.
10264 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10265 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10266 Info.ptrVal = I.getArgOperand(0);
10268 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10269 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10270 Info.vol = false; // volatile loads with NEON intrinsics not supported
10271 Info.readMem = true;
10272 Info.writeMem = false;
10275 case Intrinsic::arm_neon_vst1:
10276 case Intrinsic::arm_neon_vst2:
10277 case Intrinsic::arm_neon_vst3:
10278 case Intrinsic::arm_neon_vst4:
10279 case Intrinsic::arm_neon_vst2lane:
10280 case Intrinsic::arm_neon_vst3lane:
10281 case Intrinsic::arm_neon_vst4lane: {
10282 Info.opc = ISD::INTRINSIC_VOID;
10283 // Conservatively set memVT to the entire set of vectors stored.
10284 unsigned NumElts = 0;
10285 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10286 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10287 if (!ArgTy->isVectorTy())
10289 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10291 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10292 Info.ptrVal = I.getArgOperand(0);
10294 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10295 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10296 Info.vol = false; // volatile stores with NEON intrinsics not supported
10297 Info.readMem = false;
10298 Info.writeMem = true;
10301 case Intrinsic::arm_strexd: {
10302 Info.opc = ISD::INTRINSIC_W_CHAIN;
10303 Info.memVT = MVT::i64;
10304 Info.ptrVal = I.getArgOperand(2);
10308 Info.readMem = false;
10309 Info.writeMem = true;
10312 case Intrinsic::arm_ldrexd: {
10313 Info.opc = ISD::INTRINSIC_W_CHAIN;
10314 Info.memVT = MVT::i64;
10315 Info.ptrVal = I.getArgOperand(0);
10319 Info.readMem = true;
10320 Info.writeMem = false;