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,
1932 SmallVector<SDValue, 4> RetOps;
1933 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1935 // Copy the result values into the output registers.
1936 for (unsigned i = 0, realRVLocIdx = 0;
1938 ++i, ++realRVLocIdx) {
1939 CCValAssign &VA = RVLocs[i];
1940 assert(VA.isRegLoc() && "Can only return in registers!");
1942 SDValue Arg = OutVals[realRVLocIdx];
1944 switch (VA.getLocInfo()) {
1945 default: llvm_unreachable("Unknown loc info!");
1946 case CCValAssign::Full: break;
1947 case CCValAssign::BCvt:
1948 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1952 if (VA.needsCustom()) {
1953 if (VA.getLocVT() == MVT::v2f64) {
1954 // Extract the first half and return it in two registers.
1955 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1956 DAG.getConstant(0, MVT::i32));
1957 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1958 DAG.getVTList(MVT::i32, MVT::i32), Half);
1960 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1961 Flag = Chain.getValue(1);
1962 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1963 VA = RVLocs[++i]; // skip ahead to next loc
1964 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1965 HalfGPRs.getValue(1), Flag);
1966 Flag = Chain.getValue(1);
1967 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1968 VA = RVLocs[++i]; // skip ahead to next loc
1970 // Extract the 2nd half and fall through to handle it as an f64 value.
1971 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1972 DAG.getConstant(1, MVT::i32));
1974 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1976 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1977 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1978 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1979 Flag = Chain.getValue(1);
1980 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1981 VA = RVLocs[++i]; // skip ahead to next loc
1982 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1985 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1987 // Guarantee that all emitted copies are
1988 // stuck together, avoiding something bad.
1989 Flag = Chain.getValue(1);
1990 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1993 // Update chain and glue.
1996 RetOps.push_back(Flag);
1998 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
1999 RetOps.data(), RetOps.size());
2002 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2003 if (N->getNumValues() != 1)
2005 if (!N->hasNUsesOfValue(1, 0))
2008 SDValue TCChain = Chain;
2009 SDNode *Copy = *N->use_begin();
2010 if (Copy->getOpcode() == ISD::CopyToReg) {
2011 // If the copy has a glue operand, we conservatively assume it isn't safe to
2012 // perform a tail call.
2013 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2015 TCChain = Copy->getOperand(0);
2016 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2017 SDNode *VMov = Copy;
2018 // f64 returned in a pair of GPRs.
2019 SmallPtrSet<SDNode*, 2> Copies;
2020 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2022 if (UI->getOpcode() != ISD::CopyToReg)
2026 if (Copies.size() > 2)
2029 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2031 SDValue UseChain = UI->getOperand(0);
2032 if (Copies.count(UseChain.getNode()))
2039 } else if (Copy->getOpcode() == ISD::BITCAST) {
2040 // f32 returned in a single GPR.
2041 if (!Copy->hasOneUse())
2043 Copy = *Copy->use_begin();
2044 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2046 Chain = Copy->getOperand(0);
2051 bool HasRet = false;
2052 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2054 if (UI->getOpcode() != ARMISD::RET_FLAG)
2066 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2067 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2070 if (!CI->isTailCall())
2073 return !Subtarget->isThumb1Only();
2076 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2077 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2078 // one of the above mentioned nodes. It has to be wrapped because otherwise
2079 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2080 // be used to form addressing mode. These wrapped nodes will be selected
2082 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2083 EVT PtrVT = Op.getValueType();
2084 // FIXME there is no actual debug info here
2085 DebugLoc dl = Op.getDebugLoc();
2086 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2088 if (CP->isMachineConstantPoolEntry())
2089 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2090 CP->getAlignment());
2092 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2093 CP->getAlignment());
2094 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2097 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2098 return MachineJumpTableInfo::EK_Inline;
2101 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2102 SelectionDAG &DAG) const {
2103 MachineFunction &MF = DAG.getMachineFunction();
2104 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2105 unsigned ARMPCLabelIndex = 0;
2106 DebugLoc DL = Op.getDebugLoc();
2107 EVT PtrVT = getPointerTy();
2108 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2109 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2111 if (RelocM == Reloc::Static) {
2112 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2114 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2115 ARMPCLabelIndex = AFI->createPICLabelUId();
2116 ARMConstantPoolValue *CPV =
2117 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2118 ARMCP::CPBlockAddress, PCAdj);
2119 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2121 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2122 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2123 MachinePointerInfo::getConstantPool(),
2124 false, false, false, 0);
2125 if (RelocM == Reloc::Static)
2127 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2128 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2131 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2133 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2134 SelectionDAG &DAG) const {
2135 DebugLoc dl = GA->getDebugLoc();
2136 EVT PtrVT = getPointerTy();
2137 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2138 MachineFunction &MF = DAG.getMachineFunction();
2139 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2140 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2141 ARMConstantPoolValue *CPV =
2142 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2143 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2144 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2145 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2146 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2147 MachinePointerInfo::getConstantPool(),
2148 false, false, false, 0);
2149 SDValue Chain = Argument.getValue(1);
2151 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2152 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2154 // call __tls_get_addr.
2157 Entry.Node = Argument;
2158 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2159 Args.push_back(Entry);
2160 // FIXME: is there useful debug info available here?
2161 TargetLowering::CallLoweringInfo CLI(Chain,
2162 (Type *) Type::getInt32Ty(*DAG.getContext()),
2163 false, false, false, false,
2164 0, CallingConv::C, /*isTailCall=*/false,
2165 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2166 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2167 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2168 return CallResult.first;
2171 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2172 // "local exec" model.
2174 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2176 TLSModel::Model model) const {
2177 const GlobalValue *GV = GA->getGlobal();
2178 DebugLoc dl = GA->getDebugLoc();
2180 SDValue Chain = DAG.getEntryNode();
2181 EVT PtrVT = getPointerTy();
2182 // Get the Thread Pointer
2183 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2185 if (model == TLSModel::InitialExec) {
2186 MachineFunction &MF = DAG.getMachineFunction();
2187 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2188 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2189 // Initial exec model.
2190 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2191 ARMConstantPoolValue *CPV =
2192 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2193 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2195 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2196 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2197 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2198 MachinePointerInfo::getConstantPool(),
2199 false, false, false, 0);
2200 Chain = Offset.getValue(1);
2202 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2203 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2205 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2206 MachinePointerInfo::getConstantPool(),
2207 false, false, false, 0);
2210 assert(model == TLSModel::LocalExec);
2211 ARMConstantPoolValue *CPV =
2212 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2213 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2214 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2215 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2216 MachinePointerInfo::getConstantPool(),
2217 false, false, false, 0);
2220 // The address of the thread local variable is the add of the thread
2221 // pointer with the offset of the variable.
2222 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2226 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2227 // TODO: implement the "local dynamic" model
2228 assert(Subtarget->isTargetELF() &&
2229 "TLS not implemented for non-ELF targets");
2230 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2232 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2235 case TLSModel::GeneralDynamic:
2236 case TLSModel::LocalDynamic:
2237 return LowerToTLSGeneralDynamicModel(GA, DAG);
2238 case TLSModel::InitialExec:
2239 case TLSModel::LocalExec:
2240 return LowerToTLSExecModels(GA, DAG, model);
2242 llvm_unreachable("bogus TLS model");
2245 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2246 SelectionDAG &DAG) const {
2247 EVT PtrVT = getPointerTy();
2248 DebugLoc dl = Op.getDebugLoc();
2249 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2250 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2251 if (RelocM == Reloc::PIC_) {
2252 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2253 ARMConstantPoolValue *CPV =
2254 ARMConstantPoolConstant::Create(GV,
2255 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2256 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2257 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2258 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2260 MachinePointerInfo::getConstantPool(),
2261 false, false, false, 0);
2262 SDValue Chain = Result.getValue(1);
2263 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2264 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2266 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2267 MachinePointerInfo::getGOT(),
2268 false, false, false, 0);
2272 // If we have T2 ops, we can materialize the address directly via movt/movw
2273 // pair. This is always cheaper.
2274 if (Subtarget->useMovt()) {
2276 // FIXME: Once remat is capable of dealing with instructions with register
2277 // operands, expand this into two nodes.
2278 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2279 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2281 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2282 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2283 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2284 MachinePointerInfo::getConstantPool(),
2285 false, false, false, 0);
2289 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2290 SelectionDAG &DAG) const {
2291 EVT PtrVT = getPointerTy();
2292 DebugLoc dl = Op.getDebugLoc();
2293 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2294 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2295 MachineFunction &MF = DAG.getMachineFunction();
2296 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2298 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2299 // update ARMFastISel::ARMMaterializeGV.
2300 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2302 // FIXME: Once remat is capable of dealing with instructions with register
2303 // operands, expand this into two nodes.
2304 if (RelocM == Reloc::Static)
2305 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2306 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2308 unsigned Wrapper = (RelocM == Reloc::PIC_)
2309 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2310 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2311 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2312 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2313 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2314 MachinePointerInfo::getGOT(),
2315 false, false, false, 0);
2319 unsigned ARMPCLabelIndex = 0;
2321 if (RelocM == Reloc::Static) {
2322 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2324 ARMPCLabelIndex = AFI->createPICLabelUId();
2325 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2326 ARMConstantPoolValue *CPV =
2327 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2329 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2331 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2333 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2334 MachinePointerInfo::getConstantPool(),
2335 false, false, false, 0);
2336 SDValue Chain = Result.getValue(1);
2338 if (RelocM == Reloc::PIC_) {
2339 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2340 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2343 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2344 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2345 false, false, false, 0);
2350 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2351 SelectionDAG &DAG) const {
2352 assert(Subtarget->isTargetELF() &&
2353 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2354 MachineFunction &MF = DAG.getMachineFunction();
2355 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2356 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2357 EVT PtrVT = getPointerTy();
2358 DebugLoc dl = Op.getDebugLoc();
2359 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2360 ARMConstantPoolValue *CPV =
2361 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2362 ARMPCLabelIndex, PCAdj);
2363 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2364 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2365 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2366 MachinePointerInfo::getConstantPool(),
2367 false, false, false, 0);
2368 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2369 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2373 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2374 DebugLoc dl = Op.getDebugLoc();
2375 SDValue Val = DAG.getConstant(0, MVT::i32);
2376 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2377 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2378 Op.getOperand(1), Val);
2382 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2383 DebugLoc dl = Op.getDebugLoc();
2384 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2385 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2389 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2390 const ARMSubtarget *Subtarget) const {
2391 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2392 DebugLoc dl = Op.getDebugLoc();
2394 default: return SDValue(); // Don't custom lower most intrinsics.
2395 case Intrinsic::arm_thread_pointer: {
2396 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2397 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2399 case Intrinsic::eh_sjlj_lsda: {
2400 MachineFunction &MF = DAG.getMachineFunction();
2401 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2402 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2403 EVT PtrVT = getPointerTy();
2404 DebugLoc dl = Op.getDebugLoc();
2405 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2407 unsigned PCAdj = (RelocM != Reloc::PIC_)
2408 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2409 ARMConstantPoolValue *CPV =
2410 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2411 ARMCP::CPLSDA, PCAdj);
2412 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2413 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2415 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2416 MachinePointerInfo::getConstantPool(),
2417 false, false, false, 0);
2419 if (RelocM == Reloc::PIC_) {
2420 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2421 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2425 case Intrinsic::arm_neon_vmulls:
2426 case Intrinsic::arm_neon_vmullu: {
2427 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2428 ? ARMISD::VMULLs : ARMISD::VMULLu;
2429 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2430 Op.getOperand(1), Op.getOperand(2));
2435 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2436 const ARMSubtarget *Subtarget) {
2437 DebugLoc dl = Op.getDebugLoc();
2438 if (!Subtarget->hasDataBarrier()) {
2439 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2440 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2442 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2443 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2444 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2445 DAG.getConstant(0, MVT::i32));
2448 SDValue Op5 = Op.getOperand(5);
2449 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2450 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2451 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2452 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2454 ARM_MB::MemBOpt DMBOpt;
2455 if (isDeviceBarrier)
2456 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2458 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2459 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2460 DAG.getConstant(DMBOpt, MVT::i32));
2464 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2465 const ARMSubtarget *Subtarget) {
2466 // FIXME: handle "fence singlethread" more efficiently.
2467 DebugLoc dl = Op.getDebugLoc();
2468 if (!Subtarget->hasDataBarrier()) {
2469 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2470 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2472 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2473 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2474 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2475 DAG.getConstant(0, MVT::i32));
2478 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2479 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2482 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2483 const ARMSubtarget *Subtarget) {
2484 // ARM pre v5TE and Thumb1 does not have preload instructions.
2485 if (!(Subtarget->isThumb2() ||
2486 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2487 // Just preserve the chain.
2488 return Op.getOperand(0);
2490 DebugLoc dl = Op.getDebugLoc();
2491 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2493 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2494 // ARMv7 with MP extension has PLDW.
2495 return Op.getOperand(0);
2497 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2498 if (Subtarget->isThumb()) {
2500 isRead = ~isRead & 1;
2501 isData = ~isData & 1;
2504 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2505 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2506 DAG.getConstant(isData, MVT::i32));
2509 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2510 MachineFunction &MF = DAG.getMachineFunction();
2511 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2513 // vastart just stores the address of the VarArgsFrameIndex slot into the
2514 // memory location argument.
2515 DebugLoc dl = Op.getDebugLoc();
2516 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2517 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2518 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2519 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2520 MachinePointerInfo(SV), false, false, 0);
2524 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2525 SDValue &Root, SelectionDAG &DAG,
2526 DebugLoc dl) const {
2527 MachineFunction &MF = DAG.getMachineFunction();
2528 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2530 const TargetRegisterClass *RC;
2531 if (AFI->isThumb1OnlyFunction())
2532 RC = &ARM::tGPRRegClass;
2534 RC = &ARM::GPRRegClass;
2536 // Transform the arguments stored in physical registers into virtual ones.
2537 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2538 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2541 if (NextVA.isMemLoc()) {
2542 MachineFrameInfo *MFI = MF.getFrameInfo();
2543 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2545 // Create load node to retrieve arguments from the stack.
2546 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2547 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2548 MachinePointerInfo::getFixedStack(FI),
2549 false, false, false, 0);
2551 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2552 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2555 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2559 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2560 unsigned &VARegSize, unsigned &VARegSaveSize)
2563 if (CCInfo.isFirstByValRegValid())
2564 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2566 unsigned int firstUnalloced;
2567 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2568 sizeof(GPRArgRegs) /
2569 sizeof(GPRArgRegs[0]));
2570 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2573 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2574 VARegSize = NumGPRs * 4;
2575 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2578 // The remaining GPRs hold either the beginning of variable-argument
2579 // data, or the beginning of an aggregate passed by value (usually
2580 // byval). Either way, we allocate stack slots adjacent to the data
2581 // provided by our caller, and store the unallocated registers there.
2582 // If this is a variadic function, the va_list pointer will begin with
2583 // these values; otherwise, this reassembles a (byval) structure that
2584 // was split between registers and memory.
2586 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2587 DebugLoc dl, SDValue &Chain,
2588 const Value *OrigArg,
2589 unsigned OffsetFromOrigArg,
2591 bool ForceMutable) const {
2592 MachineFunction &MF = DAG.getMachineFunction();
2593 MachineFrameInfo *MFI = MF.getFrameInfo();
2594 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2595 unsigned firstRegToSaveIndex;
2596 if (CCInfo.isFirstByValRegValid())
2597 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2599 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2600 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2603 unsigned VARegSize, VARegSaveSize;
2604 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2605 if (VARegSaveSize) {
2606 // If this function is vararg, store any remaining integer argument regs
2607 // to their spots on the stack so that they may be loaded by deferencing
2608 // the result of va_next.
2609 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2610 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2611 ArgOffset + VARegSaveSize
2614 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2617 SmallVector<SDValue, 4> MemOps;
2618 for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2619 const TargetRegisterClass *RC;
2620 if (AFI->isThumb1OnlyFunction())
2621 RC = &ARM::tGPRRegClass;
2623 RC = &ARM::GPRRegClass;
2625 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2626 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2628 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2629 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2631 MemOps.push_back(Store);
2632 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2633 DAG.getConstant(4, getPointerTy()));
2635 if (!MemOps.empty())
2636 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2637 &MemOps[0], MemOps.size());
2639 // This will point to the next argument passed via stack.
2640 AFI->setVarArgsFrameIndex(
2641 MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2645 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2646 CallingConv::ID CallConv, bool isVarArg,
2647 const SmallVectorImpl<ISD::InputArg>
2649 DebugLoc dl, SelectionDAG &DAG,
2650 SmallVectorImpl<SDValue> &InVals)
2652 MachineFunction &MF = DAG.getMachineFunction();
2653 MachineFrameInfo *MFI = MF.getFrameInfo();
2655 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2657 // Assign locations to all of the incoming arguments.
2658 SmallVector<CCValAssign, 16> ArgLocs;
2659 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2660 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2661 CCInfo.AnalyzeFormalArguments(Ins,
2662 CCAssignFnForNode(CallConv, /* Return*/ false,
2665 SmallVector<SDValue, 16> ArgValues;
2666 int lastInsIndex = -1;
2668 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2669 unsigned CurArgIdx = 0;
2670 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2671 CCValAssign &VA = ArgLocs[i];
2672 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2673 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2674 // Arguments stored in registers.
2675 if (VA.isRegLoc()) {
2676 EVT RegVT = VA.getLocVT();
2678 if (VA.needsCustom()) {
2679 // f64 and vector types are split up into multiple registers or
2680 // combinations of registers and stack slots.
2681 if (VA.getLocVT() == MVT::v2f64) {
2682 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2684 VA = ArgLocs[++i]; // skip ahead to next loc
2686 if (VA.isMemLoc()) {
2687 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2688 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2689 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2690 MachinePointerInfo::getFixedStack(FI),
2691 false, false, false, 0);
2693 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2696 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2697 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2698 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2699 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2700 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2702 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2705 const TargetRegisterClass *RC;
2707 if (RegVT == MVT::f32)
2708 RC = &ARM::SPRRegClass;
2709 else if (RegVT == MVT::f64)
2710 RC = &ARM::DPRRegClass;
2711 else if (RegVT == MVT::v2f64)
2712 RC = &ARM::QPRRegClass;
2713 else if (RegVT == MVT::i32)
2714 RC = AFI->isThumb1OnlyFunction() ?
2715 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2716 (const TargetRegisterClass*)&ARM::GPRRegClass;
2718 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2720 // Transform the arguments in physical registers into virtual ones.
2721 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2722 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2725 // If this is an 8 or 16-bit value, it is really passed promoted
2726 // to 32 bits. Insert an assert[sz]ext to capture this, then
2727 // truncate to the right size.
2728 switch (VA.getLocInfo()) {
2729 default: llvm_unreachable("Unknown loc info!");
2730 case CCValAssign::Full: break;
2731 case CCValAssign::BCvt:
2732 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2734 case CCValAssign::SExt:
2735 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2736 DAG.getValueType(VA.getValVT()));
2737 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2739 case CCValAssign::ZExt:
2740 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2741 DAG.getValueType(VA.getValVT()));
2742 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2746 InVals.push_back(ArgValue);
2748 } else { // VA.isRegLoc()
2751 assert(VA.isMemLoc());
2752 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2754 int index = ArgLocs[i].getValNo();
2756 // Some Ins[] entries become multiple ArgLoc[] entries.
2757 // Process them only once.
2758 if (index != lastInsIndex)
2760 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2761 // FIXME: For now, all byval parameter objects are marked mutable.
2762 // This can be changed with more analysis.
2763 // In case of tail call optimization mark all arguments mutable.
2764 // Since they could be overwritten by lowering of arguments in case of
2766 if (Flags.isByVal()) {
2767 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2768 if (!AFI->getVarArgsFrameIndex()) {
2769 VarArgStyleRegisters(CCInfo, DAG,
2770 dl, Chain, CurOrigArg,
2771 Ins[VA.getValNo()].PartOffset,
2772 VA.getLocMemOffset(),
2773 true /*force mutable frames*/);
2774 int VAFrameIndex = AFI->getVarArgsFrameIndex();
2775 InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2777 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2778 VA.getLocMemOffset(), false);
2779 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2782 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2783 VA.getLocMemOffset(), true);
2785 // Create load nodes to retrieve arguments from the stack.
2786 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2787 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2788 MachinePointerInfo::getFixedStack(FI),
2789 false, false, false, 0));
2791 lastInsIndex = index;
2798 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2799 CCInfo.getNextStackOffset());
2804 /// isFloatingPointZero - Return true if this is +0.0.
2805 static bool isFloatingPointZero(SDValue Op) {
2806 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2807 return CFP->getValueAPF().isPosZero();
2808 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2809 // Maybe this has already been legalized into the constant pool?
2810 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2811 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2812 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2813 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2814 return CFP->getValueAPF().isPosZero();
2820 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2821 /// the given operands.
2823 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2824 SDValue &ARMcc, SelectionDAG &DAG,
2825 DebugLoc dl) const {
2826 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2827 unsigned C = RHSC->getZExtValue();
2828 if (!isLegalICmpImmediate(C)) {
2829 // Constant does not fit, try adjusting it by one?
2834 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2835 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2836 RHS = DAG.getConstant(C-1, MVT::i32);
2841 if (C != 0 && isLegalICmpImmediate(C-1)) {
2842 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2843 RHS = DAG.getConstant(C-1, MVT::i32);
2848 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2849 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2850 RHS = DAG.getConstant(C+1, MVT::i32);
2855 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2856 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2857 RHS = DAG.getConstant(C+1, MVT::i32);
2864 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2865 ARMISD::NodeType CompareType;
2868 CompareType = ARMISD::CMP;
2873 CompareType = ARMISD::CMPZ;
2876 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2877 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2880 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2882 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2883 DebugLoc dl) const {
2885 if (!isFloatingPointZero(RHS))
2886 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2888 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2889 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2892 /// duplicateCmp - Glue values can have only one use, so this function
2893 /// duplicates a comparison node.
2895 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2896 unsigned Opc = Cmp.getOpcode();
2897 DebugLoc DL = Cmp.getDebugLoc();
2898 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2899 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2901 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2902 Cmp = Cmp.getOperand(0);
2903 Opc = Cmp.getOpcode();
2904 if (Opc == ARMISD::CMPFP)
2905 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2907 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2908 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2910 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2913 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2914 SDValue Cond = Op.getOperand(0);
2915 SDValue SelectTrue = Op.getOperand(1);
2916 SDValue SelectFalse = Op.getOperand(2);
2917 DebugLoc dl = Op.getDebugLoc();
2921 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2922 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2924 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2925 const ConstantSDNode *CMOVTrue =
2926 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2927 const ConstantSDNode *CMOVFalse =
2928 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2930 if (CMOVTrue && CMOVFalse) {
2931 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2932 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2936 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2938 False = SelectFalse;
2939 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2944 if (True.getNode() && False.getNode()) {
2945 EVT VT = Op.getValueType();
2946 SDValue ARMcc = Cond.getOperand(2);
2947 SDValue CCR = Cond.getOperand(3);
2948 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2949 assert(True.getValueType() == VT);
2950 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2955 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2956 // undefined bits before doing a full-word comparison with zero.
2957 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2958 DAG.getConstant(1, Cond.getValueType()));
2960 return DAG.getSelectCC(dl, Cond,
2961 DAG.getConstant(0, Cond.getValueType()),
2962 SelectTrue, SelectFalse, ISD::SETNE);
2965 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2966 EVT VT = Op.getValueType();
2967 SDValue LHS = Op.getOperand(0);
2968 SDValue RHS = Op.getOperand(1);
2969 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2970 SDValue TrueVal = Op.getOperand(2);
2971 SDValue FalseVal = Op.getOperand(3);
2972 DebugLoc dl = Op.getDebugLoc();
2974 if (LHS.getValueType() == MVT::i32) {
2976 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2977 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2978 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2981 ARMCC::CondCodes CondCode, CondCode2;
2982 FPCCToARMCC(CC, CondCode, CondCode2);
2984 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2985 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2986 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2987 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2989 if (CondCode2 != ARMCC::AL) {
2990 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2991 // FIXME: Needs another CMP because flag can have but one use.
2992 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2993 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2994 Result, TrueVal, ARMcc2, CCR, Cmp2);
2999 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3000 /// to morph to an integer compare sequence.
3001 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3002 const ARMSubtarget *Subtarget) {
3003 SDNode *N = Op.getNode();
3004 if (!N->hasOneUse())
3005 // Otherwise it requires moving the value from fp to integer registers.
3007 if (!N->getNumValues())
3009 EVT VT = Op.getValueType();
3010 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3011 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3012 // vmrs are very slow, e.g. cortex-a8.
3015 if (isFloatingPointZero(Op)) {
3019 return ISD::isNormalLoad(N);
3022 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3023 if (isFloatingPointZero(Op))
3024 return DAG.getConstant(0, MVT::i32);
3026 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3027 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3028 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3029 Ld->isVolatile(), Ld->isNonTemporal(),
3030 Ld->isInvariant(), Ld->getAlignment());
3032 llvm_unreachable("Unknown VFP cmp argument!");
3035 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3036 SDValue &RetVal1, SDValue &RetVal2) {
3037 if (isFloatingPointZero(Op)) {
3038 RetVal1 = DAG.getConstant(0, MVT::i32);
3039 RetVal2 = DAG.getConstant(0, MVT::i32);
3043 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3044 SDValue Ptr = Ld->getBasePtr();
3045 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3046 Ld->getChain(), Ptr,
3047 Ld->getPointerInfo(),
3048 Ld->isVolatile(), Ld->isNonTemporal(),
3049 Ld->isInvariant(), Ld->getAlignment());
3051 EVT PtrType = Ptr.getValueType();
3052 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3053 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3054 PtrType, Ptr, DAG.getConstant(4, PtrType));
3055 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3056 Ld->getChain(), NewPtr,
3057 Ld->getPointerInfo().getWithOffset(4),
3058 Ld->isVolatile(), Ld->isNonTemporal(),
3059 Ld->isInvariant(), NewAlign);
3063 llvm_unreachable("Unknown VFP cmp argument!");
3066 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3067 /// f32 and even f64 comparisons to integer ones.
3069 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3070 SDValue Chain = Op.getOperand(0);
3071 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3072 SDValue LHS = Op.getOperand(2);
3073 SDValue RHS = Op.getOperand(3);
3074 SDValue Dest = Op.getOperand(4);
3075 DebugLoc dl = Op.getDebugLoc();
3077 bool LHSSeenZero = false;
3078 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3079 bool RHSSeenZero = false;
3080 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3081 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3082 // If unsafe fp math optimization is enabled and there are no other uses of
3083 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3084 // to an integer comparison.
3085 if (CC == ISD::SETOEQ)
3087 else if (CC == ISD::SETUNE)
3090 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3092 if (LHS.getValueType() == MVT::f32) {
3093 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3094 bitcastf32Toi32(LHS, DAG), Mask);
3095 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3096 bitcastf32Toi32(RHS, DAG), Mask);
3097 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3098 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3099 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3100 Chain, Dest, ARMcc, CCR, Cmp);
3105 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3106 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3107 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3108 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3109 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3110 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3111 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3112 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3113 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3119 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3120 SDValue Chain = Op.getOperand(0);
3121 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3122 SDValue LHS = Op.getOperand(2);
3123 SDValue RHS = Op.getOperand(3);
3124 SDValue Dest = Op.getOperand(4);
3125 DebugLoc dl = Op.getDebugLoc();
3127 if (LHS.getValueType() == MVT::i32) {
3129 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3130 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3131 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3132 Chain, Dest, ARMcc, CCR, Cmp);
3135 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3137 if (getTargetMachine().Options.UnsafeFPMath &&
3138 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3139 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3140 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3141 if (Result.getNode())
3145 ARMCC::CondCodes CondCode, CondCode2;
3146 FPCCToARMCC(CC, CondCode, CondCode2);
3148 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3149 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3150 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3151 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3152 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3153 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3154 if (CondCode2 != ARMCC::AL) {
3155 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3156 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3157 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3162 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3163 SDValue Chain = Op.getOperand(0);
3164 SDValue Table = Op.getOperand(1);
3165 SDValue Index = Op.getOperand(2);
3166 DebugLoc dl = Op.getDebugLoc();
3168 EVT PTy = getPointerTy();
3169 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3170 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3171 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3172 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3173 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3174 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3175 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3176 if (Subtarget->isThumb2()) {
3177 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3178 // which does another jump to the destination. This also makes it easier
3179 // to translate it to TBB / TBH later.
3180 // FIXME: This might not work if the function is extremely large.
3181 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3182 Addr, Op.getOperand(2), JTI, UId);
3184 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3185 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3186 MachinePointerInfo::getJumpTable(),
3187 false, false, false, 0);
3188 Chain = Addr.getValue(1);
3189 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3190 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3192 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3193 MachinePointerInfo::getJumpTable(),
3194 false, false, false, 0);
3195 Chain = Addr.getValue(1);
3196 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3200 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3201 EVT VT = Op.getValueType();
3202 DebugLoc dl = Op.getDebugLoc();
3204 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3205 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3207 return DAG.UnrollVectorOp(Op.getNode());
3210 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3211 "Invalid type for custom lowering!");
3212 if (VT != MVT::v4i16)
3213 return DAG.UnrollVectorOp(Op.getNode());
3215 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3216 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3219 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3220 EVT VT = Op.getValueType();
3222 return LowerVectorFP_TO_INT(Op, DAG);
3224 DebugLoc dl = Op.getDebugLoc();
3227 switch (Op.getOpcode()) {
3228 default: llvm_unreachable("Invalid opcode!");
3229 case ISD::FP_TO_SINT:
3230 Opc = ARMISD::FTOSI;
3232 case ISD::FP_TO_UINT:
3233 Opc = ARMISD::FTOUI;
3236 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3237 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3240 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3241 EVT VT = Op.getValueType();
3242 DebugLoc dl = Op.getDebugLoc();
3244 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3245 if (VT.getVectorElementType() == MVT::f32)
3247 return DAG.UnrollVectorOp(Op.getNode());
3250 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3251 "Invalid type for custom lowering!");
3252 if (VT != MVT::v4f32)
3253 return DAG.UnrollVectorOp(Op.getNode());
3257 switch (Op.getOpcode()) {
3258 default: llvm_unreachable("Invalid opcode!");
3259 case ISD::SINT_TO_FP:
3260 CastOpc = ISD::SIGN_EXTEND;
3261 Opc = ISD::SINT_TO_FP;
3263 case ISD::UINT_TO_FP:
3264 CastOpc = ISD::ZERO_EXTEND;
3265 Opc = ISD::UINT_TO_FP;
3269 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3270 return DAG.getNode(Opc, dl, VT, Op);
3273 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3274 EVT VT = Op.getValueType();
3276 return LowerVectorINT_TO_FP(Op, DAG);
3278 DebugLoc dl = Op.getDebugLoc();
3281 switch (Op.getOpcode()) {
3282 default: llvm_unreachable("Invalid opcode!");
3283 case ISD::SINT_TO_FP:
3284 Opc = ARMISD::SITOF;
3286 case ISD::UINT_TO_FP:
3287 Opc = ARMISD::UITOF;
3291 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3292 return DAG.getNode(Opc, dl, VT, Op);
3295 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3296 // Implement fcopysign with a fabs and a conditional fneg.
3297 SDValue Tmp0 = Op.getOperand(0);
3298 SDValue Tmp1 = Op.getOperand(1);
3299 DebugLoc dl = Op.getDebugLoc();
3300 EVT VT = Op.getValueType();
3301 EVT SrcVT = Tmp1.getValueType();
3302 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3303 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3304 bool UseNEON = !InGPR && Subtarget->hasNEON();
3307 // Use VBSL to copy the sign bit.
3308 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3309 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3310 DAG.getTargetConstant(EncodedVal, MVT::i32));
3311 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3313 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3314 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3315 DAG.getConstant(32, MVT::i32));
3316 else /*if (VT == MVT::f32)*/
3317 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3318 if (SrcVT == MVT::f32) {
3319 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3321 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3322 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3323 DAG.getConstant(32, MVT::i32));
3324 } else if (VT == MVT::f32)
3325 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3326 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3327 DAG.getConstant(32, MVT::i32));
3328 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3329 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3331 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3333 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3334 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3335 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3337 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3338 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3339 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3340 if (VT == MVT::f32) {
3341 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3342 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3343 DAG.getConstant(0, MVT::i32));
3345 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3351 // Bitcast operand 1 to i32.
3352 if (SrcVT == MVT::f64)
3353 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3354 &Tmp1, 1).getValue(1);
3355 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3357 // Or in the signbit with integer operations.
3358 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3359 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3360 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3361 if (VT == MVT::f32) {
3362 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3363 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3364 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3365 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3368 // f64: Or the high part with signbit and then combine two parts.
3369 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3371 SDValue Lo = Tmp0.getValue(0);
3372 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3373 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3374 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3377 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3378 MachineFunction &MF = DAG.getMachineFunction();
3379 MachineFrameInfo *MFI = MF.getFrameInfo();
3380 MFI->setReturnAddressIsTaken(true);
3382 EVT VT = Op.getValueType();
3383 DebugLoc dl = Op.getDebugLoc();
3384 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3386 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3387 SDValue Offset = DAG.getConstant(4, MVT::i32);
3388 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3389 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3390 MachinePointerInfo(), false, false, false, 0);
3393 // Return LR, which contains the return address. Mark it an implicit live-in.
3394 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3395 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3398 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3399 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3400 MFI->setFrameAddressIsTaken(true);
3402 EVT VT = Op.getValueType();
3403 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3404 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3405 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3406 ? ARM::R7 : ARM::R11;
3407 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3409 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3410 MachinePointerInfo(),
3411 false, false, false, 0);
3415 /// ExpandBITCAST - If the target supports VFP, this function is called to
3416 /// expand a bit convert where either the source or destination type is i64 to
3417 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3418 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3419 /// vectors), since the legalizer won't know what to do with that.
3420 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3421 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3422 DebugLoc dl = N->getDebugLoc();
3423 SDValue Op = N->getOperand(0);
3425 // This function is only supposed to be called for i64 types, either as the
3426 // source or destination of the bit convert.
3427 EVT SrcVT = Op.getValueType();
3428 EVT DstVT = N->getValueType(0);
3429 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3430 "ExpandBITCAST called for non-i64 type");
3432 // Turn i64->f64 into VMOVDRR.
3433 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3434 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3435 DAG.getConstant(0, MVT::i32));
3436 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3437 DAG.getConstant(1, MVT::i32));
3438 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3439 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3442 // Turn f64->i64 into VMOVRRD.
3443 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3444 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3445 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3446 // Merge the pieces into a single i64 value.
3447 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3453 /// getZeroVector - Returns a vector of specified type with all zero elements.
3454 /// Zero vectors are used to represent vector negation and in those cases
3455 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3456 /// not support i64 elements, so sometimes the zero vectors will need to be
3457 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3459 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3460 assert(VT.isVector() && "Expected a vector type");
3461 // The canonical modified immediate encoding of a zero vector is....0!
3462 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3463 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3464 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3465 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3468 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3469 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3470 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3471 SelectionDAG &DAG) const {
3472 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3473 EVT VT = Op.getValueType();
3474 unsigned VTBits = VT.getSizeInBits();
3475 DebugLoc dl = Op.getDebugLoc();
3476 SDValue ShOpLo = Op.getOperand(0);
3477 SDValue ShOpHi = Op.getOperand(1);
3478 SDValue ShAmt = Op.getOperand(2);
3480 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3482 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3484 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3485 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3486 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3487 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3488 DAG.getConstant(VTBits, MVT::i32));
3489 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3490 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3491 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3493 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3494 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3496 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3497 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3500 SDValue Ops[2] = { Lo, Hi };
3501 return DAG.getMergeValues(Ops, 2, dl);
3504 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3505 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3506 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3507 SelectionDAG &DAG) const {
3508 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3509 EVT VT = Op.getValueType();
3510 unsigned VTBits = VT.getSizeInBits();
3511 DebugLoc dl = Op.getDebugLoc();
3512 SDValue ShOpLo = Op.getOperand(0);
3513 SDValue ShOpHi = Op.getOperand(1);
3514 SDValue ShAmt = Op.getOperand(2);
3517 assert(Op.getOpcode() == ISD::SHL_PARTS);
3518 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3519 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3520 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3521 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3522 DAG.getConstant(VTBits, MVT::i32));
3523 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3524 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3526 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3527 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3528 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3530 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3531 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3534 SDValue Ops[2] = { Lo, Hi };
3535 return DAG.getMergeValues(Ops, 2, dl);
3538 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3539 SelectionDAG &DAG) const {
3540 // The rounding mode is in bits 23:22 of the FPSCR.
3541 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3542 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3543 // so that the shift + and get folded into a bitfield extract.
3544 DebugLoc dl = Op.getDebugLoc();
3545 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3546 DAG.getConstant(Intrinsic::arm_get_fpscr,
3548 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3549 DAG.getConstant(1U << 22, MVT::i32));
3550 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3551 DAG.getConstant(22, MVT::i32));
3552 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3553 DAG.getConstant(3, MVT::i32));
3556 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3557 const ARMSubtarget *ST) {
3558 EVT VT = N->getValueType(0);
3559 DebugLoc dl = N->getDebugLoc();
3561 if (!ST->hasV6T2Ops())
3564 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3565 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3568 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3569 /// for each 16-bit element from operand, repeated. The basic idea is to
3570 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3572 /// Trace for v4i16:
3573 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3574 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3575 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3576 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3577 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3578 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3579 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3580 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3581 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3582 EVT VT = N->getValueType(0);
3583 DebugLoc DL = N->getDebugLoc();
3585 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3586 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3587 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3588 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3589 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3590 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3593 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3594 /// bit-count for each 16-bit element from the operand. We need slightly
3595 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3596 /// 64/128-bit registers.
3598 /// Trace for v4i16:
3599 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3600 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3601 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3602 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3603 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3604 EVT VT = N->getValueType(0);
3605 DebugLoc DL = N->getDebugLoc();
3607 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3608 if (VT.is64BitVector()) {
3609 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3610 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3611 DAG.getIntPtrConstant(0));
3613 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3614 BitCounts, DAG.getIntPtrConstant(0));
3615 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3619 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3620 /// bit-count for each 32-bit element from the operand. The idea here is
3621 /// to split the vector into 16-bit elements, leverage the 16-bit count
3622 /// routine, and then combine the results.
3624 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3625 /// input = [v0 v1 ] (vi: 32-bit elements)
3626 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3627 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3628 /// vrev: N0 = [k1 k0 k3 k2 ]
3630 /// N1 =+[k1 k0 k3 k2 ]
3632 /// N2 =+[k1 k3 k0 k2 ]
3634 /// Extended =+[k1 k3 k0 k2 ]
3636 /// Extracted=+[k1 k3 ]
3638 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3639 EVT VT = N->getValueType(0);
3640 DebugLoc DL = N->getDebugLoc();
3642 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3644 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3645 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3646 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3647 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3648 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3650 if (VT.is64BitVector()) {
3651 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3652 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3653 DAG.getIntPtrConstant(0));
3655 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3656 DAG.getIntPtrConstant(0));
3657 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3661 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3662 const ARMSubtarget *ST) {
3663 EVT VT = N->getValueType(0);
3665 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3666 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3667 VT == MVT::v4i16 || VT == MVT::v8i16) &&
3668 "Unexpected type for custom ctpop lowering");
3670 if (VT.getVectorElementType() == MVT::i32)
3671 return lowerCTPOP32BitElements(N, DAG);
3673 return lowerCTPOP16BitElements(N, DAG);
3676 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3677 const ARMSubtarget *ST) {
3678 EVT VT = N->getValueType(0);
3679 DebugLoc dl = N->getDebugLoc();
3684 // Lower vector shifts on NEON to use VSHL.
3685 assert(ST->hasNEON() && "unexpected vector shift");
3687 // Left shifts translate directly to the vshiftu intrinsic.
3688 if (N->getOpcode() == ISD::SHL)
3689 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3690 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3691 N->getOperand(0), N->getOperand(1));
3693 assert((N->getOpcode() == ISD::SRA ||
3694 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3696 // NEON uses the same intrinsics for both left and right shifts. For
3697 // right shifts, the shift amounts are negative, so negate the vector of
3699 EVT ShiftVT = N->getOperand(1).getValueType();
3700 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3701 getZeroVector(ShiftVT, DAG, dl),
3703 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3704 Intrinsic::arm_neon_vshifts :
3705 Intrinsic::arm_neon_vshiftu);
3706 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3707 DAG.getConstant(vshiftInt, MVT::i32),
3708 N->getOperand(0), NegatedCount);
3711 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3712 const ARMSubtarget *ST) {
3713 EVT VT = N->getValueType(0);
3714 DebugLoc dl = N->getDebugLoc();
3716 // We can get here for a node like i32 = ISD::SHL i32, i64
3720 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3721 "Unknown shift to lower!");
3723 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3724 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3725 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3728 // If we are in thumb mode, we don't have RRX.
3729 if (ST->isThumb1Only()) return SDValue();
3731 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3732 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3733 DAG.getConstant(0, MVT::i32));
3734 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3735 DAG.getConstant(1, MVT::i32));
3737 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3738 // captures the result into a carry flag.
3739 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3740 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3742 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3743 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3745 // Merge the pieces into a single i64 value.
3746 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3749 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3750 SDValue TmpOp0, TmpOp1;
3751 bool Invert = false;
3755 SDValue Op0 = Op.getOperand(0);
3756 SDValue Op1 = Op.getOperand(1);
3757 SDValue CC = Op.getOperand(2);
3758 EVT VT = Op.getValueType();
3759 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3760 DebugLoc dl = Op.getDebugLoc();
3762 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3763 switch (SetCCOpcode) {
3764 default: llvm_unreachable("Illegal FP comparison");
3766 case ISD::SETNE: Invert = true; // Fallthrough
3768 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3770 case ISD::SETLT: Swap = true; // Fallthrough
3772 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3774 case ISD::SETLE: Swap = true; // Fallthrough
3776 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3777 case ISD::SETUGE: Swap = true; // Fallthrough
3778 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3779 case ISD::SETUGT: Swap = true; // Fallthrough
3780 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3781 case ISD::SETUEQ: Invert = true; // Fallthrough
3783 // Expand this to (OLT | OGT).
3787 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3788 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3790 case ISD::SETUO: Invert = true; // Fallthrough
3792 // Expand this to (OLT | OGE).
3796 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3797 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3801 // Integer comparisons.
3802 switch (SetCCOpcode) {
3803 default: llvm_unreachable("Illegal integer comparison");
3804 case ISD::SETNE: Invert = true;
3805 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3806 case ISD::SETLT: Swap = true;
3807 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3808 case ISD::SETLE: Swap = true;
3809 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3810 case ISD::SETULT: Swap = true;
3811 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3812 case ISD::SETULE: Swap = true;
3813 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3816 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3817 if (Opc == ARMISD::VCEQ) {
3820 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3822 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3825 // Ignore bitconvert.
3826 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3827 AndOp = AndOp.getOperand(0);
3829 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3831 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3832 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3839 std::swap(Op0, Op1);
3841 // If one of the operands is a constant vector zero, attempt to fold the
3842 // comparison to a specialized compare-against-zero form.
3844 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3846 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3847 if (Opc == ARMISD::VCGE)
3848 Opc = ARMISD::VCLEZ;
3849 else if (Opc == ARMISD::VCGT)
3850 Opc = ARMISD::VCLTZ;
3855 if (SingleOp.getNode()) {
3858 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3860 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3862 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3864 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3866 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3868 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3871 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3875 Result = DAG.getNOT(dl, Result, VT);
3880 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3881 /// valid vector constant for a NEON instruction with a "modified immediate"
3882 /// operand (e.g., VMOV). If so, return the encoded value.
3883 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3884 unsigned SplatBitSize, SelectionDAG &DAG,
3885 EVT &VT, bool is128Bits, NEONModImmType type) {
3886 unsigned OpCmode, Imm;
3888 // SplatBitSize is set to the smallest size that splats the vector, so a
3889 // zero vector will always have SplatBitSize == 8. However, NEON modified
3890 // immediate instructions others than VMOV do not support the 8-bit encoding
3891 // of a zero vector, and the default encoding of zero is supposed to be the
3896 switch (SplatBitSize) {
3898 if (type != VMOVModImm)
3900 // Any 1-byte value is OK. Op=0, Cmode=1110.
3901 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3904 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3908 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3909 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3910 if ((SplatBits & ~0xff) == 0) {
3911 // Value = 0x00nn: Op=x, Cmode=100x.
3916 if ((SplatBits & ~0xff00) == 0) {
3917 // Value = 0xnn00: Op=x, Cmode=101x.
3919 Imm = SplatBits >> 8;
3925 // NEON's 32-bit VMOV supports splat values where:
3926 // * only one byte is nonzero, or
3927 // * the least significant byte is 0xff and the second byte is nonzero, or
3928 // * the least significant 2 bytes are 0xff and the third is nonzero.
3929 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3930 if ((SplatBits & ~0xff) == 0) {
3931 // Value = 0x000000nn: Op=x, Cmode=000x.
3936 if ((SplatBits & ~0xff00) == 0) {
3937 // Value = 0x0000nn00: Op=x, Cmode=001x.
3939 Imm = SplatBits >> 8;
3942 if ((SplatBits & ~0xff0000) == 0) {
3943 // Value = 0x00nn0000: Op=x, Cmode=010x.
3945 Imm = SplatBits >> 16;
3948 if ((SplatBits & ~0xff000000) == 0) {
3949 // Value = 0xnn000000: Op=x, Cmode=011x.
3951 Imm = SplatBits >> 24;
3955 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3956 if (type == OtherModImm) return SDValue();
3958 if ((SplatBits & ~0xffff) == 0 &&
3959 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3960 // Value = 0x0000nnff: Op=x, Cmode=1100.
3962 Imm = SplatBits >> 8;
3967 if ((SplatBits & ~0xffffff) == 0 &&
3968 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3969 // Value = 0x00nnffff: Op=x, Cmode=1101.
3971 Imm = SplatBits >> 16;
3972 SplatBits |= 0xffff;
3976 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3977 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3978 // VMOV.I32. A (very) minor optimization would be to replicate the value
3979 // and fall through here to test for a valid 64-bit splat. But, then the
3980 // caller would also need to check and handle the change in size.
3984 if (type != VMOVModImm)
3986 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3987 uint64_t BitMask = 0xff;
3989 unsigned ImmMask = 1;
3991 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3992 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3995 } else if ((SplatBits & BitMask) != 0) {
4001 // Op=1, Cmode=1110.
4004 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4009 llvm_unreachable("unexpected size for isNEONModifiedImm");
4012 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4013 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4016 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4017 const ARMSubtarget *ST) const {
4018 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4021 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4022 assert(Op.getValueType() == MVT::f32 &&
4023 "ConstantFP custom lowering should only occur for f32.");
4025 // Try splatting with a VMOV.f32...
4026 APFloat FPVal = CFP->getValueAPF();
4027 int ImmVal = ARM_AM::getFP32Imm(FPVal);
4029 DebugLoc DL = Op.getDebugLoc();
4030 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4031 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4033 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4034 DAG.getConstant(0, MVT::i32));
4037 // If that fails, try a VMOV.i32
4039 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4040 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4042 if (NewVal != SDValue()) {
4043 DebugLoc DL = Op.getDebugLoc();
4044 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4046 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4048 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4049 DAG.getConstant(0, MVT::i32));
4052 // Finally, try a VMVN.i32
4053 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4055 if (NewVal != SDValue()) {
4056 DebugLoc DL = Op.getDebugLoc();
4057 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4058 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4060 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4061 DAG.getConstant(0, MVT::i32));
4067 // check if an VEXT instruction can handle the shuffle mask when the
4068 // vector sources of the shuffle are the same.
4069 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4070 unsigned NumElts = VT.getVectorNumElements();
4072 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4078 // If this is a VEXT shuffle, the immediate value is the index of the first
4079 // element. The other shuffle indices must be the successive elements after
4081 unsigned ExpectedElt = Imm;
4082 for (unsigned i = 1; i < NumElts; ++i) {
4083 // Increment the expected index. If it wraps around, just follow it
4084 // back to index zero and keep going.
4086 if (ExpectedElt == NumElts)
4089 if (M[i] < 0) continue; // ignore UNDEF indices
4090 if (ExpectedElt != static_cast<unsigned>(M[i]))
4098 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4099 bool &ReverseVEXT, unsigned &Imm) {
4100 unsigned NumElts = VT.getVectorNumElements();
4101 ReverseVEXT = false;
4103 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4109 // If this is a VEXT shuffle, the immediate value is the index of the first
4110 // element. The other shuffle indices must be the successive elements after
4112 unsigned ExpectedElt = Imm;
4113 for (unsigned i = 1; i < NumElts; ++i) {
4114 // Increment the expected index. If it wraps around, it may still be
4115 // a VEXT but the source vectors must be swapped.
4117 if (ExpectedElt == NumElts * 2) {
4122 if (M[i] < 0) continue; // ignore UNDEF indices
4123 if (ExpectedElt != static_cast<unsigned>(M[i]))
4127 // Adjust the index value if the source operands will be swapped.
4134 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4135 /// instruction with the specified blocksize. (The order of the elements
4136 /// within each block of the vector is reversed.)
4137 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4138 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4139 "Only possible block sizes for VREV are: 16, 32, 64");
4141 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4145 unsigned NumElts = VT.getVectorNumElements();
4146 unsigned BlockElts = M[0] + 1;
4147 // If the first shuffle index is UNDEF, be optimistic.
4149 BlockElts = BlockSize / EltSz;
4151 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4154 for (unsigned i = 0; i < NumElts; ++i) {
4155 if (M[i] < 0) continue; // ignore UNDEF indices
4156 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4163 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4164 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4165 // range, then 0 is placed into the resulting vector. So pretty much any mask
4166 // of 8 elements can work here.
4167 return VT == MVT::v8i8 && M.size() == 8;
4170 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4171 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4175 unsigned NumElts = VT.getVectorNumElements();
4176 WhichResult = (M[0] == 0 ? 0 : 1);
4177 for (unsigned i = 0; i < NumElts; i += 2) {
4178 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4179 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4185 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4186 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4187 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4188 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4189 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4193 unsigned NumElts = VT.getVectorNumElements();
4194 WhichResult = (M[0] == 0 ? 0 : 1);
4195 for (unsigned i = 0; i < NumElts; i += 2) {
4196 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4197 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4203 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4204 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4208 unsigned NumElts = VT.getVectorNumElements();
4209 WhichResult = (M[0] == 0 ? 0 : 1);
4210 for (unsigned i = 0; i != NumElts; ++i) {
4211 if (M[i] < 0) continue; // ignore UNDEF indices
4212 if ((unsigned) M[i] != 2 * i + WhichResult)
4216 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4217 if (VT.is64BitVector() && EltSz == 32)
4223 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4224 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4225 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4226 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4227 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4231 unsigned Half = VT.getVectorNumElements() / 2;
4232 WhichResult = (M[0] == 0 ? 0 : 1);
4233 for (unsigned j = 0; j != 2; ++j) {
4234 unsigned Idx = WhichResult;
4235 for (unsigned i = 0; i != Half; ++i) {
4236 int MIdx = M[i + j * Half];
4237 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4243 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4244 if (VT.is64BitVector() && EltSz == 32)
4250 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4251 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4255 unsigned NumElts = VT.getVectorNumElements();
4256 WhichResult = (M[0] == 0 ? 0 : 1);
4257 unsigned Idx = WhichResult * NumElts / 2;
4258 for (unsigned i = 0; i != NumElts; i += 2) {
4259 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4260 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4265 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4266 if (VT.is64BitVector() && EltSz == 32)
4272 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4273 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4274 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4275 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4276 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4280 unsigned NumElts = VT.getVectorNumElements();
4281 WhichResult = (M[0] == 0 ? 0 : 1);
4282 unsigned Idx = WhichResult * NumElts / 2;
4283 for (unsigned i = 0; i != NumElts; i += 2) {
4284 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4285 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4290 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4291 if (VT.is64BitVector() && EltSz == 32)
4297 /// \return true if this is a reverse operation on an vector.
4298 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4299 unsigned NumElts = VT.getVectorNumElements();
4300 // Make sure the mask has the right size.
4301 if (NumElts != M.size())
4304 // Look for <15, ..., 3, -1, 1, 0>.
4305 for (unsigned i = 0; i != NumElts; ++i)
4306 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4312 // If N is an integer constant that can be moved into a register in one
4313 // instruction, return an SDValue of such a constant (will become a MOV
4314 // instruction). Otherwise return null.
4315 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4316 const ARMSubtarget *ST, DebugLoc dl) {
4318 if (!isa<ConstantSDNode>(N))
4320 Val = cast<ConstantSDNode>(N)->getZExtValue();
4322 if (ST->isThumb1Only()) {
4323 if (Val <= 255 || ~Val <= 255)
4324 return DAG.getConstant(Val, MVT::i32);
4326 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4327 return DAG.getConstant(Val, MVT::i32);
4332 // If this is a case we can't handle, return null and let the default
4333 // expansion code take care of it.
4334 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4335 const ARMSubtarget *ST) const {
4336 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4337 DebugLoc dl = Op.getDebugLoc();
4338 EVT VT = Op.getValueType();
4340 APInt SplatBits, SplatUndef;
4341 unsigned SplatBitSize;
4343 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4344 if (SplatBitSize <= 64) {
4345 // Check if an immediate VMOV works.
4347 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4348 SplatUndef.getZExtValue(), SplatBitSize,
4349 DAG, VmovVT, VT.is128BitVector(),
4351 if (Val.getNode()) {
4352 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4353 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4356 // Try an immediate VMVN.
4357 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4358 Val = isNEONModifiedImm(NegatedImm,
4359 SplatUndef.getZExtValue(), SplatBitSize,
4360 DAG, VmovVT, VT.is128BitVector(),
4362 if (Val.getNode()) {
4363 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4364 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4367 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4368 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4369 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4371 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4372 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4378 // Scan through the operands to see if only one value is used.
4380 // As an optimisation, even if more than one value is used it may be more
4381 // profitable to splat with one value then change some lanes.
4383 // Heuristically we decide to do this if the vector has a "dominant" value,
4384 // defined as splatted to more than half of the lanes.
4385 unsigned NumElts = VT.getVectorNumElements();
4386 bool isOnlyLowElement = true;
4387 bool usesOnlyOneValue = true;
4388 bool hasDominantValue = false;
4389 bool isConstant = true;
4391 // Map of the number of times a particular SDValue appears in the
4393 DenseMap<SDValue, unsigned> ValueCounts;
4395 for (unsigned i = 0; i < NumElts; ++i) {
4396 SDValue V = Op.getOperand(i);
4397 if (V.getOpcode() == ISD::UNDEF)
4400 isOnlyLowElement = false;
4401 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4404 ValueCounts.insert(std::make_pair(V, 0));
4405 unsigned &Count = ValueCounts[V];
4407 // Is this value dominant? (takes up more than half of the lanes)
4408 if (++Count > (NumElts / 2)) {
4409 hasDominantValue = true;
4413 if (ValueCounts.size() != 1)
4414 usesOnlyOneValue = false;
4415 if (!Value.getNode() && ValueCounts.size() > 0)
4416 Value = ValueCounts.begin()->first;
4418 if (ValueCounts.size() == 0)
4419 return DAG.getUNDEF(VT);
4421 if (isOnlyLowElement)
4422 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4424 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4426 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4427 // i32 and try again.
4428 if (hasDominantValue && EltSize <= 32) {
4432 // If we are VDUPing a value that comes directly from a vector, that will
4433 // cause an unnecessary move to and from a GPR, where instead we could
4434 // just use VDUPLANE.
4435 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4436 // We need to create a new undef vector to use for the VDUPLANE if the
4437 // size of the vector from which we get the value is different than the
4438 // size of the vector that we need to create. We will insert the element
4439 // such that the register coalescer will remove unnecessary copies.
4440 if (VT != Value->getOperand(0).getValueType()) {
4441 ConstantSDNode *constIndex;
4442 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4443 assert(constIndex && "The index is not a constant!");
4444 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4445 VT.getVectorNumElements();
4446 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4447 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4448 Value, DAG.getConstant(index, MVT::i32)),
4449 DAG.getConstant(index, MVT::i32));
4451 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4452 Value->getOperand(0), Value->getOperand(1));
4456 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4458 if (!usesOnlyOneValue) {
4459 // The dominant value was splatted as 'N', but we now have to insert
4460 // all differing elements.
4461 for (unsigned I = 0; I < NumElts; ++I) {
4462 if (Op.getOperand(I) == Value)
4464 SmallVector<SDValue, 3> Ops;
4466 Ops.push_back(Op.getOperand(I));
4467 Ops.push_back(DAG.getConstant(I, MVT::i32));
4468 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4473 if (VT.getVectorElementType().isFloatingPoint()) {
4474 SmallVector<SDValue, 8> Ops;
4475 for (unsigned i = 0; i < NumElts; ++i)
4476 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4478 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4479 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4480 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4482 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4484 if (usesOnlyOneValue) {
4485 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4486 if (isConstant && Val.getNode())
4487 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4491 // If all elements are constants and the case above didn't get hit, fall back
4492 // to the default expansion, which will generate a load from the constant
4497 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4499 SDValue shuffle = ReconstructShuffle(Op, DAG);
4500 if (shuffle != SDValue())
4504 // Vectors with 32- or 64-bit elements can be built by directly assigning
4505 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4506 // will be legalized.
4507 if (EltSize >= 32) {
4508 // Do the expansion with floating-point types, since that is what the VFP
4509 // registers are defined to use, and since i64 is not legal.
4510 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4511 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4512 SmallVector<SDValue, 8> Ops;
4513 for (unsigned i = 0; i < NumElts; ++i)
4514 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4515 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4516 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4522 // Gather data to see if the operation can be modelled as a
4523 // shuffle in combination with VEXTs.
4524 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4525 SelectionDAG &DAG) const {
4526 DebugLoc dl = Op.getDebugLoc();
4527 EVT VT = Op.getValueType();
4528 unsigned NumElts = VT.getVectorNumElements();
4530 SmallVector<SDValue, 2> SourceVecs;
4531 SmallVector<unsigned, 2> MinElts;
4532 SmallVector<unsigned, 2> MaxElts;
4534 for (unsigned i = 0; i < NumElts; ++i) {
4535 SDValue V = Op.getOperand(i);
4536 if (V.getOpcode() == ISD::UNDEF)
4538 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4539 // A shuffle can only come from building a vector from various
4540 // elements of other vectors.
4542 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4543 VT.getVectorElementType()) {
4544 // This code doesn't know how to handle shuffles where the vector
4545 // element types do not match (this happens because type legalization
4546 // promotes the return type of EXTRACT_VECTOR_ELT).
4547 // FIXME: It might be appropriate to extend this code to handle
4548 // mismatched types.
4552 // Record this extraction against the appropriate vector if possible...
4553 SDValue SourceVec = V.getOperand(0);
4554 // If the element number isn't a constant, we can't effectively
4555 // analyze what's going on.
4556 if (!isa<ConstantSDNode>(V.getOperand(1)))
4558 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4559 bool FoundSource = false;
4560 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4561 if (SourceVecs[j] == SourceVec) {
4562 if (MinElts[j] > EltNo)
4564 if (MaxElts[j] < EltNo)
4571 // Or record a new source if not...
4573 SourceVecs.push_back(SourceVec);
4574 MinElts.push_back(EltNo);
4575 MaxElts.push_back(EltNo);
4579 // Currently only do something sane when at most two source vectors
4581 if (SourceVecs.size() > 2)
4584 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4585 int VEXTOffsets[2] = {0, 0};
4587 // This loop extracts the usage patterns of the source vectors
4588 // and prepares appropriate SDValues for a shuffle if possible.
4589 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4590 if (SourceVecs[i].getValueType() == VT) {
4591 // No VEXT necessary
4592 ShuffleSrcs[i] = SourceVecs[i];
4595 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4596 // It probably isn't worth padding out a smaller vector just to
4597 // break it down again in a shuffle.
4601 // Since only 64-bit and 128-bit vectors are legal on ARM and
4602 // we've eliminated the other cases...
4603 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4604 "unexpected vector sizes in ReconstructShuffle");
4606 if (MaxElts[i] - MinElts[i] >= NumElts) {
4607 // Span too large for a VEXT to cope
4611 if (MinElts[i] >= NumElts) {
4612 // The extraction can just take the second half
4613 VEXTOffsets[i] = NumElts;
4614 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4616 DAG.getIntPtrConstant(NumElts));
4617 } else if (MaxElts[i] < NumElts) {
4618 // The extraction can just take the first half
4620 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4622 DAG.getIntPtrConstant(0));
4624 // An actual VEXT is needed
4625 VEXTOffsets[i] = MinElts[i];
4626 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4628 DAG.getIntPtrConstant(0));
4629 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4631 DAG.getIntPtrConstant(NumElts));
4632 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4633 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4637 SmallVector<int, 8> Mask;
4639 for (unsigned i = 0; i < NumElts; ++i) {
4640 SDValue Entry = Op.getOperand(i);
4641 if (Entry.getOpcode() == ISD::UNDEF) {
4646 SDValue ExtractVec = Entry.getOperand(0);
4647 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4648 .getOperand(1))->getSExtValue();
4649 if (ExtractVec == SourceVecs[0]) {
4650 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4652 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4656 // Final check before we try to produce nonsense...
4657 if (isShuffleMaskLegal(Mask, VT))
4658 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4664 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4665 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4666 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4667 /// are assumed to be legal.
4669 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4671 if (VT.getVectorNumElements() == 4 &&
4672 (VT.is128BitVector() || VT.is64BitVector())) {
4673 unsigned PFIndexes[4];
4674 for (unsigned i = 0; i != 4; ++i) {
4678 PFIndexes[i] = M[i];
4681 // Compute the index in the perfect shuffle table.
4682 unsigned PFTableIndex =
4683 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4684 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4685 unsigned Cost = (PFEntry >> 30);
4692 unsigned Imm, WhichResult;
4694 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4695 return (EltSize >= 32 ||
4696 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4697 isVREVMask(M, VT, 64) ||
4698 isVREVMask(M, VT, 32) ||
4699 isVREVMask(M, VT, 16) ||
4700 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4701 isVTBLMask(M, VT) ||
4702 isVTRNMask(M, VT, WhichResult) ||
4703 isVUZPMask(M, VT, WhichResult) ||
4704 isVZIPMask(M, VT, WhichResult) ||
4705 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4706 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4707 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4708 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4711 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4712 /// the specified operations to build the shuffle.
4713 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4714 SDValue RHS, SelectionDAG &DAG,
4716 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4717 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4718 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4721 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4730 OP_VUZPL, // VUZP, left result
4731 OP_VUZPR, // VUZP, right result
4732 OP_VZIPL, // VZIP, left result
4733 OP_VZIPR, // VZIP, right result
4734 OP_VTRNL, // VTRN, left result
4735 OP_VTRNR // VTRN, right result
4738 if (OpNum == OP_COPY) {
4739 if (LHSID == (1*9+2)*9+3) return LHS;
4740 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4744 SDValue OpLHS, OpRHS;
4745 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4746 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4747 EVT VT = OpLHS.getValueType();
4750 default: llvm_unreachable("Unknown shuffle opcode!");
4752 // VREV divides the vector in half and swaps within the half.
4753 if (VT.getVectorElementType() == MVT::i32 ||
4754 VT.getVectorElementType() == MVT::f32)
4755 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4756 // vrev <4 x i16> -> VREV32
4757 if (VT.getVectorElementType() == MVT::i16)
4758 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4759 // vrev <4 x i8> -> VREV16
4760 assert(VT.getVectorElementType() == MVT::i8);
4761 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4766 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4767 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4771 return DAG.getNode(ARMISD::VEXT, dl, VT,
4773 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4776 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4777 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4780 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4781 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4784 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4785 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4789 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4790 ArrayRef<int> ShuffleMask,
4791 SelectionDAG &DAG) {
4792 // Check to see if we can use the VTBL instruction.
4793 SDValue V1 = Op.getOperand(0);
4794 SDValue V2 = Op.getOperand(1);
4795 DebugLoc DL = Op.getDebugLoc();
4797 SmallVector<SDValue, 8> VTBLMask;
4798 for (ArrayRef<int>::iterator
4799 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4800 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4802 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4803 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4804 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4807 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4808 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4812 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
4813 SelectionDAG &DAG) {
4814 DebugLoc DL = Op.getDebugLoc();
4815 SDValue OpLHS = Op.getOperand(0);
4816 EVT VT = OpLHS.getValueType();
4818 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
4819 "Expect an v8i16/v16i8 type");
4820 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
4821 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
4822 // extract the first 8 bytes into the top double word and the last 8 bytes
4823 // into the bottom double word. The v8i16 case is similar.
4824 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
4825 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
4826 DAG.getConstant(ExtractNum, MVT::i32));
4829 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4830 SDValue V1 = Op.getOperand(0);
4831 SDValue V2 = Op.getOperand(1);
4832 DebugLoc dl = Op.getDebugLoc();
4833 EVT VT = Op.getValueType();
4834 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4836 // Convert shuffles that are directly supported on NEON to target-specific
4837 // DAG nodes, instead of keeping them as shuffles and matching them again
4838 // during code selection. This is more efficient and avoids the possibility
4839 // of inconsistencies between legalization and selection.
4840 // FIXME: floating-point vectors should be canonicalized to integer vectors
4841 // of the same time so that they get CSEd properly.
4842 ArrayRef<int> ShuffleMask = SVN->getMask();
4844 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4845 if (EltSize <= 32) {
4846 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4847 int Lane = SVN->getSplatIndex();
4848 // If this is undef splat, generate it via "just" vdup, if possible.
4849 if (Lane == -1) Lane = 0;
4851 // Test if V1 is a SCALAR_TO_VECTOR.
4852 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4853 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4855 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4856 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4858 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4859 !isa<ConstantSDNode>(V1.getOperand(0))) {
4860 bool IsScalarToVector = true;
4861 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4862 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4863 IsScalarToVector = false;
4866 if (IsScalarToVector)
4867 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4869 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4870 DAG.getConstant(Lane, MVT::i32));
4875 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4878 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4879 DAG.getConstant(Imm, MVT::i32));
4882 if (isVREVMask(ShuffleMask, VT, 64))
4883 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4884 if (isVREVMask(ShuffleMask, VT, 32))
4885 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4886 if (isVREVMask(ShuffleMask, VT, 16))
4887 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4889 if (V2->getOpcode() == ISD::UNDEF &&
4890 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4891 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4892 DAG.getConstant(Imm, MVT::i32));
4895 // Check for Neon shuffles that modify both input vectors in place.
4896 // If both results are used, i.e., if there are two shuffles with the same
4897 // source operands and with masks corresponding to both results of one of
4898 // these operations, DAG memoization will ensure that a single node is
4899 // used for both shuffles.
4900 unsigned WhichResult;
4901 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4902 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4903 V1, V2).getValue(WhichResult);
4904 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4905 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4906 V1, V2).getValue(WhichResult);
4907 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4908 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4909 V1, V2).getValue(WhichResult);
4911 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4912 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4913 V1, V1).getValue(WhichResult);
4914 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4915 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4916 V1, V1).getValue(WhichResult);
4917 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4918 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4919 V1, V1).getValue(WhichResult);
4922 // If the shuffle is not directly supported and it has 4 elements, use
4923 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4924 unsigned NumElts = VT.getVectorNumElements();
4926 unsigned PFIndexes[4];
4927 for (unsigned i = 0; i != 4; ++i) {
4928 if (ShuffleMask[i] < 0)
4931 PFIndexes[i] = ShuffleMask[i];
4934 // Compute the index in the perfect shuffle table.
4935 unsigned PFTableIndex =
4936 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4937 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4938 unsigned Cost = (PFEntry >> 30);
4941 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4944 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4945 if (EltSize >= 32) {
4946 // Do the expansion with floating-point types, since that is what the VFP
4947 // registers are defined to use, and since i64 is not legal.
4948 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4949 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4950 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4951 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4952 SmallVector<SDValue, 8> Ops;
4953 for (unsigned i = 0; i < NumElts; ++i) {
4954 if (ShuffleMask[i] < 0)
4955 Ops.push_back(DAG.getUNDEF(EltVT));
4957 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4958 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4959 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4962 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4963 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4966 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
4967 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
4969 if (VT == MVT::v8i8) {
4970 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4971 if (NewOp.getNode())
4978 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4979 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4980 SDValue Lane = Op.getOperand(2);
4981 if (!isa<ConstantSDNode>(Lane))
4987 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4988 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4989 SDValue Lane = Op.getOperand(1);
4990 if (!isa<ConstantSDNode>(Lane))
4993 SDValue Vec = Op.getOperand(0);
4994 if (Op.getValueType() == MVT::i32 &&
4995 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4996 DebugLoc dl = Op.getDebugLoc();
4997 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5003 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5004 // The only time a CONCAT_VECTORS operation can have legal types is when
5005 // two 64-bit vectors are concatenated to a 128-bit vector.
5006 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5007 "unexpected CONCAT_VECTORS");
5008 DebugLoc dl = Op.getDebugLoc();
5009 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5010 SDValue Op0 = Op.getOperand(0);
5011 SDValue Op1 = Op.getOperand(1);
5012 if (Op0.getOpcode() != ISD::UNDEF)
5013 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5014 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5015 DAG.getIntPtrConstant(0));
5016 if (Op1.getOpcode() != ISD::UNDEF)
5017 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5018 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5019 DAG.getIntPtrConstant(1));
5020 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5023 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5024 /// element has been zero/sign-extended, depending on the isSigned parameter,
5025 /// from an integer type half its size.
5026 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5028 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5029 EVT VT = N->getValueType(0);
5030 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5031 SDNode *BVN = N->getOperand(0).getNode();
5032 if (BVN->getValueType(0) != MVT::v4i32 ||
5033 BVN->getOpcode() != ISD::BUILD_VECTOR)
5035 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5036 unsigned HiElt = 1 - LoElt;
5037 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5038 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5039 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5040 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5041 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5044 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5045 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5048 if (Hi0->isNullValue() && Hi1->isNullValue())
5054 if (N->getOpcode() != ISD::BUILD_VECTOR)
5057 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5058 SDNode *Elt = N->getOperand(i).getNode();
5059 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5060 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5061 unsigned HalfSize = EltSize / 2;
5063 if (!isIntN(HalfSize, C->getSExtValue()))
5066 if (!isUIntN(HalfSize, C->getZExtValue()))
5077 /// isSignExtended - Check if a node is a vector value that is sign-extended
5078 /// or a constant BUILD_VECTOR with sign-extended elements.
5079 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5080 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5082 if (isExtendedBUILD_VECTOR(N, DAG, true))
5087 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5088 /// or a constant BUILD_VECTOR with zero-extended elements.
5089 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5090 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5092 if (isExtendedBUILD_VECTOR(N, DAG, false))
5097 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5098 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5099 /// We insert the required extension here to get the vector to fill a D register.
5100 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5103 unsigned ExtOpcode) {
5104 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5105 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5106 // 64-bits we need to insert a new extension so that it will be 64-bits.
5107 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5108 if (OrigTy.getSizeInBits() >= 64)
5111 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5112 MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5114 switch (OrigSimpleTy) {
5115 default: llvm_unreachable("Unexpected Orig Vector Type");
5124 return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5127 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5128 /// does not do any sign/zero extension. If the original vector is less
5129 /// than 64 bits, an appropriate extension will be added after the load to
5130 /// reach a total size of 64 bits. We have to add the extension separately
5131 /// because ARM does not have a sign/zero extending load for vectors.
5132 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5133 SDValue NonExtendingLoad =
5134 DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5135 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5136 LD->isNonTemporal(), LD->isInvariant(),
5137 LD->getAlignment());
5139 switch (LD->getExtensionType()) {
5140 default: llvm_unreachable("Unexpected LoadExtType");
5142 case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5143 case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5145 MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5146 MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5147 return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5148 MemType, ExtType, ExtOp);
5151 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5152 /// extending load, or BUILD_VECTOR with extended elements, return the
5153 /// unextended value. The unextended vector should be 64 bits so that it can
5154 /// be used as an operand to a VMULL instruction. If the original vector size
5155 /// before extension is less than 64 bits we add a an extension to resize
5156 /// the vector to 64 bits.
5157 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5158 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5159 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5160 N->getOperand(0)->getValueType(0),
5164 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5165 return SkipLoadExtensionForVMULL(LD, DAG);
5167 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5168 // have been legalized as a BITCAST from v4i32.
5169 if (N->getOpcode() == ISD::BITCAST) {
5170 SDNode *BVN = N->getOperand(0).getNode();
5171 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5172 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5173 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5174 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5175 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5177 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5178 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5179 EVT VT = N->getValueType(0);
5180 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5181 unsigned NumElts = VT.getVectorNumElements();
5182 MVT TruncVT = MVT::getIntegerVT(EltSize);
5183 SmallVector<SDValue, 8> Ops;
5184 for (unsigned i = 0; i != NumElts; ++i) {
5185 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5186 const APInt &CInt = C->getAPIntValue();
5187 // Element types smaller than 32 bits are not legal, so use i32 elements.
5188 // The values are implicitly truncated so sext vs. zext doesn't matter.
5189 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5191 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5192 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5195 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5196 unsigned Opcode = N->getOpcode();
5197 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5198 SDNode *N0 = N->getOperand(0).getNode();
5199 SDNode *N1 = N->getOperand(1).getNode();
5200 return N0->hasOneUse() && N1->hasOneUse() &&
5201 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5206 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5207 unsigned Opcode = N->getOpcode();
5208 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5209 SDNode *N0 = N->getOperand(0).getNode();
5210 SDNode *N1 = N->getOperand(1).getNode();
5211 return N0->hasOneUse() && N1->hasOneUse() &&
5212 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5217 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5218 // Multiplications are only custom-lowered for 128-bit vectors so that
5219 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5220 EVT VT = Op.getValueType();
5221 assert(VT.is128BitVector() && VT.isInteger() &&
5222 "unexpected type for custom-lowering ISD::MUL");
5223 SDNode *N0 = Op.getOperand(0).getNode();
5224 SDNode *N1 = Op.getOperand(1).getNode();
5225 unsigned NewOpc = 0;
5227 bool isN0SExt = isSignExtended(N0, DAG);
5228 bool isN1SExt = isSignExtended(N1, DAG);
5229 if (isN0SExt && isN1SExt)
5230 NewOpc = ARMISD::VMULLs;
5232 bool isN0ZExt = isZeroExtended(N0, DAG);
5233 bool isN1ZExt = isZeroExtended(N1, DAG);
5234 if (isN0ZExt && isN1ZExt)
5235 NewOpc = ARMISD::VMULLu;
5236 else if (isN1SExt || isN1ZExt) {
5237 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5238 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5239 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5240 NewOpc = ARMISD::VMULLs;
5242 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5243 NewOpc = ARMISD::VMULLu;
5245 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5247 NewOpc = ARMISD::VMULLu;
5253 if (VT == MVT::v2i64)
5254 // Fall through to expand this. It is not legal.
5257 // Other vector multiplications are legal.
5262 // Legalize to a VMULL instruction.
5263 DebugLoc DL = Op.getDebugLoc();
5265 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5267 Op0 = SkipExtensionForVMULL(N0, DAG);
5268 assert(Op0.getValueType().is64BitVector() &&
5269 Op1.getValueType().is64BitVector() &&
5270 "unexpected types for extended operands to VMULL");
5271 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5274 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5275 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5282 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5283 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5284 EVT Op1VT = Op1.getValueType();
5285 return DAG.getNode(N0->getOpcode(), DL, VT,
5286 DAG.getNode(NewOpc, DL, VT,
5287 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5288 DAG.getNode(NewOpc, DL, VT,
5289 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5293 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5295 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5296 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5297 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5298 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5299 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5300 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5301 // Get reciprocal estimate.
5302 // float4 recip = vrecpeq_f32(yf);
5303 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5304 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5305 // Because char has a smaller range than uchar, we can actually get away
5306 // without any newton steps. This requires that we use a weird bias
5307 // of 0xb000, however (again, this has been exhaustively tested).
5308 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5309 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5310 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5311 Y = DAG.getConstant(0xb000, MVT::i32);
5312 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5313 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5314 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5315 // Convert back to short.
5316 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5317 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5322 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5324 // Convert to float.
5325 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5326 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5327 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5328 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5329 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5330 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5332 // Use reciprocal estimate and one refinement step.
5333 // float4 recip = vrecpeq_f32(yf);
5334 // recip *= vrecpsq_f32(yf, recip);
5335 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5336 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5337 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5338 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5340 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5341 // Because short has a smaller range than ushort, we can actually get away
5342 // with only a single newton step. This requires that we use a weird bias
5343 // of 89, however (again, this has been exhaustively tested).
5344 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5345 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5346 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5347 N1 = DAG.getConstant(0x89, MVT::i32);
5348 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5349 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5350 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5351 // Convert back to integer and return.
5352 // return vmovn_s32(vcvt_s32_f32(result));
5353 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5354 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5358 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5359 EVT VT = Op.getValueType();
5360 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5361 "unexpected type for custom-lowering ISD::SDIV");
5363 DebugLoc dl = Op.getDebugLoc();
5364 SDValue N0 = Op.getOperand(0);
5365 SDValue N1 = Op.getOperand(1);
5368 if (VT == MVT::v8i8) {
5369 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5370 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5372 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5373 DAG.getIntPtrConstant(4));
5374 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5375 DAG.getIntPtrConstant(4));
5376 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5377 DAG.getIntPtrConstant(0));
5378 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5379 DAG.getIntPtrConstant(0));
5381 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5382 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5384 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5385 N0 = LowerCONCAT_VECTORS(N0, DAG);
5387 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5390 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5393 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5394 EVT VT = Op.getValueType();
5395 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5396 "unexpected type for custom-lowering ISD::UDIV");
5398 DebugLoc dl = Op.getDebugLoc();
5399 SDValue N0 = Op.getOperand(0);
5400 SDValue N1 = Op.getOperand(1);
5403 if (VT == MVT::v8i8) {
5404 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5405 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5407 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5408 DAG.getIntPtrConstant(4));
5409 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5410 DAG.getIntPtrConstant(4));
5411 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5412 DAG.getIntPtrConstant(0));
5413 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5414 DAG.getIntPtrConstant(0));
5416 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5417 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5419 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5420 N0 = LowerCONCAT_VECTORS(N0, DAG);
5422 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5423 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5428 // v4i16 sdiv ... Convert to float.
5429 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5430 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5431 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5432 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5433 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5434 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5436 // Use reciprocal estimate and two refinement steps.
5437 // float4 recip = vrecpeq_f32(yf);
5438 // recip *= vrecpsq_f32(yf, recip);
5439 // recip *= vrecpsq_f32(yf, recip);
5440 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5441 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5442 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5443 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5445 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5446 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5447 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5449 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5450 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5451 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5452 // and that it will never cause us to return an answer too large).
5453 // float4 result = as_float4(as_int4(xf*recip) + 2);
5454 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5455 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5456 N1 = DAG.getConstant(2, MVT::i32);
5457 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5458 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5459 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5460 // Convert back to integer and return.
5461 // return vmovn_u32(vcvt_s32_f32(result));
5462 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5463 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5467 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5468 EVT VT = Op.getNode()->getValueType(0);
5469 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5472 bool ExtraOp = false;
5473 switch (Op.getOpcode()) {
5474 default: llvm_unreachable("Invalid code");
5475 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5476 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5477 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5478 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5482 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5484 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5485 Op.getOperand(1), Op.getOperand(2));
5488 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5489 // Monotonic load/store is legal for all targets
5490 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5493 // Aquire/Release load/store is not legal for targets without a
5494 // dmb or equivalent available.
5500 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5501 SelectionDAG &DAG, unsigned NewOp) {
5502 DebugLoc dl = Node->getDebugLoc();
5503 assert (Node->getValueType(0) == MVT::i64 &&
5504 "Only know how to expand i64 atomics");
5506 SmallVector<SDValue, 6> Ops;
5507 Ops.push_back(Node->getOperand(0)); // Chain
5508 Ops.push_back(Node->getOperand(1)); // Ptr
5510 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5511 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5512 // High part of Val1
5513 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5514 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5515 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5516 // High part of Val1
5517 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5518 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5519 // High part of Val2
5520 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5521 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5523 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5525 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5526 cast<MemSDNode>(Node)->getMemOperand());
5527 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5528 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5529 Results.push_back(Result.getValue(2));
5532 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5533 switch (Op.getOpcode()) {
5534 default: llvm_unreachable("Don't know how to custom lower this!");
5535 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5536 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5537 case ISD::GlobalAddress:
5538 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5539 LowerGlobalAddressELF(Op, DAG);
5540 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5541 case ISD::SELECT: return LowerSELECT(Op, DAG);
5542 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5543 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5544 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5545 case ISD::VASTART: return LowerVASTART(Op, DAG);
5546 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5547 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5548 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5549 case ISD::SINT_TO_FP:
5550 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5551 case ISD::FP_TO_SINT:
5552 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5553 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5554 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5555 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5556 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5557 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5558 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5559 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5561 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5564 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5565 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5566 case ISD::SRL_PARTS:
5567 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5568 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5569 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5570 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5571 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5572 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5573 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5574 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5575 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5576 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5577 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5578 case ISD::MUL: return LowerMUL(Op, DAG);
5579 case ISD::SDIV: return LowerSDIV(Op, DAG);
5580 case ISD::UDIV: return LowerUDIV(Op, DAG);
5584 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5585 case ISD::ATOMIC_LOAD:
5586 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5590 /// ReplaceNodeResults - Replace the results of node with an illegal result
5591 /// type with new values built out of custom code.
5592 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5593 SmallVectorImpl<SDValue>&Results,
5594 SelectionDAG &DAG) const {
5596 switch (N->getOpcode()) {
5598 llvm_unreachable("Don't know how to custom expand this!");
5600 Res = ExpandBITCAST(N, DAG);
5604 Res = Expand64BitShift(N, DAG, Subtarget);
5606 case ISD::ATOMIC_LOAD_ADD:
5607 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5609 case ISD::ATOMIC_LOAD_AND:
5610 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5612 case ISD::ATOMIC_LOAD_NAND:
5613 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5615 case ISD::ATOMIC_LOAD_OR:
5616 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5618 case ISD::ATOMIC_LOAD_SUB:
5619 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5621 case ISD::ATOMIC_LOAD_XOR:
5622 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5624 case ISD::ATOMIC_SWAP:
5625 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5627 case ISD::ATOMIC_CMP_SWAP:
5628 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5630 case ISD::ATOMIC_LOAD_MIN:
5631 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5633 case ISD::ATOMIC_LOAD_UMIN:
5634 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5636 case ISD::ATOMIC_LOAD_MAX:
5637 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5639 case ISD::ATOMIC_LOAD_UMAX:
5640 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5644 Results.push_back(Res);
5647 //===----------------------------------------------------------------------===//
5648 // ARM Scheduler Hooks
5649 //===----------------------------------------------------------------------===//
5652 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5653 MachineBasicBlock *BB,
5654 unsigned Size) const {
5655 unsigned dest = MI->getOperand(0).getReg();
5656 unsigned ptr = MI->getOperand(1).getReg();
5657 unsigned oldval = MI->getOperand(2).getReg();
5658 unsigned newval = MI->getOperand(3).getReg();
5659 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5660 DebugLoc dl = MI->getDebugLoc();
5661 bool isThumb2 = Subtarget->isThumb2();
5663 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5664 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5665 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5666 (const TargetRegisterClass*)&ARM::GPRRegClass);
5669 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5670 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5671 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5674 unsigned ldrOpc, strOpc;
5676 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5678 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5679 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5682 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5683 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5686 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5687 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5691 MachineFunction *MF = BB->getParent();
5692 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5693 MachineFunction::iterator It = BB;
5694 ++It; // insert the new blocks after the current block
5696 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5697 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5698 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5699 MF->insert(It, loop1MBB);
5700 MF->insert(It, loop2MBB);
5701 MF->insert(It, exitMBB);
5703 // Transfer the remainder of BB and its successor edges to exitMBB.
5704 exitMBB->splice(exitMBB->begin(), BB,
5705 llvm::next(MachineBasicBlock::iterator(MI)),
5707 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5711 // fallthrough --> loop1MBB
5712 BB->addSuccessor(loop1MBB);
5715 // ldrex dest, [ptr]
5719 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5720 if (ldrOpc == ARM::t2LDREX)
5722 AddDefaultPred(MIB);
5723 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5724 .addReg(dest).addReg(oldval));
5725 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5726 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5727 BB->addSuccessor(loop2MBB);
5728 BB->addSuccessor(exitMBB);
5731 // strex scratch, newval, [ptr]
5735 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5736 if (strOpc == ARM::t2STREX)
5738 AddDefaultPred(MIB);
5739 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5740 .addReg(scratch).addImm(0));
5741 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5742 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5743 BB->addSuccessor(loop1MBB);
5744 BB->addSuccessor(exitMBB);
5750 MI->eraseFromParent(); // The instruction is gone now.
5756 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5757 unsigned Size, unsigned BinOpcode) const {
5758 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5759 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5761 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5762 MachineFunction *MF = BB->getParent();
5763 MachineFunction::iterator It = BB;
5766 unsigned dest = MI->getOperand(0).getReg();
5767 unsigned ptr = MI->getOperand(1).getReg();
5768 unsigned incr = MI->getOperand(2).getReg();
5769 DebugLoc dl = MI->getDebugLoc();
5770 bool isThumb2 = Subtarget->isThumb2();
5772 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5774 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5775 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5778 unsigned ldrOpc, strOpc;
5780 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5782 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5783 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5786 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5787 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5790 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5791 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5795 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5796 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5797 MF->insert(It, loopMBB);
5798 MF->insert(It, exitMBB);
5800 // Transfer the remainder of BB and its successor edges to exitMBB.
5801 exitMBB->splice(exitMBB->begin(), BB,
5802 llvm::next(MachineBasicBlock::iterator(MI)),
5804 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5806 const TargetRegisterClass *TRC = isThumb2 ?
5807 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5808 (const TargetRegisterClass*)&ARM::GPRRegClass;
5809 unsigned scratch = MRI.createVirtualRegister(TRC);
5810 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5814 // fallthrough --> loopMBB
5815 BB->addSuccessor(loopMBB);
5819 // <binop> scratch2, dest, incr
5820 // strex scratch, scratch2, ptr
5823 // fallthrough --> exitMBB
5825 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5826 if (ldrOpc == ARM::t2LDREX)
5828 AddDefaultPred(MIB);
5830 // operand order needs to go the other way for NAND
5831 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5832 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5833 addReg(incr).addReg(dest)).addReg(0);
5835 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5836 addReg(dest).addReg(incr)).addReg(0);
5839 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5840 if (strOpc == ARM::t2STREX)
5842 AddDefaultPred(MIB);
5843 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5844 .addReg(scratch).addImm(0));
5845 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5846 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5848 BB->addSuccessor(loopMBB);
5849 BB->addSuccessor(exitMBB);
5855 MI->eraseFromParent(); // The instruction is gone now.
5861 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5862 MachineBasicBlock *BB,
5865 ARMCC::CondCodes Cond) const {
5866 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5868 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5869 MachineFunction *MF = BB->getParent();
5870 MachineFunction::iterator It = BB;
5873 unsigned dest = MI->getOperand(0).getReg();
5874 unsigned ptr = MI->getOperand(1).getReg();
5875 unsigned incr = MI->getOperand(2).getReg();
5876 unsigned oldval = dest;
5877 DebugLoc dl = MI->getDebugLoc();
5878 bool isThumb2 = Subtarget->isThumb2();
5880 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5882 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5883 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5886 unsigned ldrOpc, strOpc, extendOpc;
5888 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5890 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5891 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5892 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5895 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5896 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5897 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5900 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5901 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5906 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5907 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5908 MF->insert(It, loopMBB);
5909 MF->insert(It, exitMBB);
5911 // Transfer the remainder of BB and its successor edges to exitMBB.
5912 exitMBB->splice(exitMBB->begin(), BB,
5913 llvm::next(MachineBasicBlock::iterator(MI)),
5915 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5917 const TargetRegisterClass *TRC = isThumb2 ?
5918 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5919 (const TargetRegisterClass*)&ARM::GPRRegClass;
5920 unsigned scratch = MRI.createVirtualRegister(TRC);
5921 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5925 // fallthrough --> loopMBB
5926 BB->addSuccessor(loopMBB);
5930 // (sign extend dest, if required)
5932 // cmov.cond scratch2, incr, dest
5933 // strex scratch, scratch2, ptr
5936 // fallthrough --> exitMBB
5938 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5939 if (ldrOpc == ARM::t2LDREX)
5941 AddDefaultPred(MIB);
5943 // Sign extend the value, if necessary.
5944 if (signExtend && extendOpc) {
5945 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5946 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5951 // Build compare and cmov instructions.
5952 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5953 .addReg(oldval).addReg(incr));
5954 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5955 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5957 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5958 if (strOpc == ARM::t2STREX)
5960 AddDefaultPred(MIB);
5961 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5962 .addReg(scratch).addImm(0));
5963 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5964 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5966 BB->addSuccessor(loopMBB);
5967 BB->addSuccessor(exitMBB);
5973 MI->eraseFromParent(); // The instruction is gone now.
5979 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5980 unsigned Op1, unsigned Op2,
5981 bool NeedsCarry, bool IsCmpxchg,
5982 bool IsMinMax, ARMCC::CondCodes CC) const {
5983 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5984 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5986 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5987 MachineFunction *MF = BB->getParent();
5988 MachineFunction::iterator It = BB;
5991 unsigned destlo = MI->getOperand(0).getReg();
5992 unsigned desthi = MI->getOperand(1).getReg();
5993 unsigned ptr = MI->getOperand(2).getReg();
5994 unsigned vallo = MI->getOperand(3).getReg();
5995 unsigned valhi = MI->getOperand(4).getReg();
5996 DebugLoc dl = MI->getDebugLoc();
5997 bool isThumb2 = Subtarget->isThumb2();
5999 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6001 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6002 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6003 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6006 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6007 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6008 if (IsCmpxchg || IsMinMax)
6009 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6011 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6012 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6014 MF->insert(It, loopMBB);
6015 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6016 if (IsCmpxchg) MF->insert(It, cont2BB);
6017 MF->insert(It, exitMBB);
6019 // Transfer the remainder of BB and its successor edges to exitMBB.
6020 exitMBB->splice(exitMBB->begin(), BB,
6021 llvm::next(MachineBasicBlock::iterator(MI)),
6023 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6025 const TargetRegisterClass *TRC = isThumb2 ?
6026 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6027 (const TargetRegisterClass*)&ARM::GPRRegClass;
6028 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6032 // fallthrough --> loopMBB
6033 BB->addSuccessor(loopMBB);
6036 // ldrexd r2, r3, ptr
6037 // <binopa> r0, r2, incr
6038 // <binopb> r1, r3, incr
6039 // strexd storesuccess, r0, r1, ptr
6040 // cmp storesuccess, #0
6042 // fallthrough --> exitMBB
6047 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6048 .addReg(destlo, RegState::Define)
6049 .addReg(desthi, RegState::Define)
6052 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6053 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6054 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6055 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6056 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6057 .addReg(GPRPair0, 0, ARM::gsub_0);
6058 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6059 .addReg(GPRPair0, 0, ARM::gsub_1);
6062 unsigned StoreLo, StoreHi;
6065 for (unsigned i = 0; i < 2; i++) {
6066 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6068 .addReg(i == 0 ? destlo : desthi)
6069 .addReg(i == 0 ? vallo : valhi));
6070 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6071 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6072 BB->addSuccessor(exitMBB);
6073 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6074 BB = (i == 0 ? contBB : cont2BB);
6077 // Copy to physregs for strexd
6078 StoreLo = MI->getOperand(5).getReg();
6079 StoreHi = MI->getOperand(6).getReg();
6081 // Perform binary operation
6082 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6083 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6084 .addReg(destlo).addReg(vallo))
6085 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6086 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6087 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6088 .addReg(desthi).addReg(valhi))
6089 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6094 // Copy to physregs for strexd
6099 // Compare and branch to exit block.
6100 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6101 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6102 BB->addSuccessor(exitMBB);
6103 BB->addSuccessor(contBB);
6111 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6112 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6114 // Marshal a pair...
6115 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6116 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6117 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6118 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6119 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6122 .addImm(ARM::gsub_0);
6123 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6126 .addImm(ARM::gsub_1);
6129 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6130 .addReg(StorePair).addReg(ptr));
6133 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6134 .addReg(storesuccess).addImm(0));
6135 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6136 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6138 BB->addSuccessor(loopMBB);
6139 BB->addSuccessor(exitMBB);
6145 MI->eraseFromParent(); // The instruction is gone now.
6150 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6151 /// registers the function context.
6152 void ARMTargetLowering::
6153 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6154 MachineBasicBlock *DispatchBB, int FI) const {
6155 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6156 DebugLoc dl = MI->getDebugLoc();
6157 MachineFunction *MF = MBB->getParent();
6158 MachineRegisterInfo *MRI = &MF->getRegInfo();
6159 MachineConstantPool *MCP = MF->getConstantPool();
6160 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6161 const Function *F = MF->getFunction();
6163 bool isThumb = Subtarget->isThumb();
6164 bool isThumb2 = Subtarget->isThumb2();
6166 unsigned PCLabelId = AFI->createPICLabelUId();
6167 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6168 ARMConstantPoolValue *CPV =
6169 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6170 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6172 const TargetRegisterClass *TRC = isThumb ?
6173 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6174 (const TargetRegisterClass*)&ARM::GPRRegClass;
6176 // Grab constant pool and fixed stack memory operands.
6177 MachineMemOperand *CPMMO =
6178 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6179 MachineMemOperand::MOLoad, 4, 4);
6181 MachineMemOperand *FIMMOSt =
6182 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6183 MachineMemOperand::MOStore, 4, 4);
6185 // Load the address of the dispatch MBB into the jump buffer.
6187 // Incoming value: jbuf
6188 // ldr.n r5, LCPI1_1
6191 // str r5, [$jbuf, #+4] ; &jbuf[1]
6192 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6193 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6194 .addConstantPoolIndex(CPI)
6195 .addMemOperand(CPMMO));
6196 // Set the low bit because of thumb mode.
6197 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6199 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6200 .addReg(NewVReg1, RegState::Kill)
6202 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6203 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6204 .addReg(NewVReg2, RegState::Kill)
6206 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6207 .addReg(NewVReg3, RegState::Kill)
6209 .addImm(36) // &jbuf[1] :: pc
6210 .addMemOperand(FIMMOSt));
6211 } else if (isThumb) {
6212 // Incoming value: jbuf
6213 // ldr.n r1, LCPI1_4
6217 // add r2, $jbuf, #+4 ; &jbuf[1]
6219 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6220 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6221 .addConstantPoolIndex(CPI)
6222 .addMemOperand(CPMMO));
6223 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6224 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6225 .addReg(NewVReg1, RegState::Kill)
6227 // Set the low bit because of thumb mode.
6228 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6229 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6230 .addReg(ARM::CPSR, RegState::Define)
6232 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6233 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6234 .addReg(ARM::CPSR, RegState::Define)
6235 .addReg(NewVReg2, RegState::Kill)
6236 .addReg(NewVReg3, RegState::Kill));
6237 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6238 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6240 .addImm(36)); // &jbuf[1] :: pc
6241 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6242 .addReg(NewVReg4, RegState::Kill)
6243 .addReg(NewVReg5, RegState::Kill)
6245 .addMemOperand(FIMMOSt));
6247 // Incoming value: jbuf
6250 // str r1, [$jbuf, #+4] ; &jbuf[1]
6251 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6252 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6253 .addConstantPoolIndex(CPI)
6255 .addMemOperand(CPMMO));
6256 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6257 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6258 .addReg(NewVReg1, RegState::Kill)
6259 .addImm(PCLabelId));
6260 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6261 .addReg(NewVReg2, RegState::Kill)
6263 .addImm(36) // &jbuf[1] :: pc
6264 .addMemOperand(FIMMOSt));
6268 MachineBasicBlock *ARMTargetLowering::
6269 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6270 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6271 DebugLoc dl = MI->getDebugLoc();
6272 MachineFunction *MF = MBB->getParent();
6273 MachineRegisterInfo *MRI = &MF->getRegInfo();
6274 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6275 MachineFrameInfo *MFI = MF->getFrameInfo();
6276 int FI = MFI->getFunctionContextIndex();
6278 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6279 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6280 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6282 // Get a mapping of the call site numbers to all of the landing pads they're
6284 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6285 unsigned MaxCSNum = 0;
6286 MachineModuleInfo &MMI = MF->getMMI();
6287 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6289 if (!BB->isLandingPad()) continue;
6291 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6293 for (MachineBasicBlock::iterator
6294 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6295 if (!II->isEHLabel()) continue;
6297 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6298 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6300 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6301 for (SmallVectorImpl<unsigned>::iterator
6302 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6303 CSI != CSE; ++CSI) {
6304 CallSiteNumToLPad[*CSI].push_back(BB);
6305 MaxCSNum = std::max(MaxCSNum, *CSI);
6311 // Get an ordered list of the machine basic blocks for the jump table.
6312 std::vector<MachineBasicBlock*> LPadList;
6313 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6314 LPadList.reserve(CallSiteNumToLPad.size());
6315 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6316 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6317 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6318 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6319 LPadList.push_back(*II);
6320 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6324 assert(!LPadList.empty() &&
6325 "No landing pad destinations for the dispatch jump table!");
6327 // Create the jump table and associated information.
6328 MachineJumpTableInfo *JTI =
6329 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6330 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6331 unsigned UId = AFI->createJumpTableUId();
6333 // Create the MBBs for the dispatch code.
6335 // Shove the dispatch's address into the return slot in the function context.
6336 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6337 DispatchBB->setIsLandingPad();
6339 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6340 unsigned trap_opcode;
6341 if (Subtarget->isThumb()) {
6342 trap_opcode = ARM::tTRAP;
6344 if (Subtarget->useNaClTrap())
6345 trap_opcode = ARM::TRAPNaCl;
6347 trap_opcode = ARM::TRAP;
6349 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6350 DispatchBB->addSuccessor(TrapBB);
6352 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6353 DispatchBB->addSuccessor(DispContBB);
6356 MF->insert(MF->end(), DispatchBB);
6357 MF->insert(MF->end(), DispContBB);
6358 MF->insert(MF->end(), TrapBB);
6360 // Insert code into the entry block that creates and registers the function
6362 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6364 MachineMemOperand *FIMMOLd =
6365 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6366 MachineMemOperand::MOLoad |
6367 MachineMemOperand::MOVolatile, 4, 4);
6369 MachineInstrBuilder MIB;
6370 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6372 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6373 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6375 // Add a register mask with no preserved registers. This results in all
6376 // registers being marked as clobbered.
6377 MIB.addRegMask(RI.getNoPreservedMask());
6379 unsigned NumLPads = LPadList.size();
6380 if (Subtarget->isThumb2()) {
6381 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6382 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6385 .addMemOperand(FIMMOLd));
6387 if (NumLPads < 256) {
6388 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6390 .addImm(LPadList.size()));
6392 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6393 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6394 .addImm(NumLPads & 0xFFFF));
6396 unsigned VReg2 = VReg1;
6397 if ((NumLPads & 0xFFFF0000) != 0) {
6398 VReg2 = MRI->createVirtualRegister(TRC);
6399 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6401 .addImm(NumLPads >> 16));
6404 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6409 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6414 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6415 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6416 .addJumpTableIndex(MJTI)
6419 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6422 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6423 .addReg(NewVReg3, RegState::Kill)
6425 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6427 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6428 .addReg(NewVReg4, RegState::Kill)
6430 .addJumpTableIndex(MJTI)
6432 } else if (Subtarget->isThumb()) {
6433 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6434 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6437 .addMemOperand(FIMMOLd));
6439 if (NumLPads < 256) {
6440 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6444 MachineConstantPool *ConstantPool = MF->getConstantPool();
6445 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6446 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6448 // MachineConstantPool wants an explicit alignment.
6449 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6451 Align = getDataLayout()->getTypeAllocSize(C->getType());
6452 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6454 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6455 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6456 .addReg(VReg1, RegState::Define)
6457 .addConstantPoolIndex(Idx));
6458 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6463 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6468 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6469 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6470 .addReg(ARM::CPSR, RegState::Define)
6474 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6475 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6476 .addJumpTableIndex(MJTI)
6479 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6480 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6481 .addReg(ARM::CPSR, RegState::Define)
6482 .addReg(NewVReg2, RegState::Kill)
6485 MachineMemOperand *JTMMOLd =
6486 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6487 MachineMemOperand::MOLoad, 4, 4);
6489 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6490 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6491 .addReg(NewVReg4, RegState::Kill)
6493 .addMemOperand(JTMMOLd));
6495 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6496 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6497 .addReg(ARM::CPSR, RegState::Define)
6498 .addReg(NewVReg5, RegState::Kill)
6501 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6502 .addReg(NewVReg6, RegState::Kill)
6503 .addJumpTableIndex(MJTI)
6506 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6507 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6510 .addMemOperand(FIMMOLd));
6512 if (NumLPads < 256) {
6513 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6516 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6517 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6518 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6519 .addImm(NumLPads & 0xFFFF));
6521 unsigned VReg2 = VReg1;
6522 if ((NumLPads & 0xFFFF0000) != 0) {
6523 VReg2 = MRI->createVirtualRegister(TRC);
6524 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6526 .addImm(NumLPads >> 16));
6529 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6533 MachineConstantPool *ConstantPool = MF->getConstantPool();
6534 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6535 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6537 // MachineConstantPool wants an explicit alignment.
6538 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6540 Align = getDataLayout()->getTypeAllocSize(C->getType());
6541 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6543 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6544 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6545 .addReg(VReg1, RegState::Define)
6546 .addConstantPoolIndex(Idx)
6548 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6550 .addReg(VReg1, RegState::Kill));
6553 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6558 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6560 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6562 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6563 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6564 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6565 .addJumpTableIndex(MJTI)
6568 MachineMemOperand *JTMMOLd =
6569 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6570 MachineMemOperand::MOLoad, 4, 4);
6571 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6573 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6574 .addReg(NewVReg3, RegState::Kill)
6577 .addMemOperand(JTMMOLd));
6579 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6580 .addReg(NewVReg5, RegState::Kill)
6582 .addJumpTableIndex(MJTI)
6586 // Add the jump table entries as successors to the MBB.
6587 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6588 for (std::vector<MachineBasicBlock*>::iterator
6589 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6590 MachineBasicBlock *CurMBB = *I;
6591 if (SeenMBBs.insert(CurMBB))
6592 DispContBB->addSuccessor(CurMBB);
6595 // N.B. the order the invoke BBs are processed in doesn't matter here.
6596 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6597 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6598 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6599 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6600 MachineBasicBlock *BB = *I;
6602 // Remove the landing pad successor from the invoke block and replace it
6603 // with the new dispatch block.
6604 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6606 while (!Successors.empty()) {
6607 MachineBasicBlock *SMBB = Successors.pop_back_val();
6608 if (SMBB->isLandingPad()) {
6609 BB->removeSuccessor(SMBB);
6610 MBBLPads.push_back(SMBB);
6614 BB->addSuccessor(DispatchBB);
6616 // Find the invoke call and mark all of the callee-saved registers as
6617 // 'implicit defined' so that they're spilled. This prevents code from
6618 // moving instructions to before the EH block, where they will never be
6620 for (MachineBasicBlock::reverse_iterator
6621 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6622 if (!II->isCall()) continue;
6624 DenseMap<unsigned, bool> DefRegs;
6625 for (MachineInstr::mop_iterator
6626 OI = II->operands_begin(), OE = II->operands_end();
6628 if (!OI->isReg()) continue;
6629 DefRegs[OI->getReg()] = true;
6632 MachineInstrBuilder MIB(*MF, &*II);
6634 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6635 unsigned Reg = SavedRegs[i];
6636 if (Subtarget->isThumb2() &&
6637 !ARM::tGPRRegClass.contains(Reg) &&
6638 !ARM::hGPRRegClass.contains(Reg))
6640 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6642 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6645 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6652 // Mark all former landing pads as non-landing pads. The dispatch is the only
6654 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6655 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6656 (*I)->setIsLandingPad(false);
6658 // The instruction is gone now.
6659 MI->eraseFromParent();
6665 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6666 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6667 E = MBB->succ_end(); I != E; ++I)
6670 llvm_unreachable("Expecting a BB with two successors!");
6673 MachineBasicBlock *ARMTargetLowering::
6674 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6675 // This pseudo instruction has 3 operands: dst, src, size
6676 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6677 // Otherwise, we will generate unrolled scalar copies.
6678 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6679 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6680 MachineFunction::iterator It = BB;
6683 unsigned dest = MI->getOperand(0).getReg();
6684 unsigned src = MI->getOperand(1).getReg();
6685 unsigned SizeVal = MI->getOperand(2).getImm();
6686 unsigned Align = MI->getOperand(3).getImm();
6687 DebugLoc dl = MI->getDebugLoc();
6689 bool isThumb2 = Subtarget->isThumb2();
6690 MachineFunction *MF = BB->getParent();
6691 MachineRegisterInfo &MRI = MF->getRegInfo();
6692 unsigned ldrOpc, strOpc, UnitSize = 0;
6694 const TargetRegisterClass *TRC = isThumb2 ?
6695 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6696 (const TargetRegisterClass*)&ARM::GPRRegClass;
6697 const TargetRegisterClass *TRC_Vec = 0;
6700 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6701 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6703 } else if (Align & 2) {
6704 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6705 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6708 // Check whether we can use NEON instructions.
6709 if (!MF->getFunction()->getAttributes().
6710 hasAttribute(AttributeSet::FunctionIndex,
6711 Attribute::NoImplicitFloat) &&
6712 Subtarget->hasNEON()) {
6713 if ((Align % 16 == 0) && SizeVal >= 16) {
6714 ldrOpc = ARM::VLD1q32wb_fixed;
6715 strOpc = ARM::VST1q32wb_fixed;
6717 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6719 else if ((Align % 8 == 0) && SizeVal >= 8) {
6720 ldrOpc = ARM::VLD1d32wb_fixed;
6721 strOpc = ARM::VST1d32wb_fixed;
6723 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6726 // Can't use NEON instructions.
6727 if (UnitSize == 0) {
6728 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6729 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6734 unsigned BytesLeft = SizeVal % UnitSize;
6735 unsigned LoopSize = SizeVal - BytesLeft;
6737 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6738 // Use LDR and STR to copy.
6739 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6740 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6741 unsigned srcIn = src;
6742 unsigned destIn = dest;
6743 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6744 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6745 unsigned srcOut = MRI.createVirtualRegister(TRC);
6746 unsigned destOut = MRI.createVirtualRegister(TRC);
6747 if (UnitSize >= 8) {
6748 AddDefaultPred(BuildMI(*BB, MI, dl,
6749 TII->get(ldrOpc), scratch)
6750 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6752 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6753 .addReg(destIn).addImm(0).addReg(scratch));
6754 } else if (isThumb2) {
6755 AddDefaultPred(BuildMI(*BB, MI, dl,
6756 TII->get(ldrOpc), scratch)
6757 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6759 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6760 .addReg(scratch).addReg(destIn)
6763 AddDefaultPred(BuildMI(*BB, MI, dl,
6764 TII->get(ldrOpc), scratch)
6765 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6768 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6769 .addReg(scratch).addReg(destIn)
6770 .addReg(0).addImm(UnitSize));
6776 // Handle the leftover bytes with LDRB and STRB.
6777 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6778 // [destOut] = STRB_POST(scratch, destIn, 1)
6779 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6780 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6781 for (unsigned i = 0; i < BytesLeft; i++) {
6782 unsigned scratch = MRI.createVirtualRegister(TRC);
6783 unsigned srcOut = MRI.createVirtualRegister(TRC);
6784 unsigned destOut = MRI.createVirtualRegister(TRC);
6786 AddDefaultPred(BuildMI(*BB, MI, dl,
6787 TII->get(ldrOpc),scratch)
6788 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6790 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6791 .addReg(scratch).addReg(destIn)
6792 .addReg(0).addImm(1));
6794 AddDefaultPred(BuildMI(*BB, MI, dl,
6795 TII->get(ldrOpc),scratch)
6796 .addReg(srcOut, RegState::Define).addReg(srcIn)
6797 .addReg(0).addImm(1));
6799 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6800 .addReg(scratch).addReg(destIn)
6801 .addReg(0).addImm(1));
6806 MI->eraseFromParent(); // The instruction is gone now.
6810 // Expand the pseudo op to a loop.
6813 // movw varEnd, # --> with thumb2
6815 // ldrcp varEnd, idx --> without thumb2
6816 // fallthrough --> loopMBB
6818 // PHI varPhi, varEnd, varLoop
6819 // PHI srcPhi, src, srcLoop
6820 // PHI destPhi, dst, destLoop
6821 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6822 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6823 // subs varLoop, varPhi, #UnitSize
6825 // fallthrough --> exitMBB
6827 // epilogue to handle left-over bytes
6828 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6829 // [destOut] = STRB_POST(scratch, destLoop, 1)
6830 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6831 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6832 MF->insert(It, loopMBB);
6833 MF->insert(It, exitMBB);
6835 // Transfer the remainder of BB and its successor edges to exitMBB.
6836 exitMBB->splice(exitMBB->begin(), BB,
6837 llvm::next(MachineBasicBlock::iterator(MI)),
6839 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6841 // Load an immediate to varEnd.
6842 unsigned varEnd = MRI.createVirtualRegister(TRC);
6844 unsigned VReg1 = varEnd;
6845 if ((LoopSize & 0xFFFF0000) != 0)
6846 VReg1 = MRI.createVirtualRegister(TRC);
6847 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6848 .addImm(LoopSize & 0xFFFF));
6850 if ((LoopSize & 0xFFFF0000) != 0)
6851 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6853 .addImm(LoopSize >> 16));
6855 MachineConstantPool *ConstantPool = MF->getConstantPool();
6856 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6857 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6859 // MachineConstantPool wants an explicit alignment.
6860 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6862 Align = getDataLayout()->getTypeAllocSize(C->getType());
6863 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6865 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6866 .addReg(varEnd, RegState::Define)
6867 .addConstantPoolIndex(Idx)
6870 BB->addSuccessor(loopMBB);
6872 // Generate the loop body:
6873 // varPhi = PHI(varLoop, varEnd)
6874 // srcPhi = PHI(srcLoop, src)
6875 // destPhi = PHI(destLoop, dst)
6876 MachineBasicBlock *entryBB = BB;
6878 unsigned varLoop = MRI.createVirtualRegister(TRC);
6879 unsigned varPhi = MRI.createVirtualRegister(TRC);
6880 unsigned srcLoop = MRI.createVirtualRegister(TRC);
6881 unsigned srcPhi = MRI.createVirtualRegister(TRC);
6882 unsigned destLoop = MRI.createVirtualRegister(TRC);
6883 unsigned destPhi = MRI.createVirtualRegister(TRC);
6885 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6886 .addReg(varLoop).addMBB(loopMBB)
6887 .addReg(varEnd).addMBB(entryBB);
6888 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6889 .addReg(srcLoop).addMBB(loopMBB)
6890 .addReg(src).addMBB(entryBB);
6891 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6892 .addReg(destLoop).addMBB(loopMBB)
6893 .addReg(dest).addMBB(entryBB);
6895 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6896 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6897 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6898 if (UnitSize >= 8) {
6899 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6900 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6902 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6903 .addReg(destPhi).addImm(0).addReg(scratch));
6904 } else if (isThumb2) {
6905 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6906 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6908 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6909 .addReg(scratch).addReg(destPhi)
6912 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6913 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6916 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6917 .addReg(scratch).addReg(destPhi)
6918 .addReg(0).addImm(UnitSize));
6921 // Decrement loop variable by UnitSize.
6922 MachineInstrBuilder MIB = BuildMI(BB, dl,
6923 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6924 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6925 MIB->getOperand(5).setReg(ARM::CPSR);
6926 MIB->getOperand(5).setIsDef(true);
6928 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6929 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6931 // loopMBB can loop back to loopMBB or fall through to exitMBB.
6932 BB->addSuccessor(loopMBB);
6933 BB->addSuccessor(exitMBB);
6935 // Add epilogue to handle BytesLeft.
6937 MachineInstr *StartOfExit = exitMBB->begin();
6938 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6939 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6941 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6942 // [destOut] = STRB_POST(scratch, destLoop, 1)
6943 unsigned srcIn = srcLoop;
6944 unsigned destIn = destLoop;
6945 for (unsigned i = 0; i < BytesLeft; i++) {
6946 unsigned scratch = MRI.createVirtualRegister(TRC);
6947 unsigned srcOut = MRI.createVirtualRegister(TRC);
6948 unsigned destOut = MRI.createVirtualRegister(TRC);
6950 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6951 TII->get(ldrOpc),scratch)
6952 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6954 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6955 .addReg(scratch).addReg(destIn)
6958 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6959 TII->get(ldrOpc),scratch)
6960 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6962 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6963 .addReg(scratch).addReg(destIn)
6964 .addReg(0).addImm(1));
6970 MI->eraseFromParent(); // The instruction is gone now.
6975 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6976 MachineBasicBlock *BB) const {
6977 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6978 DebugLoc dl = MI->getDebugLoc();
6979 bool isThumb2 = Subtarget->isThumb2();
6980 switch (MI->getOpcode()) {
6983 llvm_unreachable("Unexpected instr type to insert");
6985 // The Thumb2 pre-indexed stores have the same MI operands, they just
6986 // define them differently in the .td files from the isel patterns, so
6987 // they need pseudos.
6988 case ARM::t2STR_preidx:
6989 MI->setDesc(TII->get(ARM::t2STR_PRE));
6991 case ARM::t2STRB_preidx:
6992 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6994 case ARM::t2STRH_preidx:
6995 MI->setDesc(TII->get(ARM::t2STRH_PRE));
6998 case ARM::STRi_preidx:
6999 case ARM::STRBi_preidx: {
7000 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7001 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7002 // Decode the offset.
7003 unsigned Offset = MI->getOperand(4).getImm();
7004 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7005 Offset = ARM_AM::getAM2Offset(Offset);
7009 MachineMemOperand *MMO = *MI->memoperands_begin();
7010 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7011 .addOperand(MI->getOperand(0)) // Rn_wb
7012 .addOperand(MI->getOperand(1)) // Rt
7013 .addOperand(MI->getOperand(2)) // Rn
7014 .addImm(Offset) // offset (skip GPR==zero_reg)
7015 .addOperand(MI->getOperand(5)) // pred
7016 .addOperand(MI->getOperand(6))
7017 .addMemOperand(MMO);
7018 MI->eraseFromParent();
7021 case ARM::STRr_preidx:
7022 case ARM::STRBr_preidx:
7023 case ARM::STRH_preidx: {
7025 switch (MI->getOpcode()) {
7026 default: llvm_unreachable("unexpected opcode!");
7027 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7028 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7029 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7031 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7032 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7033 MIB.addOperand(MI->getOperand(i));
7034 MI->eraseFromParent();
7037 case ARM::ATOMIC_LOAD_ADD_I8:
7038 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7039 case ARM::ATOMIC_LOAD_ADD_I16:
7040 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7041 case ARM::ATOMIC_LOAD_ADD_I32:
7042 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7044 case ARM::ATOMIC_LOAD_AND_I8:
7045 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7046 case ARM::ATOMIC_LOAD_AND_I16:
7047 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7048 case ARM::ATOMIC_LOAD_AND_I32:
7049 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7051 case ARM::ATOMIC_LOAD_OR_I8:
7052 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7053 case ARM::ATOMIC_LOAD_OR_I16:
7054 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7055 case ARM::ATOMIC_LOAD_OR_I32:
7056 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7058 case ARM::ATOMIC_LOAD_XOR_I8:
7059 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7060 case ARM::ATOMIC_LOAD_XOR_I16:
7061 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7062 case ARM::ATOMIC_LOAD_XOR_I32:
7063 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7065 case ARM::ATOMIC_LOAD_NAND_I8:
7066 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7067 case ARM::ATOMIC_LOAD_NAND_I16:
7068 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7069 case ARM::ATOMIC_LOAD_NAND_I32:
7070 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7072 case ARM::ATOMIC_LOAD_SUB_I8:
7073 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7074 case ARM::ATOMIC_LOAD_SUB_I16:
7075 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7076 case ARM::ATOMIC_LOAD_SUB_I32:
7077 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7079 case ARM::ATOMIC_LOAD_MIN_I8:
7080 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7081 case ARM::ATOMIC_LOAD_MIN_I16:
7082 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7083 case ARM::ATOMIC_LOAD_MIN_I32:
7084 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7086 case ARM::ATOMIC_LOAD_MAX_I8:
7087 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7088 case ARM::ATOMIC_LOAD_MAX_I16:
7089 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7090 case ARM::ATOMIC_LOAD_MAX_I32:
7091 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7093 case ARM::ATOMIC_LOAD_UMIN_I8:
7094 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7095 case ARM::ATOMIC_LOAD_UMIN_I16:
7096 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7097 case ARM::ATOMIC_LOAD_UMIN_I32:
7098 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7100 case ARM::ATOMIC_LOAD_UMAX_I8:
7101 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7102 case ARM::ATOMIC_LOAD_UMAX_I16:
7103 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7104 case ARM::ATOMIC_LOAD_UMAX_I32:
7105 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7107 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7108 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7109 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7111 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7112 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7113 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7116 case ARM::ATOMADD6432:
7117 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7118 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7119 /*NeedsCarry*/ true);
7120 case ARM::ATOMSUB6432:
7121 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7122 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7123 /*NeedsCarry*/ true);
7124 case ARM::ATOMOR6432:
7125 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7126 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7127 case ARM::ATOMXOR6432:
7128 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7129 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7130 case ARM::ATOMAND6432:
7131 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7132 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7133 case ARM::ATOMSWAP6432:
7134 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7135 case ARM::ATOMCMPXCHG6432:
7136 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7137 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7138 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7139 case ARM::ATOMMIN6432:
7140 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7141 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7142 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7143 /*IsMinMax*/ true, ARMCC::LT);
7144 case ARM::ATOMMAX6432:
7145 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7146 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7147 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7148 /*IsMinMax*/ true, ARMCC::GE);
7149 case ARM::ATOMUMIN6432:
7150 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7151 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7152 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7153 /*IsMinMax*/ true, ARMCC::LO);
7154 case ARM::ATOMUMAX6432:
7155 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7156 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7157 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7158 /*IsMinMax*/ true, ARMCC::HS);
7160 case ARM::tMOVCCr_pseudo: {
7161 // To "insert" a SELECT_CC instruction, we actually have to insert the
7162 // diamond control-flow pattern. The incoming instruction knows the
7163 // destination vreg to set, the condition code register to branch on, the
7164 // true/false values to select between, and a branch opcode to use.
7165 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7166 MachineFunction::iterator It = BB;
7172 // cmpTY ccX, r1, r2
7174 // fallthrough --> copy0MBB
7175 MachineBasicBlock *thisMBB = BB;
7176 MachineFunction *F = BB->getParent();
7177 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7178 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7179 F->insert(It, copy0MBB);
7180 F->insert(It, sinkMBB);
7182 // Transfer the remainder of BB and its successor edges to sinkMBB.
7183 sinkMBB->splice(sinkMBB->begin(), BB,
7184 llvm::next(MachineBasicBlock::iterator(MI)),
7186 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7188 BB->addSuccessor(copy0MBB);
7189 BB->addSuccessor(sinkMBB);
7191 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7192 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7195 // %FalseValue = ...
7196 // # fallthrough to sinkMBB
7199 // Update machine-CFG edges
7200 BB->addSuccessor(sinkMBB);
7203 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7206 BuildMI(*BB, BB->begin(), dl,
7207 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7208 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7209 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7211 MI->eraseFromParent(); // The pseudo instruction is gone now.
7216 case ARM::BCCZi64: {
7217 // If there is an unconditional branch to the other successor, remove it.
7218 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7220 // Compare both parts that make up the double comparison separately for
7222 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7224 unsigned LHS1 = MI->getOperand(1).getReg();
7225 unsigned LHS2 = MI->getOperand(2).getReg();
7227 AddDefaultPred(BuildMI(BB, dl,
7228 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7229 .addReg(LHS1).addImm(0));
7230 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7231 .addReg(LHS2).addImm(0)
7232 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7234 unsigned RHS1 = MI->getOperand(3).getReg();
7235 unsigned RHS2 = MI->getOperand(4).getReg();
7236 AddDefaultPred(BuildMI(BB, dl,
7237 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7238 .addReg(LHS1).addReg(RHS1));
7239 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7240 .addReg(LHS2).addReg(RHS2)
7241 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7244 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7245 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7246 if (MI->getOperand(0).getImm() == ARMCC::NE)
7247 std::swap(destMBB, exitMBB);
7249 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7250 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7252 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7254 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7256 MI->eraseFromParent(); // The pseudo instruction is gone now.
7260 case ARM::Int_eh_sjlj_setjmp:
7261 case ARM::Int_eh_sjlj_setjmp_nofp:
7262 case ARM::tInt_eh_sjlj_setjmp:
7263 case ARM::t2Int_eh_sjlj_setjmp:
7264 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7265 EmitSjLjDispatchBlock(MI, BB);
7270 // To insert an ABS instruction, we have to insert the
7271 // diamond control-flow pattern. The incoming instruction knows the
7272 // source vreg to test against 0, the destination vreg to set,
7273 // the condition code register to branch on, the
7274 // true/false values to select between, and a branch opcode to use.
7279 // BCC (branch to SinkBB if V0 >= 0)
7280 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7281 // SinkBB: V1 = PHI(V2, V3)
7282 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7283 MachineFunction::iterator BBI = BB;
7285 MachineFunction *Fn = BB->getParent();
7286 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7287 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7288 Fn->insert(BBI, RSBBB);
7289 Fn->insert(BBI, SinkBB);
7291 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7292 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7293 bool isThumb2 = Subtarget->isThumb2();
7294 MachineRegisterInfo &MRI = Fn->getRegInfo();
7295 // In Thumb mode S must not be specified if source register is the SP or
7296 // PC and if destination register is the SP, so restrict register class
7297 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7298 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7299 (const TargetRegisterClass*)&ARM::GPRRegClass);
7301 // Transfer the remainder of BB and its successor edges to sinkMBB.
7302 SinkBB->splice(SinkBB->begin(), BB,
7303 llvm::next(MachineBasicBlock::iterator(MI)),
7305 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7307 BB->addSuccessor(RSBBB);
7308 BB->addSuccessor(SinkBB);
7310 // fall through to SinkMBB
7311 RSBBB->addSuccessor(SinkBB);
7313 // insert a cmp at the end of BB
7314 AddDefaultPred(BuildMI(BB, dl,
7315 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7316 .addReg(ABSSrcReg).addImm(0));
7318 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7320 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7321 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7323 // insert rsbri in RSBBB
7324 // Note: BCC and rsbri will be converted into predicated rsbmi
7325 // by if-conversion pass
7326 BuildMI(*RSBBB, RSBBB->begin(), dl,
7327 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7328 .addReg(ABSSrcReg, RegState::Kill)
7329 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7331 // insert PHI in SinkBB,
7332 // reuse ABSDstReg to not change uses of ABS instruction
7333 BuildMI(*SinkBB, SinkBB->begin(), dl,
7334 TII->get(ARM::PHI), ABSDstReg)
7335 .addReg(NewRsbDstReg).addMBB(RSBBB)
7336 .addReg(ABSSrcReg).addMBB(BB);
7338 // remove ABS instruction
7339 MI->eraseFromParent();
7341 // return last added BB
7344 case ARM::COPY_STRUCT_BYVAL_I32:
7346 return EmitStructByval(MI, BB);
7350 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7351 SDNode *Node) const {
7352 if (!MI->hasPostISelHook()) {
7353 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7354 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7358 const MCInstrDesc *MCID = &MI->getDesc();
7359 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7360 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7361 // operand is still set to noreg. If needed, set the optional operand's
7362 // register to CPSR, and remove the redundant implicit def.
7364 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7366 // Rename pseudo opcodes.
7367 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7369 const ARMBaseInstrInfo *TII =
7370 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7371 MCID = &TII->get(NewOpc);
7373 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7374 "converted opcode should be the same except for cc_out");
7378 // Add the optional cc_out operand
7379 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7381 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7383 // Any ARM instruction that sets the 's' bit should specify an optional
7384 // "cc_out" operand in the last operand position.
7385 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7386 assert(!NewOpc && "Optional cc_out operand required");
7389 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7390 // since we already have an optional CPSR def.
7391 bool definesCPSR = false;
7392 bool deadCPSR = false;
7393 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7395 const MachineOperand &MO = MI->getOperand(i);
7396 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7400 MI->RemoveOperand(i);
7405 assert(!NewOpc && "Optional cc_out operand required");
7408 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7410 assert(!MI->getOperand(ccOutIdx).getReg() &&
7411 "expect uninitialized optional cc_out operand");
7415 // If this instruction was defined with an optional CPSR def and its dag node
7416 // had a live implicit CPSR def, then activate the optional CPSR def.
7417 MachineOperand &MO = MI->getOperand(ccOutIdx);
7418 MO.setReg(ARM::CPSR);
7422 //===----------------------------------------------------------------------===//
7423 // ARM Optimization Hooks
7424 //===----------------------------------------------------------------------===//
7426 // Helper function that checks if N is a null or all ones constant.
7427 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7428 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7431 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7434 // Return true if N is conditionally 0 or all ones.
7435 // Detects these expressions where cc is an i1 value:
7437 // (select cc 0, y) [AllOnes=0]
7438 // (select cc y, 0) [AllOnes=0]
7439 // (zext cc) [AllOnes=0]
7440 // (sext cc) [AllOnes=0/1]
7441 // (select cc -1, y) [AllOnes=1]
7442 // (select cc y, -1) [AllOnes=1]
7444 // Invert is set when N is the null/all ones constant when CC is false.
7445 // OtherOp is set to the alternative value of N.
7446 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7447 SDValue &CC, bool &Invert,
7449 SelectionDAG &DAG) {
7450 switch (N->getOpcode()) {
7451 default: return false;
7453 CC = N->getOperand(0);
7454 SDValue N1 = N->getOperand(1);
7455 SDValue N2 = N->getOperand(2);
7456 if (isZeroOrAllOnes(N1, AllOnes)) {
7461 if (isZeroOrAllOnes(N2, AllOnes)) {
7468 case ISD::ZERO_EXTEND:
7469 // (zext cc) can never be the all ones value.
7473 case ISD::SIGN_EXTEND: {
7474 EVT VT = N->getValueType(0);
7475 CC = N->getOperand(0);
7476 if (CC.getValueType() != MVT::i1)
7480 // When looking for an AllOnes constant, N is an sext, and the 'other'
7482 OtherOp = DAG.getConstant(0, VT);
7483 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7484 // When looking for a 0 constant, N can be zext or sext.
7485 OtherOp = DAG.getConstant(1, VT);
7487 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7493 // Combine a constant select operand into its use:
7495 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7496 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7497 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7498 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7499 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7501 // The transform is rejected if the select doesn't have a constant operand that
7502 // is null, or all ones when AllOnes is set.
7504 // Also recognize sext/zext from i1:
7506 // (add (zext cc), x) -> (select cc (add x, 1), x)
7507 // (add (sext cc), x) -> (select cc (add x, -1), x)
7509 // These transformations eventually create predicated instructions.
7511 // @param N The node to transform.
7512 // @param Slct The N operand that is a select.
7513 // @param OtherOp The other N operand (x above).
7514 // @param DCI Context.
7515 // @param AllOnes Require the select constant to be all ones instead of null.
7516 // @returns The new node, or SDValue() on failure.
7518 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7519 TargetLowering::DAGCombinerInfo &DCI,
7520 bool AllOnes = false) {
7521 SelectionDAG &DAG = DCI.DAG;
7522 EVT VT = N->getValueType(0);
7523 SDValue NonConstantVal;
7526 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7527 NonConstantVal, DAG))
7530 // Slct is now know to be the desired identity constant when CC is true.
7531 SDValue TrueVal = OtherOp;
7532 SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7533 OtherOp, NonConstantVal);
7534 // Unless SwapSelectOps says CC should be false.
7536 std::swap(TrueVal, FalseVal);
7538 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7539 CCOp, TrueVal, FalseVal);
7542 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7544 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7545 TargetLowering::DAGCombinerInfo &DCI) {
7546 SDValue N0 = N->getOperand(0);
7547 SDValue N1 = N->getOperand(1);
7548 if (N0.getNode()->hasOneUse()) {
7549 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7550 if (Result.getNode())
7553 if (N1.getNode()->hasOneUse()) {
7554 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7555 if (Result.getNode())
7561 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7562 // (only after legalization).
7563 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7564 TargetLowering::DAGCombinerInfo &DCI,
7565 const ARMSubtarget *Subtarget) {
7567 // Only perform optimization if after legalize, and if NEON is available. We
7568 // also expected both operands to be BUILD_VECTORs.
7569 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7570 || N0.getOpcode() != ISD::BUILD_VECTOR
7571 || N1.getOpcode() != ISD::BUILD_VECTOR)
7574 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7575 EVT VT = N->getValueType(0);
7576 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7579 // Check that the vector operands are of the right form.
7580 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7581 // operands, where N is the size of the formed vector.
7582 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7583 // index such that we have a pair wise add pattern.
7585 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7586 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7588 SDValue Vec = N0->getOperand(0)->getOperand(0);
7589 SDNode *V = Vec.getNode();
7590 unsigned nextIndex = 0;
7592 // For each operands to the ADD which are BUILD_VECTORs,
7593 // check to see if each of their operands are an EXTRACT_VECTOR with
7594 // the same vector and appropriate index.
7595 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7596 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7597 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7599 SDValue ExtVec0 = N0->getOperand(i);
7600 SDValue ExtVec1 = N1->getOperand(i);
7602 // First operand is the vector, verify its the same.
7603 if (V != ExtVec0->getOperand(0).getNode() ||
7604 V != ExtVec1->getOperand(0).getNode())
7607 // Second is the constant, verify its correct.
7608 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7609 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7611 // For the constant, we want to see all the even or all the odd.
7612 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7613 || C1->getZExtValue() != nextIndex+1)
7622 // Create VPADDL node.
7623 SelectionDAG &DAG = DCI.DAG;
7624 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7626 // Build operand list.
7627 SmallVector<SDValue, 8> Ops;
7628 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7629 TLI.getPointerTy()));
7631 // Input is the vector.
7634 // Get widened type and narrowed type.
7636 unsigned numElem = VT.getVectorNumElements();
7637 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7638 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7639 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7640 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7642 llvm_unreachable("Invalid vector element type for padd optimization.");
7645 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7646 widenType, &Ops[0], Ops.size());
7647 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7650 static SDValue findMUL_LOHI(SDValue V) {
7651 if (V->getOpcode() == ISD::UMUL_LOHI ||
7652 V->getOpcode() == ISD::SMUL_LOHI)
7657 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7658 TargetLowering::DAGCombinerInfo &DCI,
7659 const ARMSubtarget *Subtarget) {
7661 if (Subtarget->isThumb1Only()) return SDValue();
7663 // Only perform the checks after legalize when the pattern is available.
7664 if (DCI.isBeforeLegalize()) return SDValue();
7666 // Look for multiply add opportunities.
7667 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7668 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7669 // a glue link from the first add to the second add.
7670 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7671 // a S/UMLAL instruction.
7674 // \ / \ [no multiline comment]
7680 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7681 SDValue AddcOp0 = AddcNode->getOperand(0);
7682 SDValue AddcOp1 = AddcNode->getOperand(1);
7684 // Check if the two operands are from the same mul_lohi node.
7685 if (AddcOp0.getNode() == AddcOp1.getNode())
7688 assert(AddcNode->getNumValues() == 2 &&
7689 AddcNode->getValueType(0) == MVT::i32 &&
7690 AddcNode->getValueType(1) == MVT::Glue &&
7691 "Expect ADDC with two result values: i32, glue");
7693 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7694 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7695 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7696 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7697 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7700 // Look for the glued ADDE.
7701 SDNode* AddeNode = AddcNode->getGluedUser();
7702 if (AddeNode == NULL)
7705 // Make sure it is really an ADDE.
7706 if (AddeNode->getOpcode() != ISD::ADDE)
7709 assert(AddeNode->getNumOperands() == 3 &&
7710 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7711 "ADDE node has the wrong inputs");
7713 // Check for the triangle shape.
7714 SDValue AddeOp0 = AddeNode->getOperand(0);
7715 SDValue AddeOp1 = AddeNode->getOperand(1);
7717 // Make sure that the ADDE operands are not coming from the same node.
7718 if (AddeOp0.getNode() == AddeOp1.getNode())
7721 // Find the MUL_LOHI node walking up ADDE's operands.
7722 bool IsLeftOperandMUL = false;
7723 SDValue MULOp = findMUL_LOHI(AddeOp0);
7724 if (MULOp == SDValue())
7725 MULOp = findMUL_LOHI(AddeOp1);
7727 IsLeftOperandMUL = true;
7728 if (MULOp == SDValue())
7731 // Figure out the right opcode.
7732 unsigned Opc = MULOp->getOpcode();
7733 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7735 // Figure out the high and low input values to the MLAL node.
7736 SDValue* HiMul = &MULOp;
7737 SDValue* HiAdd = NULL;
7738 SDValue* LoMul = NULL;
7739 SDValue* LowAdd = NULL;
7741 if (IsLeftOperandMUL)
7747 if (AddcOp0->getOpcode() == Opc) {
7751 if (AddcOp1->getOpcode() == Opc) {
7759 if (LoMul->getNode() != HiMul->getNode())
7762 // Create the merged node.
7763 SelectionDAG &DAG = DCI.DAG;
7765 // Build operand list.
7766 SmallVector<SDValue, 8> Ops;
7767 Ops.push_back(LoMul->getOperand(0));
7768 Ops.push_back(LoMul->getOperand(1));
7769 Ops.push_back(*LowAdd);
7770 Ops.push_back(*HiAdd);
7772 SDValue MLALNode = DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7773 DAG.getVTList(MVT::i32, MVT::i32),
7774 &Ops[0], Ops.size());
7776 // Replace the ADDs' nodes uses by the MLA node's values.
7777 SDValue HiMLALResult(MLALNode.getNode(), 1);
7778 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7780 SDValue LoMLALResult(MLALNode.getNode(), 0);
7781 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7783 // Return original node to notify the driver to stop replacing.
7784 SDValue resNode(AddcNode, 0);
7788 /// PerformADDCCombine - Target-specific dag combine transform from
7789 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7790 static SDValue PerformADDCCombine(SDNode *N,
7791 TargetLowering::DAGCombinerInfo &DCI,
7792 const ARMSubtarget *Subtarget) {
7794 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7798 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7799 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7800 /// called with the default operands, and if that fails, with commuted
7802 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7803 TargetLowering::DAGCombinerInfo &DCI,
7804 const ARMSubtarget *Subtarget){
7806 // Attempt to create vpaddl for this add.
7807 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7808 if (Result.getNode())
7811 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7812 if (N0.getNode()->hasOneUse()) {
7813 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7814 if (Result.getNode()) return Result;
7819 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7821 static SDValue PerformADDCombine(SDNode *N,
7822 TargetLowering::DAGCombinerInfo &DCI,
7823 const ARMSubtarget *Subtarget) {
7824 SDValue N0 = N->getOperand(0);
7825 SDValue N1 = N->getOperand(1);
7827 // First try with the default operand order.
7828 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7829 if (Result.getNode())
7832 // If that didn't work, try again with the operands commuted.
7833 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7836 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7838 static SDValue PerformSUBCombine(SDNode *N,
7839 TargetLowering::DAGCombinerInfo &DCI) {
7840 SDValue N0 = N->getOperand(0);
7841 SDValue N1 = N->getOperand(1);
7843 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7844 if (N1.getNode()->hasOneUse()) {
7845 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7846 if (Result.getNode()) return Result;
7852 /// PerformVMULCombine
7853 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7854 /// special multiplier accumulator forwarding.
7860 static SDValue PerformVMULCombine(SDNode *N,
7861 TargetLowering::DAGCombinerInfo &DCI,
7862 const ARMSubtarget *Subtarget) {
7863 if (!Subtarget->hasVMLxForwarding())
7866 SelectionDAG &DAG = DCI.DAG;
7867 SDValue N0 = N->getOperand(0);
7868 SDValue N1 = N->getOperand(1);
7869 unsigned Opcode = N0.getOpcode();
7870 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7871 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7872 Opcode = N1.getOpcode();
7873 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7874 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7879 EVT VT = N->getValueType(0);
7880 DebugLoc DL = N->getDebugLoc();
7881 SDValue N00 = N0->getOperand(0);
7882 SDValue N01 = N0->getOperand(1);
7883 return DAG.getNode(Opcode, DL, VT,
7884 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7885 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7888 static SDValue PerformMULCombine(SDNode *N,
7889 TargetLowering::DAGCombinerInfo &DCI,
7890 const ARMSubtarget *Subtarget) {
7891 SelectionDAG &DAG = DCI.DAG;
7893 if (Subtarget->isThumb1Only())
7896 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7899 EVT VT = N->getValueType(0);
7900 if (VT.is64BitVector() || VT.is128BitVector())
7901 return PerformVMULCombine(N, DCI, Subtarget);
7905 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7909 int64_t MulAmt = C->getSExtValue();
7910 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7912 ShiftAmt = ShiftAmt & (32 - 1);
7913 SDValue V = N->getOperand(0);
7914 DebugLoc DL = N->getDebugLoc();
7917 MulAmt >>= ShiftAmt;
7920 if (isPowerOf2_32(MulAmt - 1)) {
7921 // (mul x, 2^N + 1) => (add (shl x, N), x)
7922 Res = DAG.getNode(ISD::ADD, DL, VT,
7924 DAG.getNode(ISD::SHL, DL, VT,
7926 DAG.getConstant(Log2_32(MulAmt - 1),
7928 } else if (isPowerOf2_32(MulAmt + 1)) {
7929 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7930 Res = DAG.getNode(ISD::SUB, DL, VT,
7931 DAG.getNode(ISD::SHL, DL, VT,
7933 DAG.getConstant(Log2_32(MulAmt + 1),
7939 uint64_t MulAmtAbs = -MulAmt;
7940 if (isPowerOf2_32(MulAmtAbs + 1)) {
7941 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7942 Res = DAG.getNode(ISD::SUB, DL, VT,
7944 DAG.getNode(ISD::SHL, DL, VT,
7946 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7948 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7949 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7950 Res = DAG.getNode(ISD::ADD, DL, VT,
7952 DAG.getNode(ISD::SHL, DL, VT,
7954 DAG.getConstant(Log2_32(MulAmtAbs-1),
7956 Res = DAG.getNode(ISD::SUB, DL, VT,
7957 DAG.getConstant(0, MVT::i32),Res);
7964 Res = DAG.getNode(ISD::SHL, DL, VT,
7965 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7967 // Do not add new nodes to DAG combiner worklist.
7968 DCI.CombineTo(N, Res, false);
7972 static SDValue PerformANDCombine(SDNode *N,
7973 TargetLowering::DAGCombinerInfo &DCI,
7974 const ARMSubtarget *Subtarget) {
7976 // Attempt to use immediate-form VBIC
7977 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7978 DebugLoc dl = N->getDebugLoc();
7979 EVT VT = N->getValueType(0);
7980 SelectionDAG &DAG = DCI.DAG;
7982 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7985 APInt SplatBits, SplatUndef;
7986 unsigned SplatBitSize;
7989 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7990 if (SplatBitSize <= 64) {
7992 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7993 SplatUndef.getZExtValue(), SplatBitSize,
7994 DAG, VbicVT, VT.is128BitVector(),
7996 if (Val.getNode()) {
7998 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7999 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8000 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8005 if (!Subtarget->isThumb1Only()) {
8006 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8007 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8008 if (Result.getNode())
8015 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8016 static SDValue PerformORCombine(SDNode *N,
8017 TargetLowering::DAGCombinerInfo &DCI,
8018 const ARMSubtarget *Subtarget) {
8019 // Attempt to use immediate-form VORR
8020 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8021 DebugLoc dl = N->getDebugLoc();
8022 EVT VT = N->getValueType(0);
8023 SelectionDAG &DAG = DCI.DAG;
8025 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8028 APInt SplatBits, SplatUndef;
8029 unsigned SplatBitSize;
8031 if (BVN && Subtarget->hasNEON() &&
8032 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8033 if (SplatBitSize <= 64) {
8035 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8036 SplatUndef.getZExtValue(), SplatBitSize,
8037 DAG, VorrVT, VT.is128BitVector(),
8039 if (Val.getNode()) {
8041 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8042 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8043 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8048 if (!Subtarget->isThumb1Only()) {
8049 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8050 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8051 if (Result.getNode())
8055 // The code below optimizes (or (and X, Y), Z).
8056 // The AND operand needs to have a single user to make these optimizations
8058 SDValue N0 = N->getOperand(0);
8059 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8061 SDValue N1 = N->getOperand(1);
8063 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8064 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8065 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8067 unsigned SplatBitSize;
8070 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8072 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8073 HasAnyUndefs) && !HasAnyUndefs) {
8074 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8076 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8077 HasAnyUndefs) && !HasAnyUndefs &&
8078 SplatBits0 == ~SplatBits1) {
8079 // Canonicalize the vector type to make instruction selection simpler.
8080 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8081 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8082 N0->getOperand(1), N0->getOperand(0),
8084 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8089 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8092 // BFI is only available on V6T2+
8093 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8096 DebugLoc DL = N->getDebugLoc();
8097 // 1) or (and A, mask), val => ARMbfi A, val, mask
8098 // iff (val & mask) == val
8100 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8101 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8102 // && mask == ~mask2
8103 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8104 // && ~mask == mask2
8105 // (i.e., copy a bitfield value into another bitfield of the same width)
8110 SDValue N00 = N0.getOperand(0);
8112 // The value and the mask need to be constants so we can verify this is
8113 // actually a bitfield set. If the mask is 0xffff, we can do better
8114 // via a movt instruction, so don't use BFI in that case.
8115 SDValue MaskOp = N0.getOperand(1);
8116 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8119 unsigned Mask = MaskC->getZExtValue();
8123 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8124 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8126 unsigned Val = N1C->getZExtValue();
8127 if ((Val & ~Mask) != Val)
8130 if (ARM::isBitFieldInvertedMask(Mask)) {
8131 Val >>= CountTrailingZeros_32(~Mask);
8133 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8134 DAG.getConstant(Val, MVT::i32),
8135 DAG.getConstant(Mask, MVT::i32));
8137 // Do not add new nodes to DAG combiner worklist.
8138 DCI.CombineTo(N, Res, false);
8141 } else if (N1.getOpcode() == ISD::AND) {
8142 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8143 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8146 unsigned Mask2 = N11C->getZExtValue();
8148 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8150 if (ARM::isBitFieldInvertedMask(Mask) &&
8152 // The pack halfword instruction works better for masks that fit it,
8153 // so use that when it's available.
8154 if (Subtarget->hasT2ExtractPack() &&
8155 (Mask == 0xffff || Mask == 0xffff0000))
8158 unsigned amt = CountTrailingZeros_32(Mask2);
8159 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8160 DAG.getConstant(amt, MVT::i32));
8161 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8162 DAG.getConstant(Mask, MVT::i32));
8163 // Do not add new nodes to DAG combiner worklist.
8164 DCI.CombineTo(N, Res, false);
8166 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8168 // The pack halfword instruction works better for masks that fit it,
8169 // so use that when it's available.
8170 if (Subtarget->hasT2ExtractPack() &&
8171 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8174 unsigned lsb = CountTrailingZeros_32(Mask);
8175 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8176 DAG.getConstant(lsb, MVT::i32));
8177 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8178 DAG.getConstant(Mask2, MVT::i32));
8179 // Do not add new nodes to DAG combiner worklist.
8180 DCI.CombineTo(N, Res, false);
8185 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8186 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8187 ARM::isBitFieldInvertedMask(~Mask)) {
8188 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8189 // where lsb(mask) == #shamt and masked bits of B are known zero.
8190 SDValue ShAmt = N00.getOperand(1);
8191 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8192 unsigned LSB = CountTrailingZeros_32(Mask);
8196 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8197 DAG.getConstant(~Mask, MVT::i32));
8199 // Do not add new nodes to DAG combiner worklist.
8200 DCI.CombineTo(N, Res, false);
8206 static SDValue PerformXORCombine(SDNode *N,
8207 TargetLowering::DAGCombinerInfo &DCI,
8208 const ARMSubtarget *Subtarget) {
8209 EVT VT = N->getValueType(0);
8210 SelectionDAG &DAG = DCI.DAG;
8212 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8215 if (!Subtarget->isThumb1Only()) {
8216 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8217 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8218 if (Result.getNode())
8225 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8226 /// the bits being cleared by the AND are not demanded by the BFI.
8227 static SDValue PerformBFICombine(SDNode *N,
8228 TargetLowering::DAGCombinerInfo &DCI) {
8229 SDValue N1 = N->getOperand(1);
8230 if (N1.getOpcode() == ISD::AND) {
8231 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8234 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8235 unsigned LSB = CountTrailingZeros_32(~InvMask);
8236 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8237 unsigned Mask = (1 << Width)-1;
8238 unsigned Mask2 = N11C->getZExtValue();
8239 if ((Mask & (~Mask2)) == 0)
8240 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8241 N->getOperand(0), N1.getOperand(0),
8247 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8248 /// ARMISD::VMOVRRD.
8249 static SDValue PerformVMOVRRDCombine(SDNode *N,
8250 TargetLowering::DAGCombinerInfo &DCI) {
8251 // vmovrrd(vmovdrr x, y) -> x,y
8252 SDValue InDouble = N->getOperand(0);
8253 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8254 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8256 // vmovrrd(load f64) -> (load i32), (load i32)
8257 SDNode *InNode = InDouble.getNode();
8258 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8259 InNode->getValueType(0) == MVT::f64 &&
8260 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8261 !cast<LoadSDNode>(InNode)->isVolatile()) {
8262 // TODO: Should this be done for non-FrameIndex operands?
8263 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8265 SelectionDAG &DAG = DCI.DAG;
8266 DebugLoc DL = LD->getDebugLoc();
8267 SDValue BasePtr = LD->getBasePtr();
8268 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8269 LD->getPointerInfo(), LD->isVolatile(),
8270 LD->isNonTemporal(), LD->isInvariant(),
8271 LD->getAlignment());
8273 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8274 DAG.getConstant(4, MVT::i32));
8275 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8276 LD->getPointerInfo(), LD->isVolatile(),
8277 LD->isNonTemporal(), LD->isInvariant(),
8278 std::min(4U, LD->getAlignment() / 2));
8280 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8281 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8282 DCI.RemoveFromWorklist(LD);
8290 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8291 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8292 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8293 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8294 SDValue Op0 = N->getOperand(0);
8295 SDValue Op1 = N->getOperand(1);
8296 if (Op0.getOpcode() == ISD::BITCAST)
8297 Op0 = Op0.getOperand(0);
8298 if (Op1.getOpcode() == ISD::BITCAST)
8299 Op1 = Op1.getOperand(0);
8300 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8301 Op0.getNode() == Op1.getNode() &&
8302 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8303 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8304 N->getValueType(0), Op0.getOperand(0));
8308 /// PerformSTORECombine - Target-specific dag combine xforms for
8310 static SDValue PerformSTORECombine(SDNode *N,
8311 TargetLowering::DAGCombinerInfo &DCI) {
8312 StoreSDNode *St = cast<StoreSDNode>(N);
8313 if (St->isVolatile())
8316 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8317 // pack all of the elements in one place. Next, store to memory in fewer
8319 SDValue StVal = St->getValue();
8320 EVT VT = StVal.getValueType();
8321 if (St->isTruncatingStore() && VT.isVector()) {
8322 SelectionDAG &DAG = DCI.DAG;
8323 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8324 EVT StVT = St->getMemoryVT();
8325 unsigned NumElems = VT.getVectorNumElements();
8326 assert(StVT != VT && "Cannot truncate to the same type");
8327 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8328 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8330 // From, To sizes and ElemCount must be pow of two
8331 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8333 // We are going to use the original vector elt for storing.
8334 // Accumulated smaller vector elements must be a multiple of the store size.
8335 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8337 unsigned SizeRatio = FromEltSz / ToEltSz;
8338 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8340 // Create a type on which we perform the shuffle.
8341 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8342 NumElems*SizeRatio);
8343 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8345 DebugLoc DL = St->getDebugLoc();
8346 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8347 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8348 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8350 // Can't shuffle using an illegal type.
8351 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8353 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8354 DAG.getUNDEF(WideVec.getValueType()),
8356 // At this point all of the data is stored at the bottom of the
8357 // register. We now need to save it to mem.
8359 // Find the largest store unit
8360 MVT StoreType = MVT::i8;
8361 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8362 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8363 MVT Tp = (MVT::SimpleValueType)tp;
8364 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8367 // Didn't find a legal store type.
8368 if (!TLI.isTypeLegal(StoreType))
8371 // Bitcast the original vector into a vector of store-size units
8372 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8373 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8374 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8375 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8376 SmallVector<SDValue, 8> Chains;
8377 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8378 TLI.getPointerTy());
8379 SDValue BasePtr = St->getBasePtr();
8381 // Perform one or more big stores into memory.
8382 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8383 for (unsigned I = 0; I < E; I++) {
8384 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8385 StoreType, ShuffWide,
8386 DAG.getIntPtrConstant(I));
8387 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8388 St->getPointerInfo(), St->isVolatile(),
8389 St->isNonTemporal(), St->getAlignment());
8390 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8392 Chains.push_back(Ch);
8394 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8398 if (!ISD::isNormalStore(St))
8401 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8402 // ARM stores of arguments in the same cache line.
8403 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8404 StVal.getNode()->hasOneUse()) {
8405 SelectionDAG &DAG = DCI.DAG;
8406 DebugLoc DL = St->getDebugLoc();
8407 SDValue BasePtr = St->getBasePtr();
8408 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8409 StVal.getNode()->getOperand(0), BasePtr,
8410 St->getPointerInfo(), St->isVolatile(),
8411 St->isNonTemporal(), St->getAlignment());
8413 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8414 DAG.getConstant(4, MVT::i32));
8415 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8416 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8417 St->isNonTemporal(),
8418 std::min(4U, St->getAlignment() / 2));
8421 if (StVal.getValueType() != MVT::i64 ||
8422 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8425 // Bitcast an i64 store extracted from a vector to f64.
8426 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8427 SelectionDAG &DAG = DCI.DAG;
8428 DebugLoc dl = StVal.getDebugLoc();
8429 SDValue IntVec = StVal.getOperand(0);
8430 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8431 IntVec.getValueType().getVectorNumElements());
8432 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8433 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8434 Vec, StVal.getOperand(1));
8435 dl = N->getDebugLoc();
8436 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8437 // Make the DAGCombiner fold the bitcasts.
8438 DCI.AddToWorklist(Vec.getNode());
8439 DCI.AddToWorklist(ExtElt.getNode());
8440 DCI.AddToWorklist(V.getNode());
8441 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8442 St->getPointerInfo(), St->isVolatile(),
8443 St->isNonTemporal(), St->getAlignment(),
8447 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8448 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8449 /// i64 vector to have f64 elements, since the value can then be loaded
8450 /// directly into a VFP register.
8451 static bool hasNormalLoadOperand(SDNode *N) {
8452 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8453 for (unsigned i = 0; i < NumElts; ++i) {
8454 SDNode *Elt = N->getOperand(i).getNode();
8455 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8461 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8462 /// ISD::BUILD_VECTOR.
8463 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8464 TargetLowering::DAGCombinerInfo &DCI){
8465 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8466 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8467 // into a pair of GPRs, which is fine when the value is used as a scalar,
8468 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8469 SelectionDAG &DAG = DCI.DAG;
8470 if (N->getNumOperands() == 2) {
8471 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8476 // Load i64 elements as f64 values so that type legalization does not split
8477 // them up into i32 values.
8478 EVT VT = N->getValueType(0);
8479 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8481 DebugLoc dl = N->getDebugLoc();
8482 SmallVector<SDValue, 8> Ops;
8483 unsigned NumElts = VT.getVectorNumElements();
8484 for (unsigned i = 0; i < NumElts; ++i) {
8485 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8487 // Make the DAGCombiner fold the bitcast.
8488 DCI.AddToWorklist(V.getNode());
8490 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8491 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8492 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8495 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8496 /// ISD::INSERT_VECTOR_ELT.
8497 static SDValue PerformInsertEltCombine(SDNode *N,
8498 TargetLowering::DAGCombinerInfo &DCI) {
8499 // Bitcast an i64 load inserted into a vector to f64.
8500 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8501 EVT VT = N->getValueType(0);
8502 SDNode *Elt = N->getOperand(1).getNode();
8503 if (VT.getVectorElementType() != MVT::i64 ||
8504 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8507 SelectionDAG &DAG = DCI.DAG;
8508 DebugLoc dl = N->getDebugLoc();
8509 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8510 VT.getVectorNumElements());
8511 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8512 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8513 // Make the DAGCombiner fold the bitcasts.
8514 DCI.AddToWorklist(Vec.getNode());
8515 DCI.AddToWorklist(V.getNode());
8516 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8517 Vec, V, N->getOperand(2));
8518 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8521 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8522 /// ISD::VECTOR_SHUFFLE.
8523 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8524 // The LLVM shufflevector instruction does not require the shuffle mask
8525 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8526 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8527 // operands do not match the mask length, they are extended by concatenating
8528 // them with undef vectors. That is probably the right thing for other
8529 // targets, but for NEON it is better to concatenate two double-register
8530 // size vector operands into a single quad-register size vector. Do that
8531 // transformation here:
8532 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8533 // shuffle(concat(v1, v2), undef)
8534 SDValue Op0 = N->getOperand(0);
8535 SDValue Op1 = N->getOperand(1);
8536 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8537 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8538 Op0.getNumOperands() != 2 ||
8539 Op1.getNumOperands() != 2)
8541 SDValue Concat0Op1 = Op0.getOperand(1);
8542 SDValue Concat1Op1 = Op1.getOperand(1);
8543 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8544 Concat1Op1.getOpcode() != ISD::UNDEF)
8546 // Skip the transformation if any of the types are illegal.
8547 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8548 EVT VT = N->getValueType(0);
8549 if (!TLI.isTypeLegal(VT) ||
8550 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8551 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8554 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8555 Op0.getOperand(0), Op1.getOperand(0));
8556 // Translate the shuffle mask.
8557 SmallVector<int, 16> NewMask;
8558 unsigned NumElts = VT.getVectorNumElements();
8559 unsigned HalfElts = NumElts/2;
8560 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8561 for (unsigned n = 0; n < NumElts; ++n) {
8562 int MaskElt = SVN->getMaskElt(n);
8564 if (MaskElt < (int)HalfElts)
8566 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8567 NewElt = HalfElts + MaskElt - NumElts;
8568 NewMask.push_back(NewElt);
8570 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8571 DAG.getUNDEF(VT), NewMask.data());
8574 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8575 /// NEON load/store intrinsics to merge base address updates.
8576 static SDValue CombineBaseUpdate(SDNode *N,
8577 TargetLowering::DAGCombinerInfo &DCI) {
8578 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8581 SelectionDAG &DAG = DCI.DAG;
8582 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8583 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8584 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8585 SDValue Addr = N->getOperand(AddrOpIdx);
8587 // Search for a use of the address operand that is an increment.
8588 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8589 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8591 if (User->getOpcode() != ISD::ADD ||
8592 UI.getUse().getResNo() != Addr.getResNo())
8595 // Check that the add is independent of the load/store. Otherwise, folding
8596 // it would create a cycle.
8597 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8600 // Find the new opcode for the updating load/store.
8602 bool isLaneOp = false;
8603 unsigned NewOpc = 0;
8604 unsigned NumVecs = 0;
8606 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8608 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8609 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8611 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8613 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8615 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8617 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8618 NumVecs = 2; isLaneOp = true; break;
8619 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8620 NumVecs = 3; isLaneOp = true; break;
8621 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8622 NumVecs = 4; isLaneOp = true; break;
8623 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8624 NumVecs = 1; isLoad = false; break;
8625 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8626 NumVecs = 2; isLoad = false; break;
8627 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8628 NumVecs = 3; isLoad = false; break;
8629 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8630 NumVecs = 4; isLoad = false; break;
8631 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8632 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8633 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8634 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8635 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8636 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8640 switch (N->getOpcode()) {
8641 default: llvm_unreachable("unexpected opcode for Neon base update");
8642 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8643 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8644 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8648 // Find the size of memory referenced by the load/store.
8651 VecTy = N->getValueType(0);
8653 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8654 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8656 NumBytes /= VecTy.getVectorNumElements();
8658 // If the increment is a constant, it must match the memory ref size.
8659 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8660 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8661 uint64_t IncVal = CInc->getZExtValue();
8662 if (IncVal != NumBytes)
8664 } else if (NumBytes >= 3 * 16) {
8665 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8666 // separate instructions that make it harder to use a non-constant update.
8670 // Create the new updating load/store node.
8672 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8674 for (n = 0; n < NumResultVecs; ++n)
8676 Tys[n++] = MVT::i32;
8677 Tys[n] = MVT::Other;
8678 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8679 SmallVector<SDValue, 8> Ops;
8680 Ops.push_back(N->getOperand(0)); // incoming chain
8681 Ops.push_back(N->getOperand(AddrOpIdx));
8683 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8684 Ops.push_back(N->getOperand(i));
8686 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8687 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8688 Ops.data(), Ops.size(),
8689 MemInt->getMemoryVT(),
8690 MemInt->getMemOperand());
8693 std::vector<SDValue> NewResults;
8694 for (unsigned i = 0; i < NumResultVecs; ++i) {
8695 NewResults.push_back(SDValue(UpdN.getNode(), i));
8697 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8698 DCI.CombineTo(N, NewResults);
8699 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8706 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8707 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8708 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8710 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8711 SelectionDAG &DAG = DCI.DAG;
8712 EVT VT = N->getValueType(0);
8713 // vldN-dup instructions only support 64-bit vectors for N > 1.
8714 if (!VT.is64BitVector())
8717 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8718 SDNode *VLD = N->getOperand(0).getNode();
8719 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8721 unsigned NumVecs = 0;
8722 unsigned NewOpc = 0;
8723 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8724 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8726 NewOpc = ARMISD::VLD2DUP;
8727 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8729 NewOpc = ARMISD::VLD3DUP;
8730 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8732 NewOpc = ARMISD::VLD4DUP;
8737 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8738 // numbers match the load.
8739 unsigned VLDLaneNo =
8740 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8741 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8743 // Ignore uses of the chain result.
8744 if (UI.getUse().getResNo() == NumVecs)
8747 if (User->getOpcode() != ARMISD::VDUPLANE ||
8748 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8752 // Create the vldN-dup node.
8755 for (n = 0; n < NumVecs; ++n)
8757 Tys[n] = MVT::Other;
8758 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8759 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8760 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8761 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8762 Ops, 2, VLDMemInt->getMemoryVT(),
8763 VLDMemInt->getMemOperand());
8766 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8768 unsigned ResNo = UI.getUse().getResNo();
8769 // Ignore uses of the chain result.
8770 if (ResNo == NumVecs)
8773 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8776 // Now the vldN-lane intrinsic is dead except for its chain result.
8777 // Update uses of the chain.
8778 std::vector<SDValue> VLDDupResults;
8779 for (unsigned n = 0; n < NumVecs; ++n)
8780 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8781 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8782 DCI.CombineTo(VLD, VLDDupResults);
8787 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8788 /// ARMISD::VDUPLANE.
8789 static SDValue PerformVDUPLANECombine(SDNode *N,
8790 TargetLowering::DAGCombinerInfo &DCI) {
8791 SDValue Op = N->getOperand(0);
8793 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8794 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8795 if (CombineVLDDUP(N, DCI))
8796 return SDValue(N, 0);
8798 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8799 // redundant. Ignore bit_converts for now; element sizes are checked below.
8800 while (Op.getOpcode() == ISD::BITCAST)
8801 Op = Op.getOperand(0);
8802 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8805 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8806 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8807 // The canonical VMOV for a zero vector uses a 32-bit element size.
8808 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8810 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8812 EVT VT = N->getValueType(0);
8813 if (EltSize > VT.getVectorElementType().getSizeInBits())
8816 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8819 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8820 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8821 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8825 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8827 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8832 APFloat APF = C->getValueAPF();
8833 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8834 != APFloat::opOK || !isExact)
8837 c0 = (I == 0) ? cN : c0;
8838 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8845 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8846 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8847 /// when the VMUL has a constant operand that is a power of 2.
8849 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8850 /// vmul.f32 d16, d17, d16
8851 /// vcvt.s32.f32 d16, d16
8853 /// vcvt.s32.f32 d16, d16, #3
8854 static SDValue PerformVCVTCombine(SDNode *N,
8855 TargetLowering::DAGCombinerInfo &DCI,
8856 const ARMSubtarget *Subtarget) {
8857 SelectionDAG &DAG = DCI.DAG;
8858 SDValue Op = N->getOperand(0);
8860 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8861 Op.getOpcode() != ISD::FMUL)
8865 SDValue N0 = Op->getOperand(0);
8866 SDValue ConstVec = Op->getOperand(1);
8867 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8869 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8870 !isConstVecPow2(ConstVec, isSigned, C))
8873 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8874 Intrinsic::arm_neon_vcvtfp2fxu;
8875 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8877 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8878 DAG.getConstant(Log2_64(C), MVT::i32));
8881 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8882 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8883 /// when the VDIV has a constant operand that is a power of 2.
8885 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8886 /// vcvt.f32.s32 d16, d16
8887 /// vdiv.f32 d16, d17, d16
8889 /// vcvt.f32.s32 d16, d16, #3
8890 static SDValue PerformVDIVCombine(SDNode *N,
8891 TargetLowering::DAGCombinerInfo &DCI,
8892 const ARMSubtarget *Subtarget) {
8893 SelectionDAG &DAG = DCI.DAG;
8894 SDValue Op = N->getOperand(0);
8895 unsigned OpOpcode = Op.getNode()->getOpcode();
8897 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8898 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8902 SDValue ConstVec = N->getOperand(1);
8903 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8905 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8906 !isConstVecPow2(ConstVec, isSigned, C))
8909 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8910 Intrinsic::arm_neon_vcvtfxu2fp;
8911 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8913 DAG.getConstant(IntrinsicOpcode, MVT::i32),
8914 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8917 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8918 /// operand of a vector shift operation, where all the elements of the
8919 /// build_vector must have the same constant integer value.
8920 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8921 // Ignore bit_converts.
8922 while (Op.getOpcode() == ISD::BITCAST)
8923 Op = Op.getOperand(0);
8924 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8925 APInt SplatBits, SplatUndef;
8926 unsigned SplatBitSize;
8928 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8929 HasAnyUndefs, ElementBits) ||
8930 SplatBitSize > ElementBits)
8932 Cnt = SplatBits.getSExtValue();
8936 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8937 /// operand of a vector shift left operation. That value must be in the range:
8938 /// 0 <= Value < ElementBits for a left shift; or
8939 /// 0 <= Value <= ElementBits for a long left shift.
8940 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8941 assert(VT.isVector() && "vector shift count is not a vector type");
8942 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8943 if (! getVShiftImm(Op, ElementBits, Cnt))
8945 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8948 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8949 /// operand of a vector shift right operation. For a shift opcode, the value
8950 /// is positive, but for an intrinsic the value count must be negative. The
8951 /// absolute value must be in the range:
8952 /// 1 <= |Value| <= ElementBits for a right shift; or
8953 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8954 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8956 assert(VT.isVector() && "vector shift count is not a vector type");
8957 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8958 if (! getVShiftImm(Op, ElementBits, Cnt))
8962 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8965 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8966 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8967 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8970 // Don't do anything for most intrinsics.
8973 // Vector shifts: check for immediate versions and lower them.
8974 // Note: This is done during DAG combining instead of DAG legalizing because
8975 // the build_vectors for 64-bit vector element shift counts are generally
8976 // not legal, and it is hard to see their values after they get legalized to
8977 // loads from a constant pool.
8978 case Intrinsic::arm_neon_vshifts:
8979 case Intrinsic::arm_neon_vshiftu:
8980 case Intrinsic::arm_neon_vshiftls:
8981 case Intrinsic::arm_neon_vshiftlu:
8982 case Intrinsic::arm_neon_vshiftn:
8983 case Intrinsic::arm_neon_vrshifts:
8984 case Intrinsic::arm_neon_vrshiftu:
8985 case Intrinsic::arm_neon_vrshiftn:
8986 case Intrinsic::arm_neon_vqshifts:
8987 case Intrinsic::arm_neon_vqshiftu:
8988 case Intrinsic::arm_neon_vqshiftsu:
8989 case Intrinsic::arm_neon_vqshiftns:
8990 case Intrinsic::arm_neon_vqshiftnu:
8991 case Intrinsic::arm_neon_vqshiftnsu:
8992 case Intrinsic::arm_neon_vqrshiftns:
8993 case Intrinsic::arm_neon_vqrshiftnu:
8994 case Intrinsic::arm_neon_vqrshiftnsu: {
8995 EVT VT = N->getOperand(1).getValueType();
8997 unsigned VShiftOpc = 0;
9000 case Intrinsic::arm_neon_vshifts:
9001 case Intrinsic::arm_neon_vshiftu:
9002 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9003 VShiftOpc = ARMISD::VSHL;
9006 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9007 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9008 ARMISD::VSHRs : ARMISD::VSHRu);
9013 case Intrinsic::arm_neon_vshiftls:
9014 case Intrinsic::arm_neon_vshiftlu:
9015 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9017 llvm_unreachable("invalid shift count for vshll intrinsic");
9019 case Intrinsic::arm_neon_vrshifts:
9020 case Intrinsic::arm_neon_vrshiftu:
9021 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9025 case Intrinsic::arm_neon_vqshifts:
9026 case Intrinsic::arm_neon_vqshiftu:
9027 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9031 case Intrinsic::arm_neon_vqshiftsu:
9032 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9034 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9036 case Intrinsic::arm_neon_vshiftn:
9037 case Intrinsic::arm_neon_vrshiftn:
9038 case Intrinsic::arm_neon_vqshiftns:
9039 case Intrinsic::arm_neon_vqshiftnu:
9040 case Intrinsic::arm_neon_vqshiftnsu:
9041 case Intrinsic::arm_neon_vqrshiftns:
9042 case Intrinsic::arm_neon_vqrshiftnu:
9043 case Intrinsic::arm_neon_vqrshiftnsu:
9044 // Narrowing shifts require an immediate right shift.
9045 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9047 llvm_unreachable("invalid shift count for narrowing vector shift "
9051 llvm_unreachable("unhandled vector shift");
9055 case Intrinsic::arm_neon_vshifts:
9056 case Intrinsic::arm_neon_vshiftu:
9057 // Opcode already set above.
9059 case Intrinsic::arm_neon_vshiftls:
9060 case Intrinsic::arm_neon_vshiftlu:
9061 if (Cnt == VT.getVectorElementType().getSizeInBits())
9062 VShiftOpc = ARMISD::VSHLLi;
9064 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9065 ARMISD::VSHLLs : ARMISD::VSHLLu);
9067 case Intrinsic::arm_neon_vshiftn:
9068 VShiftOpc = ARMISD::VSHRN; break;
9069 case Intrinsic::arm_neon_vrshifts:
9070 VShiftOpc = ARMISD::VRSHRs; break;
9071 case Intrinsic::arm_neon_vrshiftu:
9072 VShiftOpc = ARMISD::VRSHRu; break;
9073 case Intrinsic::arm_neon_vrshiftn:
9074 VShiftOpc = ARMISD::VRSHRN; break;
9075 case Intrinsic::arm_neon_vqshifts:
9076 VShiftOpc = ARMISD::VQSHLs; break;
9077 case Intrinsic::arm_neon_vqshiftu:
9078 VShiftOpc = ARMISD::VQSHLu; break;
9079 case Intrinsic::arm_neon_vqshiftsu:
9080 VShiftOpc = ARMISD::VQSHLsu; break;
9081 case Intrinsic::arm_neon_vqshiftns:
9082 VShiftOpc = ARMISD::VQSHRNs; break;
9083 case Intrinsic::arm_neon_vqshiftnu:
9084 VShiftOpc = ARMISD::VQSHRNu; break;
9085 case Intrinsic::arm_neon_vqshiftnsu:
9086 VShiftOpc = ARMISD::VQSHRNsu; break;
9087 case Intrinsic::arm_neon_vqrshiftns:
9088 VShiftOpc = ARMISD::VQRSHRNs; break;
9089 case Intrinsic::arm_neon_vqrshiftnu:
9090 VShiftOpc = ARMISD::VQRSHRNu; break;
9091 case Intrinsic::arm_neon_vqrshiftnsu:
9092 VShiftOpc = ARMISD::VQRSHRNsu; break;
9095 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9096 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9099 case Intrinsic::arm_neon_vshiftins: {
9100 EVT VT = N->getOperand(1).getValueType();
9102 unsigned VShiftOpc = 0;
9104 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9105 VShiftOpc = ARMISD::VSLI;
9106 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9107 VShiftOpc = ARMISD::VSRI;
9109 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9112 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9113 N->getOperand(1), N->getOperand(2),
9114 DAG.getConstant(Cnt, MVT::i32));
9117 case Intrinsic::arm_neon_vqrshifts:
9118 case Intrinsic::arm_neon_vqrshiftu:
9119 // No immediate versions of these to check for.
9126 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9127 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9128 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9129 /// vector element shift counts are generally not legal, and it is hard to see
9130 /// their values after they get legalized to loads from a constant pool.
9131 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9132 const ARMSubtarget *ST) {
9133 EVT VT = N->getValueType(0);
9134 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9135 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9136 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9137 SDValue N1 = N->getOperand(1);
9138 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9139 SDValue N0 = N->getOperand(0);
9140 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9141 DAG.MaskedValueIsZero(N0.getOperand(0),
9142 APInt::getHighBitsSet(32, 16)))
9143 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9147 // Nothing to be done for scalar shifts.
9148 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9149 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9152 assert(ST->hasNEON() && "unexpected vector shift");
9155 switch (N->getOpcode()) {
9156 default: llvm_unreachable("unexpected shift opcode");
9159 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9160 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9161 DAG.getConstant(Cnt, MVT::i32));
9166 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9167 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9168 ARMISD::VSHRs : ARMISD::VSHRu);
9169 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9170 DAG.getConstant(Cnt, MVT::i32));
9176 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9177 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9178 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9179 const ARMSubtarget *ST) {
9180 SDValue N0 = N->getOperand(0);
9182 // Check for sign- and zero-extensions of vector extract operations of 8-
9183 // and 16-bit vector elements. NEON supports these directly. They are
9184 // handled during DAG combining because type legalization will promote them
9185 // to 32-bit types and it is messy to recognize the operations after that.
9186 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9187 SDValue Vec = N0.getOperand(0);
9188 SDValue Lane = N0.getOperand(1);
9189 EVT VT = N->getValueType(0);
9190 EVT EltVT = N0.getValueType();
9191 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9193 if (VT == MVT::i32 &&
9194 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9195 TLI.isTypeLegal(Vec.getValueType()) &&
9196 isa<ConstantSDNode>(Lane)) {
9199 switch (N->getOpcode()) {
9200 default: llvm_unreachable("unexpected opcode");
9201 case ISD::SIGN_EXTEND:
9202 Opc = ARMISD::VGETLANEs;
9204 case ISD::ZERO_EXTEND:
9205 case ISD::ANY_EXTEND:
9206 Opc = ARMISD::VGETLANEu;
9209 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9216 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9217 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9218 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9219 const ARMSubtarget *ST) {
9220 // If the target supports NEON, try to use vmax/vmin instructions for f32
9221 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9222 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9223 // a NaN; only do the transformation when it matches that behavior.
9225 // For now only do this when using NEON for FP operations; if using VFP, it
9226 // is not obvious that the benefit outweighs the cost of switching to the
9228 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9229 N->getValueType(0) != MVT::f32)
9232 SDValue CondLHS = N->getOperand(0);
9233 SDValue CondRHS = N->getOperand(1);
9234 SDValue LHS = N->getOperand(2);
9235 SDValue RHS = N->getOperand(3);
9236 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9238 unsigned Opcode = 0;
9240 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9241 IsReversed = false; // x CC y ? x : y
9242 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9243 IsReversed = true ; // x CC y ? y : x
9257 // If LHS is NaN, an ordered comparison will be false and the result will
9258 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9259 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9260 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9261 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9263 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9264 // will return -0, so vmin can only be used for unsafe math or if one of
9265 // the operands is known to be nonzero.
9266 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9267 !DAG.getTarget().Options.UnsafeFPMath &&
9268 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9270 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9279 // If LHS is NaN, an ordered comparison will be false and the result will
9280 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9281 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9282 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9283 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9285 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9286 // will return +0, so vmax can only be used for unsafe math or if one of
9287 // the operands is known to be nonzero.
9288 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9289 !DAG.getTarget().Options.UnsafeFPMath &&
9290 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9292 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9298 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9301 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9303 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9304 SDValue Cmp = N->getOperand(4);
9305 if (Cmp.getOpcode() != ARMISD::CMPZ)
9306 // Only looking at EQ and NE cases.
9309 EVT VT = N->getValueType(0);
9310 DebugLoc dl = N->getDebugLoc();
9311 SDValue LHS = Cmp.getOperand(0);
9312 SDValue RHS = Cmp.getOperand(1);
9313 SDValue FalseVal = N->getOperand(0);
9314 SDValue TrueVal = N->getOperand(1);
9315 SDValue ARMcc = N->getOperand(2);
9316 ARMCC::CondCodes CC =
9317 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9335 /// FIXME: Turn this into a target neutral optimization?
9337 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9338 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9339 N->getOperand(3), Cmp);
9340 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9342 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9343 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9344 N->getOperand(3), NewCmp);
9347 if (Res.getNode()) {
9348 APInt KnownZero, KnownOne;
9349 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9350 // Capture demanded bits information that would be otherwise lost.
9351 if (KnownZero == 0xfffffffe)
9352 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9353 DAG.getValueType(MVT::i1));
9354 else if (KnownZero == 0xffffff00)
9355 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9356 DAG.getValueType(MVT::i8));
9357 else if (KnownZero == 0xffff0000)
9358 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9359 DAG.getValueType(MVT::i16));
9365 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9366 DAGCombinerInfo &DCI) const {
9367 switch (N->getOpcode()) {
9369 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9370 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9371 case ISD::SUB: return PerformSUBCombine(N, DCI);
9372 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9373 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9374 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9375 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9376 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9377 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9378 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9379 case ISD::STORE: return PerformSTORECombine(N, DCI);
9380 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9381 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9382 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9383 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9384 case ISD::FP_TO_SINT:
9385 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9386 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9387 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9390 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9391 case ISD::SIGN_EXTEND:
9392 case ISD::ZERO_EXTEND:
9393 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9394 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9395 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9396 case ARMISD::VLD2DUP:
9397 case ARMISD::VLD3DUP:
9398 case ARMISD::VLD4DUP:
9399 return CombineBaseUpdate(N, DCI);
9400 case ISD::INTRINSIC_VOID:
9401 case ISD::INTRINSIC_W_CHAIN:
9402 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9403 case Intrinsic::arm_neon_vld1:
9404 case Intrinsic::arm_neon_vld2:
9405 case Intrinsic::arm_neon_vld3:
9406 case Intrinsic::arm_neon_vld4:
9407 case Intrinsic::arm_neon_vld2lane:
9408 case Intrinsic::arm_neon_vld3lane:
9409 case Intrinsic::arm_neon_vld4lane:
9410 case Intrinsic::arm_neon_vst1:
9411 case Intrinsic::arm_neon_vst2:
9412 case Intrinsic::arm_neon_vst3:
9413 case Intrinsic::arm_neon_vst4:
9414 case Intrinsic::arm_neon_vst2lane:
9415 case Intrinsic::arm_neon_vst3lane:
9416 case Intrinsic::arm_neon_vst4lane:
9417 return CombineBaseUpdate(N, DCI);
9425 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9427 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9430 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9431 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9432 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9434 switch (VT.getSimpleVT().SimpleTy) {
9440 // Unaligned access can use (for example) LRDB, LRDH, LDR
9441 if (AllowsUnaligned) {
9443 *Fast = Subtarget->hasV7Ops();
9450 // For any little-endian targets with neon, we can support unaligned ld/st
9451 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9452 // A big-endian target may also explictly support unaligned accesses
9453 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9463 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9464 unsigned AlignCheck) {
9465 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9466 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9469 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9470 unsigned DstAlign, unsigned SrcAlign,
9471 bool IsMemset, bool ZeroMemset,
9473 MachineFunction &MF) const {
9474 const Function *F = MF.getFunction();
9476 // See if we can use NEON instructions for this...
9477 if ((!IsMemset || ZeroMemset) &&
9478 Subtarget->hasNEON() &&
9479 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9480 Attribute::NoImplicitFloat)) {
9483 (memOpAlign(SrcAlign, DstAlign, 16) ||
9484 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9486 } else if (Size >= 8 &&
9487 (memOpAlign(SrcAlign, DstAlign, 8) ||
9488 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9493 // Lowering to i32/i16 if the size permits.
9499 // Let the target-independent logic figure it out.
9503 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9504 if (Val.getOpcode() != ISD::LOAD)
9507 EVT VT1 = Val.getValueType();
9508 if (!VT1.isSimple() || !VT1.isInteger() ||
9509 !VT2.isSimple() || !VT2.isInteger())
9512 switch (VT1.getSimpleVT().SimpleTy) {
9517 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9524 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9529 switch (VT.getSimpleVT().SimpleTy) {
9530 default: return false;
9545 if ((V & (Scale - 1)) != 0)
9548 return V == (V & ((1LL << 5) - 1));
9551 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9552 const ARMSubtarget *Subtarget) {
9559 switch (VT.getSimpleVT().SimpleTy) {
9560 default: return false;
9565 // + imm12 or - imm8
9567 return V == (V & ((1LL << 8) - 1));
9568 return V == (V & ((1LL << 12) - 1));
9571 // Same as ARM mode. FIXME: NEON?
9572 if (!Subtarget->hasVFP2())
9577 return V == (V & ((1LL << 8) - 1));
9581 /// isLegalAddressImmediate - Return true if the integer value can be used
9582 /// as the offset of the target addressing mode for load / store of the
9584 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9585 const ARMSubtarget *Subtarget) {
9592 if (Subtarget->isThumb1Only())
9593 return isLegalT1AddressImmediate(V, VT);
9594 else if (Subtarget->isThumb2())
9595 return isLegalT2AddressImmediate(V, VT, Subtarget);
9600 switch (VT.getSimpleVT().SimpleTy) {
9601 default: return false;
9606 return V == (V & ((1LL << 12) - 1));
9609 return V == (V & ((1LL << 8) - 1));
9612 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9617 return V == (V & ((1LL << 8) - 1));
9621 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9623 int Scale = AM.Scale;
9627 switch (VT.getSimpleVT().SimpleTy) {
9628 default: return false;
9637 return Scale == 2 || Scale == 4 || Scale == 8;
9640 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9644 // Note, we allow "void" uses (basically, uses that aren't loads or
9645 // stores), because arm allows folding a scale into many arithmetic
9646 // operations. This should be made more precise and revisited later.
9648 // Allow r << imm, but the imm has to be a multiple of two.
9649 if (Scale & 1) return false;
9650 return isPowerOf2_32(Scale);
9654 /// isLegalAddressingMode - Return true if the addressing mode represented
9655 /// by AM is legal for this target, for a load/store of the specified type.
9656 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9658 EVT VT = getValueType(Ty, true);
9659 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9662 // Can never fold addr of global into load/store.
9667 case 0: // no scale reg, must be "r+i" or "r", or "i".
9670 if (Subtarget->isThumb1Only())
9674 // ARM doesn't support any R+R*scale+imm addr modes.
9681 if (Subtarget->isThumb2())
9682 return isLegalT2ScaledAddressingMode(AM, VT);
9684 int Scale = AM.Scale;
9685 switch (VT.getSimpleVT().SimpleTy) {
9686 default: return false;
9690 if (Scale < 0) Scale = -Scale;
9694 return isPowerOf2_32(Scale & ~1);
9698 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9703 // Note, we allow "void" uses (basically, uses that aren't loads or
9704 // stores), because arm allows folding a scale into many arithmetic
9705 // operations. This should be made more precise and revisited later.
9707 // Allow r << imm, but the imm has to be a multiple of two.
9708 if (Scale & 1) return false;
9709 return isPowerOf2_32(Scale);
9715 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9716 /// icmp immediate, that is the target has icmp instructions which can compare
9717 /// a register against the immediate without having to materialize the
9718 /// immediate into a register.
9719 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9720 // Thumb2 and ARM modes can use cmn for negative immediates.
9721 if (!Subtarget->isThumb())
9722 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9723 if (Subtarget->isThumb2())
9724 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9725 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9726 return Imm >= 0 && Imm <= 255;
9729 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9730 /// *or sub* immediate, that is the target has add or sub instructions which can
9731 /// add a register with the immediate without having to materialize the
9732 /// immediate into a register.
9733 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9734 // Same encoding for add/sub, just flip the sign.
9735 int64_t AbsImm = llvm::abs64(Imm);
9736 if (!Subtarget->isThumb())
9737 return ARM_AM::getSOImmVal(AbsImm) != -1;
9738 if (Subtarget->isThumb2())
9739 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9740 // Thumb1 only has 8-bit unsigned immediate.
9741 return AbsImm >= 0 && AbsImm <= 255;
9744 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9745 bool isSEXTLoad, SDValue &Base,
9746 SDValue &Offset, bool &isInc,
9747 SelectionDAG &DAG) {
9748 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9751 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9753 Base = Ptr->getOperand(0);
9754 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9755 int RHSC = (int)RHS->getZExtValue();
9756 if (RHSC < 0 && RHSC > -256) {
9757 assert(Ptr->getOpcode() == ISD::ADD);
9759 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9763 isInc = (Ptr->getOpcode() == ISD::ADD);
9764 Offset = Ptr->getOperand(1);
9766 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9768 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9769 int RHSC = (int)RHS->getZExtValue();
9770 if (RHSC < 0 && RHSC > -0x1000) {
9771 assert(Ptr->getOpcode() == ISD::ADD);
9773 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9774 Base = Ptr->getOperand(0);
9779 if (Ptr->getOpcode() == ISD::ADD) {
9781 ARM_AM::ShiftOpc ShOpcVal=
9782 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9783 if (ShOpcVal != ARM_AM::no_shift) {
9784 Base = Ptr->getOperand(1);
9785 Offset = Ptr->getOperand(0);
9787 Base = Ptr->getOperand(0);
9788 Offset = Ptr->getOperand(1);
9793 isInc = (Ptr->getOpcode() == ISD::ADD);
9794 Base = Ptr->getOperand(0);
9795 Offset = Ptr->getOperand(1);
9799 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9803 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9804 bool isSEXTLoad, SDValue &Base,
9805 SDValue &Offset, bool &isInc,
9806 SelectionDAG &DAG) {
9807 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9810 Base = Ptr->getOperand(0);
9811 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9812 int RHSC = (int)RHS->getZExtValue();
9813 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9814 assert(Ptr->getOpcode() == ISD::ADD);
9816 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9818 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9819 isInc = Ptr->getOpcode() == ISD::ADD;
9820 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9828 /// getPreIndexedAddressParts - returns true by value, base pointer and
9829 /// offset pointer and addressing mode by reference if the node's address
9830 /// can be legally represented as pre-indexed load / store address.
9832 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9834 ISD::MemIndexedMode &AM,
9835 SelectionDAG &DAG) const {
9836 if (Subtarget->isThumb1Only())
9841 bool isSEXTLoad = false;
9842 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9843 Ptr = LD->getBasePtr();
9844 VT = LD->getMemoryVT();
9845 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9846 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9847 Ptr = ST->getBasePtr();
9848 VT = ST->getMemoryVT();
9853 bool isLegal = false;
9854 if (Subtarget->isThumb2())
9855 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9856 Offset, isInc, DAG);
9858 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9859 Offset, isInc, DAG);
9863 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9867 /// getPostIndexedAddressParts - returns true by value, base pointer and
9868 /// offset pointer and addressing mode by reference if this node can be
9869 /// combined with a load / store to form a post-indexed load / store.
9870 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9873 ISD::MemIndexedMode &AM,
9874 SelectionDAG &DAG) const {
9875 if (Subtarget->isThumb1Only())
9880 bool isSEXTLoad = false;
9881 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9882 VT = LD->getMemoryVT();
9883 Ptr = LD->getBasePtr();
9884 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9885 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9886 VT = ST->getMemoryVT();
9887 Ptr = ST->getBasePtr();
9892 bool isLegal = false;
9893 if (Subtarget->isThumb2())
9894 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9897 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9903 // Swap base ptr and offset to catch more post-index load / store when
9904 // it's legal. In Thumb2 mode, offset must be an immediate.
9905 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9906 !Subtarget->isThumb2())
9907 std::swap(Base, Offset);
9909 // Post-indexed load / store update the base pointer.
9914 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9918 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9921 const SelectionDAG &DAG,
9922 unsigned Depth) const {
9923 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9924 switch (Op.getOpcode()) {
9926 case ARMISD::CMOV: {
9927 // Bits are known zero/one if known on the LHS and RHS.
9928 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9929 if (KnownZero == 0 && KnownOne == 0) return;
9931 APInt KnownZeroRHS, KnownOneRHS;
9932 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9933 KnownZero &= KnownZeroRHS;
9934 KnownOne &= KnownOneRHS;
9940 //===----------------------------------------------------------------------===//
9941 // ARM Inline Assembly Support
9942 //===----------------------------------------------------------------------===//
9944 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9945 // Looking for "rev" which is V6+.
9946 if (!Subtarget->hasV6Ops())
9949 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9950 std::string AsmStr = IA->getAsmString();
9951 SmallVector<StringRef, 4> AsmPieces;
9952 SplitString(AsmStr, AsmPieces, ";\n");
9954 switch (AsmPieces.size()) {
9955 default: return false;
9957 AsmStr = AsmPieces[0];
9959 SplitString(AsmStr, AsmPieces, " \t,");
9962 if (AsmPieces.size() == 3 &&
9963 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9964 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9965 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9966 if (Ty && Ty->getBitWidth() == 32)
9967 return IntrinsicLowering::LowerToByteSwap(CI);
9975 /// getConstraintType - Given a constraint letter, return the type of
9976 /// constraint it is for this target.
9977 ARMTargetLowering::ConstraintType
9978 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9979 if (Constraint.size() == 1) {
9980 switch (Constraint[0]) {
9982 case 'l': return C_RegisterClass;
9983 case 'w': return C_RegisterClass;
9984 case 'h': return C_RegisterClass;
9985 case 'x': return C_RegisterClass;
9986 case 't': return C_RegisterClass;
9987 case 'j': return C_Other; // Constant for movw.
9988 // An address with a single base register. Due to the way we
9989 // currently handle addresses it is the same as an 'r' memory constraint.
9990 case 'Q': return C_Memory;
9992 } else if (Constraint.size() == 2) {
9993 switch (Constraint[0]) {
9995 // All 'U+' constraints are addresses.
9996 case 'U': return C_Memory;
9999 return TargetLowering::getConstraintType(Constraint);
10002 /// Examine constraint type and operand type and determine a weight value.
10003 /// This object must already have been set up with the operand type
10004 /// and the current alternative constraint selected.
10005 TargetLowering::ConstraintWeight
10006 ARMTargetLowering::getSingleConstraintMatchWeight(
10007 AsmOperandInfo &info, const char *constraint) const {
10008 ConstraintWeight weight = CW_Invalid;
10009 Value *CallOperandVal = info.CallOperandVal;
10010 // If we don't have a value, we can't do a match,
10011 // but allow it at the lowest weight.
10012 if (CallOperandVal == NULL)
10014 Type *type = CallOperandVal->getType();
10015 // Look at the constraint type.
10016 switch (*constraint) {
10018 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10021 if (type->isIntegerTy()) {
10022 if (Subtarget->isThumb())
10023 weight = CW_SpecificReg;
10025 weight = CW_Register;
10029 if (type->isFloatingPointTy())
10030 weight = CW_Register;
10036 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10038 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10040 if (Constraint.size() == 1) {
10041 // GCC ARM Constraint Letters
10042 switch (Constraint[0]) {
10043 case 'l': // Low regs or general regs.
10044 if (Subtarget->isThumb())
10045 return RCPair(0U, &ARM::tGPRRegClass);
10046 return RCPair(0U, &ARM::GPRRegClass);
10047 case 'h': // High regs or no regs.
10048 if (Subtarget->isThumb())
10049 return RCPair(0U, &ARM::hGPRRegClass);
10052 return RCPair(0U, &ARM::GPRRegClass);
10054 if (VT == MVT::f32)
10055 return RCPair(0U, &ARM::SPRRegClass);
10056 if (VT.getSizeInBits() == 64)
10057 return RCPair(0U, &ARM::DPRRegClass);
10058 if (VT.getSizeInBits() == 128)
10059 return RCPair(0U, &ARM::QPRRegClass);
10062 if (VT == MVT::f32)
10063 return RCPair(0U, &ARM::SPR_8RegClass);
10064 if (VT.getSizeInBits() == 64)
10065 return RCPair(0U, &ARM::DPR_8RegClass);
10066 if (VT.getSizeInBits() == 128)
10067 return RCPair(0U, &ARM::QPR_8RegClass);
10070 if (VT == MVT::f32)
10071 return RCPair(0U, &ARM::SPRRegClass);
10075 if (StringRef("{cc}").equals_lower(Constraint))
10076 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10078 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10081 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10082 /// vector. If it is invalid, don't add anything to Ops.
10083 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10084 std::string &Constraint,
10085 std::vector<SDValue>&Ops,
10086 SelectionDAG &DAG) const {
10087 SDValue Result(0, 0);
10089 // Currently only support length 1 constraints.
10090 if (Constraint.length() != 1) return;
10092 char ConstraintLetter = Constraint[0];
10093 switch (ConstraintLetter) {
10096 case 'I': case 'J': case 'K': case 'L':
10097 case 'M': case 'N': case 'O':
10098 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10102 int64_t CVal64 = C->getSExtValue();
10103 int CVal = (int) CVal64;
10104 // None of these constraints allow values larger than 32 bits. Check
10105 // that the value fits in an int.
10106 if (CVal != CVal64)
10109 switch (ConstraintLetter) {
10111 // Constant suitable for movw, must be between 0 and
10113 if (Subtarget->hasV6T2Ops())
10114 if (CVal >= 0 && CVal <= 65535)
10118 if (Subtarget->isThumb1Only()) {
10119 // This must be a constant between 0 and 255, for ADD
10121 if (CVal >= 0 && CVal <= 255)
10123 } else if (Subtarget->isThumb2()) {
10124 // A constant that can be used as an immediate value in a
10125 // data-processing instruction.
10126 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10129 // A constant that can be used as an immediate value in a
10130 // data-processing instruction.
10131 if (ARM_AM::getSOImmVal(CVal) != -1)
10137 if (Subtarget->isThumb()) { // FIXME thumb2
10138 // This must be a constant between -255 and -1, for negated ADD
10139 // immediates. This can be used in GCC with an "n" modifier that
10140 // prints the negated value, for use with SUB instructions. It is
10141 // not useful otherwise but is implemented for compatibility.
10142 if (CVal >= -255 && CVal <= -1)
10145 // This must be a constant between -4095 and 4095. It is not clear
10146 // what this constraint is intended for. Implemented for
10147 // compatibility with GCC.
10148 if (CVal >= -4095 && CVal <= 4095)
10154 if (Subtarget->isThumb1Only()) {
10155 // A 32-bit value where only one byte has a nonzero value. Exclude
10156 // zero to match GCC. This constraint is used by GCC internally for
10157 // constants that can be loaded with a move/shift combination.
10158 // It is not useful otherwise but is implemented for compatibility.
10159 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10161 } else if (Subtarget->isThumb2()) {
10162 // A constant whose bitwise inverse can be used as an immediate
10163 // value in a data-processing instruction. This can be used in GCC
10164 // with a "B" modifier that prints the inverted value, for use with
10165 // BIC and MVN instructions. It is not useful otherwise but is
10166 // implemented for compatibility.
10167 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10170 // A constant whose bitwise inverse can be used as an immediate
10171 // value in a data-processing instruction. This can be used in GCC
10172 // with a "B" modifier that prints the inverted value, for use with
10173 // BIC and MVN instructions. It is not useful otherwise but is
10174 // implemented for compatibility.
10175 if (ARM_AM::getSOImmVal(~CVal) != -1)
10181 if (Subtarget->isThumb1Only()) {
10182 // This must be a constant between -7 and 7,
10183 // for 3-operand ADD/SUB immediate instructions.
10184 if (CVal >= -7 && CVal < 7)
10186 } else if (Subtarget->isThumb2()) {
10187 // A constant whose negation can be used as an immediate value in a
10188 // data-processing instruction. This can be used in GCC with an "n"
10189 // modifier that prints the negated value, for use with SUB
10190 // instructions. It is not useful otherwise but is implemented for
10192 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10195 // A constant whose negation can be used as an immediate value in a
10196 // data-processing instruction. This can be used in GCC with an "n"
10197 // modifier that prints the negated value, for use with SUB
10198 // instructions. It is not useful otherwise but is implemented for
10200 if (ARM_AM::getSOImmVal(-CVal) != -1)
10206 if (Subtarget->isThumb()) { // FIXME thumb2
10207 // This must be a multiple of 4 between 0 and 1020, for
10208 // ADD sp + immediate.
10209 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10212 // A power of two or a constant between 0 and 32. This is used in
10213 // GCC for the shift amount on shifted register operands, but it is
10214 // useful in general for any shift amounts.
10215 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10221 if (Subtarget->isThumb()) { // FIXME thumb2
10222 // This must be a constant between 0 and 31, for shift amounts.
10223 if (CVal >= 0 && CVal <= 31)
10229 if (Subtarget->isThumb()) { // FIXME thumb2
10230 // This must be a multiple of 4 between -508 and 508, for
10231 // ADD/SUB sp = sp + immediate.
10232 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10237 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10241 if (Result.getNode()) {
10242 Ops.push_back(Result);
10245 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10249 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10250 // The ARM target isn't yet aware of offsets.
10254 bool ARM::isBitFieldInvertedMask(unsigned v) {
10255 if (v == 0xffffffff)
10257 // there can be 1's on either or both "outsides", all the "inside"
10258 // bits must be 0's
10259 unsigned int lsb = 0, msb = 31;
10260 while (v & (1 << msb)) --msb;
10261 while (v & (1 << lsb)) ++lsb;
10262 for (unsigned int i = lsb; i <= msb; ++i) {
10269 /// isFPImmLegal - Returns true if the target can instruction select the
10270 /// specified FP immediate natively. If false, the legalizer will
10271 /// materialize the FP immediate as a load from a constant pool.
10272 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10273 if (!Subtarget->hasVFP3())
10275 if (VT == MVT::f32)
10276 return ARM_AM::getFP32Imm(Imm) != -1;
10277 if (VT == MVT::f64)
10278 return ARM_AM::getFP64Imm(Imm) != -1;
10282 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10283 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10284 /// specified in the intrinsic calls.
10285 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10287 unsigned Intrinsic) const {
10288 switch (Intrinsic) {
10289 case Intrinsic::arm_neon_vld1:
10290 case Intrinsic::arm_neon_vld2:
10291 case Intrinsic::arm_neon_vld3:
10292 case Intrinsic::arm_neon_vld4:
10293 case Intrinsic::arm_neon_vld2lane:
10294 case Intrinsic::arm_neon_vld3lane:
10295 case Intrinsic::arm_neon_vld4lane: {
10296 Info.opc = ISD::INTRINSIC_W_CHAIN;
10297 // Conservatively set memVT to the entire set of vectors loaded.
10298 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10299 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10300 Info.ptrVal = I.getArgOperand(0);
10302 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10303 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10304 Info.vol = false; // volatile loads with NEON intrinsics not supported
10305 Info.readMem = true;
10306 Info.writeMem = false;
10309 case Intrinsic::arm_neon_vst1:
10310 case Intrinsic::arm_neon_vst2:
10311 case Intrinsic::arm_neon_vst3:
10312 case Intrinsic::arm_neon_vst4:
10313 case Intrinsic::arm_neon_vst2lane:
10314 case Intrinsic::arm_neon_vst3lane:
10315 case Intrinsic::arm_neon_vst4lane: {
10316 Info.opc = ISD::INTRINSIC_VOID;
10317 // Conservatively set memVT to the entire set of vectors stored.
10318 unsigned NumElts = 0;
10319 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10320 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10321 if (!ArgTy->isVectorTy())
10323 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10325 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10326 Info.ptrVal = I.getArgOperand(0);
10328 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10329 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10330 Info.vol = false; // volatile stores with NEON intrinsics not supported
10331 Info.readMem = false;
10332 Info.writeMem = true;
10335 case Intrinsic::arm_strexd: {
10336 Info.opc = ISD::INTRINSIC_W_CHAIN;
10337 Info.memVT = MVT::i64;
10338 Info.ptrVal = I.getArgOperand(2);
10342 Info.readMem = false;
10343 Info.writeMem = true;
10346 case Intrinsic::arm_ldrexd: {
10347 Info.opc = ISD::INTRINSIC_W_CHAIN;
10348 Info.memVT = MVT::i64;
10349 Info.ptrVal = I.getArgOperand(0);
10353 Info.readMem = true;
10354 Info.writeMem = false;