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 // NEON only has FMA instructions as of VFP4.
558 if (!Subtarget->hasVFP4()) {
559 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
560 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
563 setTargetDAGCombine(ISD::INTRINSIC_VOID);
564 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
565 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
566 setTargetDAGCombine(ISD::SHL);
567 setTargetDAGCombine(ISD::SRL);
568 setTargetDAGCombine(ISD::SRA);
569 setTargetDAGCombine(ISD::SIGN_EXTEND);
570 setTargetDAGCombine(ISD::ZERO_EXTEND);
571 setTargetDAGCombine(ISD::ANY_EXTEND);
572 setTargetDAGCombine(ISD::SELECT_CC);
573 setTargetDAGCombine(ISD::BUILD_VECTOR);
574 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
575 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
576 setTargetDAGCombine(ISD::STORE);
577 setTargetDAGCombine(ISD::FP_TO_SINT);
578 setTargetDAGCombine(ISD::FP_TO_UINT);
579 setTargetDAGCombine(ISD::FDIV);
581 // It is legal to extload from v4i8 to v4i16 or v4i32.
582 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
583 MVT::v4i16, MVT::v2i16,
585 for (unsigned i = 0; i < 6; ++i) {
586 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
587 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
588 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
592 // ARM and Thumb2 support UMLAL/SMLAL.
593 if (!Subtarget->isThumb1Only())
594 setTargetDAGCombine(ISD::ADDC);
597 computeRegisterProperties();
599 // ARM does not have f32 extending load.
600 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
602 // ARM does not have i1 sign extending load.
603 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
605 // ARM supports all 4 flavors of integer indexed load / store.
606 if (!Subtarget->isThumb1Only()) {
607 for (unsigned im = (unsigned)ISD::PRE_INC;
608 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
609 setIndexedLoadAction(im, MVT::i1, Legal);
610 setIndexedLoadAction(im, MVT::i8, Legal);
611 setIndexedLoadAction(im, MVT::i16, Legal);
612 setIndexedLoadAction(im, MVT::i32, Legal);
613 setIndexedStoreAction(im, MVT::i1, Legal);
614 setIndexedStoreAction(im, MVT::i8, Legal);
615 setIndexedStoreAction(im, MVT::i16, Legal);
616 setIndexedStoreAction(im, MVT::i32, Legal);
620 // i64 operation support.
621 setOperationAction(ISD::MUL, MVT::i64, Expand);
622 setOperationAction(ISD::MULHU, MVT::i32, Expand);
623 if (Subtarget->isThumb1Only()) {
624 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
625 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
627 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
628 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
629 setOperationAction(ISD::MULHS, MVT::i32, Expand);
631 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
632 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
633 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
634 setOperationAction(ISD::SRL, MVT::i64, Custom);
635 setOperationAction(ISD::SRA, MVT::i64, Custom);
637 if (!Subtarget->isThumb1Only()) {
638 // FIXME: We should do this for Thumb1 as well.
639 setOperationAction(ISD::ADDC, MVT::i32, Custom);
640 setOperationAction(ISD::ADDE, MVT::i32, Custom);
641 setOperationAction(ISD::SUBC, MVT::i32, Custom);
642 setOperationAction(ISD::SUBE, MVT::i32, Custom);
645 // ARM does not have ROTL.
646 setOperationAction(ISD::ROTL, MVT::i32, Expand);
647 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
648 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
649 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
650 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
652 // These just redirect to CTTZ and CTLZ on ARM.
653 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
654 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
656 // Only ARMv6 has BSWAP.
657 if (!Subtarget->hasV6Ops())
658 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
660 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
661 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
662 // These are expanded into libcalls if the cpu doesn't have HW divider.
663 setOperationAction(ISD::SDIV, MVT::i32, Expand);
664 setOperationAction(ISD::UDIV, MVT::i32, Expand);
666 setOperationAction(ISD::SREM, MVT::i32, Expand);
667 setOperationAction(ISD::UREM, MVT::i32, Expand);
668 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
669 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
671 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
672 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
673 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
674 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
675 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
677 setOperationAction(ISD::TRAP, MVT::Other, Legal);
679 // Use the default implementation.
680 setOperationAction(ISD::VASTART, MVT::Other, Custom);
681 setOperationAction(ISD::VAARG, MVT::Other, Expand);
682 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
683 setOperationAction(ISD::VAEND, MVT::Other, Expand);
684 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
685 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
687 if (!Subtarget->isTargetDarwin()) {
688 // Non-Darwin platforms may return values in these registers via the
689 // personality function.
690 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
691 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
692 setExceptionPointerRegister(ARM::R0);
693 setExceptionSelectorRegister(ARM::R1);
696 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
697 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
698 // the default expansion.
699 // FIXME: This should be checking for v6k, not just v6.
700 if (Subtarget->hasDataBarrier() ||
701 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
702 // membarrier needs custom lowering; the rest are legal and handled
704 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
705 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
706 // Custom lowering for 64-bit ops
707 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
708 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
709 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
710 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
711 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
712 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
713 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
714 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
715 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
716 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
717 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
718 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
719 setInsertFencesForAtomic(true);
721 // Set them all for expansion, which will force libcalls.
722 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
723 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
724 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
725 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
726 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
727 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
728 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
729 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
730 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
731 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
732 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
733 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
734 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
735 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
736 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
737 // Unordered/Monotonic case.
738 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
739 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
740 // Since the libcalls include locking, fold in the fences
741 setShouldFoldAtomicFences(true);
744 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
746 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
747 if (!Subtarget->hasV6Ops()) {
748 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
749 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
751 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
753 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
754 !Subtarget->isThumb1Only()) {
755 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
756 // iff target supports vfp2.
757 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
758 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
761 // We want to custom lower some of our intrinsics.
762 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
763 if (Subtarget->isTargetDarwin()) {
764 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
765 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
766 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
769 setOperationAction(ISD::SETCC, MVT::i32, Expand);
770 setOperationAction(ISD::SETCC, MVT::f32, Expand);
771 setOperationAction(ISD::SETCC, MVT::f64, Expand);
772 setOperationAction(ISD::SELECT, MVT::i32, Custom);
773 setOperationAction(ISD::SELECT, MVT::f32, Custom);
774 setOperationAction(ISD::SELECT, MVT::f64, Custom);
775 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
776 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
777 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
779 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
780 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
781 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
782 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
783 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
785 // We don't support sin/cos/fmod/copysign/pow
786 setOperationAction(ISD::FSIN, MVT::f64, Expand);
787 setOperationAction(ISD::FSIN, MVT::f32, Expand);
788 setOperationAction(ISD::FCOS, MVT::f32, Expand);
789 setOperationAction(ISD::FCOS, MVT::f64, Expand);
790 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
791 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
792 setOperationAction(ISD::FREM, MVT::f64, Expand);
793 setOperationAction(ISD::FREM, MVT::f32, Expand);
794 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
795 !Subtarget->isThumb1Only()) {
796 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
797 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
799 setOperationAction(ISD::FPOW, MVT::f64, Expand);
800 setOperationAction(ISD::FPOW, MVT::f32, Expand);
802 if (!Subtarget->hasVFP4()) {
803 setOperationAction(ISD::FMA, MVT::f64, Expand);
804 setOperationAction(ISD::FMA, MVT::f32, Expand);
807 // Various VFP goodness
808 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
809 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
810 if (Subtarget->hasVFP2()) {
811 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
812 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
813 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
814 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
816 // Special handling for half-precision FP.
817 if (!Subtarget->hasFP16()) {
818 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
819 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
823 // We have target-specific dag combine patterns for the following nodes:
824 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
825 setTargetDAGCombine(ISD::ADD);
826 setTargetDAGCombine(ISD::SUB);
827 setTargetDAGCombine(ISD::MUL);
828 setTargetDAGCombine(ISD::AND);
829 setTargetDAGCombine(ISD::OR);
830 setTargetDAGCombine(ISD::XOR);
832 if (Subtarget->hasV6Ops())
833 setTargetDAGCombine(ISD::SRL);
835 setStackPointerRegisterToSaveRestore(ARM::SP);
837 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
838 !Subtarget->hasVFP2())
839 setSchedulingPreference(Sched::RegPressure);
841 setSchedulingPreference(Sched::Hybrid);
843 //// temporary - rewrite interface to use type
844 MaxStoresPerMemset = 8;
845 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
846 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
847 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
848 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
849 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
851 // On ARM arguments smaller than 4 bytes are extended, so all arguments
852 // are at least 4 bytes aligned.
853 setMinStackArgumentAlignment(4);
855 BenefitFromCodePlacementOpt = true;
857 // Prefer likely predicted branches to selects on out-of-order cores.
858 PredictableSelectIsExpensive = Subtarget->isLikeA9();
860 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
863 // FIXME: It might make sense to define the representative register class as the
864 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
865 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
866 // SPR's representative would be DPR_VFP2. This should work well if register
867 // pressure tracking were modified such that a register use would increment the
868 // pressure of the register class's representative and all of it's super
869 // classes' representatives transitively. We have not implemented this because
870 // of the difficulty prior to coalescing of modeling operand register classes
871 // due to the common occurrence of cross class copies and subregister insertions
873 std::pair<const TargetRegisterClass*, uint8_t>
874 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
875 const TargetRegisterClass *RRC = 0;
877 switch (VT.SimpleTy) {
879 return TargetLowering::findRepresentativeClass(VT);
880 // Use DPR as representative register class for all floating point
881 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
882 // the cost is 1 for both f32 and f64.
883 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
884 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
885 RRC = &ARM::DPRRegClass;
886 // When NEON is used for SP, only half of the register file is available
887 // because operations that define both SP and DP results will be constrained
888 // to the VFP2 class (D0-D15). We currently model this constraint prior to
889 // coalescing by double-counting the SP regs. See the FIXME above.
890 if (Subtarget->useNEONForSinglePrecisionFP())
893 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
894 case MVT::v4f32: case MVT::v2f64:
895 RRC = &ARM::DPRRegClass;
899 RRC = &ARM::DPRRegClass;
903 RRC = &ARM::DPRRegClass;
907 return std::make_pair(RRC, Cost);
910 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
913 case ARMISD::Wrapper: return "ARMISD::Wrapper";
914 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
915 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
916 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
917 case ARMISD::CALL: return "ARMISD::CALL";
918 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
919 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
920 case ARMISD::tCALL: return "ARMISD::tCALL";
921 case ARMISD::BRCOND: return "ARMISD::BRCOND";
922 case ARMISD::BR_JT: return "ARMISD::BR_JT";
923 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
924 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
925 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
926 case ARMISD::CMP: return "ARMISD::CMP";
927 case ARMISD::CMN: return "ARMISD::CMN";
928 case ARMISD::CMPZ: return "ARMISD::CMPZ";
929 case ARMISD::CMPFP: return "ARMISD::CMPFP";
930 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
931 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
932 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
934 case ARMISD::CMOV: return "ARMISD::CMOV";
936 case ARMISD::RBIT: return "ARMISD::RBIT";
938 case ARMISD::FTOSI: return "ARMISD::FTOSI";
939 case ARMISD::FTOUI: return "ARMISD::FTOUI";
940 case ARMISD::SITOF: return "ARMISD::SITOF";
941 case ARMISD::UITOF: return "ARMISD::UITOF";
943 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
944 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
945 case ARMISD::RRX: return "ARMISD::RRX";
947 case ARMISD::ADDC: return "ARMISD::ADDC";
948 case ARMISD::ADDE: return "ARMISD::ADDE";
949 case ARMISD::SUBC: return "ARMISD::SUBC";
950 case ARMISD::SUBE: return "ARMISD::SUBE";
952 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
953 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
955 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
956 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
958 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
960 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
962 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
964 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
965 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
967 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
969 case ARMISD::VCEQ: return "ARMISD::VCEQ";
970 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
971 case ARMISD::VCGE: return "ARMISD::VCGE";
972 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
973 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
974 case ARMISD::VCGEU: return "ARMISD::VCGEU";
975 case ARMISD::VCGT: return "ARMISD::VCGT";
976 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
977 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
978 case ARMISD::VCGTU: return "ARMISD::VCGTU";
979 case ARMISD::VTST: return "ARMISD::VTST";
981 case ARMISD::VSHL: return "ARMISD::VSHL";
982 case ARMISD::VSHRs: return "ARMISD::VSHRs";
983 case ARMISD::VSHRu: return "ARMISD::VSHRu";
984 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
985 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
986 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
987 case ARMISD::VSHRN: return "ARMISD::VSHRN";
988 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
989 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
990 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
991 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
992 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
993 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
994 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
995 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
996 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
997 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
998 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
999 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1000 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1001 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1002 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1003 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1004 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1005 case ARMISD::VDUP: return "ARMISD::VDUP";
1006 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1007 case ARMISD::VEXT: return "ARMISD::VEXT";
1008 case ARMISD::VREV64: return "ARMISD::VREV64";
1009 case ARMISD::VREV32: return "ARMISD::VREV32";
1010 case ARMISD::VREV16: return "ARMISD::VREV16";
1011 case ARMISD::VZIP: return "ARMISD::VZIP";
1012 case ARMISD::VUZP: return "ARMISD::VUZP";
1013 case ARMISD::VTRN: return "ARMISD::VTRN";
1014 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1015 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1016 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1017 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1018 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1019 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1020 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1021 case ARMISD::FMAX: return "ARMISD::FMAX";
1022 case ARMISD::FMIN: return "ARMISD::FMIN";
1023 case ARMISD::BFI: return "ARMISD::BFI";
1024 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1025 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1026 case ARMISD::VBSL: return "ARMISD::VBSL";
1027 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1028 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1029 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1030 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1031 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1032 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1033 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1034 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1035 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1036 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1037 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1038 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1039 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1040 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1041 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1042 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1043 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1044 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1045 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1046 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1050 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1051 if (!VT.isVector()) return getPointerTy();
1052 return VT.changeVectorElementTypeToInteger();
1055 /// getRegClassFor - Return the register class that should be used for the
1056 /// specified value type.
1057 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1058 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1059 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1060 // load / store 4 to 8 consecutive D registers.
1061 if (Subtarget->hasNEON()) {
1062 if (VT == MVT::v4i64)
1063 return &ARM::QQPRRegClass;
1064 if (VT == MVT::v8i64)
1065 return &ARM::QQQQPRRegClass;
1067 return TargetLowering::getRegClassFor(VT);
1070 // Create a fast isel object.
1072 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1073 const TargetLibraryInfo *libInfo) const {
1074 return ARM::createFastISel(funcInfo, libInfo);
1077 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1078 /// be used for loads / stores from the global.
1079 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1080 return (Subtarget->isThumb1Only() ? 127 : 4095);
1083 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1084 unsigned NumVals = N->getNumValues();
1086 return Sched::RegPressure;
1088 for (unsigned i = 0; i != NumVals; ++i) {
1089 EVT VT = N->getValueType(i);
1090 if (VT == MVT::Glue || VT == MVT::Other)
1092 if (VT.isFloatingPoint() || VT.isVector())
1096 if (!N->isMachineOpcode())
1097 return Sched::RegPressure;
1099 // Load are scheduled for latency even if there instruction itinerary
1100 // is not available.
1101 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1102 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1104 if (MCID.getNumDefs() == 0)
1105 return Sched::RegPressure;
1106 if (!Itins->isEmpty() &&
1107 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1110 return Sched::RegPressure;
1113 //===----------------------------------------------------------------------===//
1115 //===----------------------------------------------------------------------===//
1117 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1118 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1120 default: llvm_unreachable("Unknown condition code!");
1121 case ISD::SETNE: return ARMCC::NE;
1122 case ISD::SETEQ: return ARMCC::EQ;
1123 case ISD::SETGT: return ARMCC::GT;
1124 case ISD::SETGE: return ARMCC::GE;
1125 case ISD::SETLT: return ARMCC::LT;
1126 case ISD::SETLE: return ARMCC::LE;
1127 case ISD::SETUGT: return ARMCC::HI;
1128 case ISD::SETUGE: return ARMCC::HS;
1129 case ISD::SETULT: return ARMCC::LO;
1130 case ISD::SETULE: return ARMCC::LS;
1134 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1135 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1136 ARMCC::CondCodes &CondCode2) {
1137 CondCode2 = ARMCC::AL;
1139 default: llvm_unreachable("Unknown FP condition!");
1141 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1143 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1145 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1146 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1147 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1148 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1149 case ISD::SETO: CondCode = ARMCC::VC; break;
1150 case ISD::SETUO: CondCode = ARMCC::VS; break;
1151 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1152 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1153 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1155 case ISD::SETULT: CondCode = ARMCC::LT; break;
1157 case ISD::SETULE: CondCode = ARMCC::LE; break;
1159 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1163 //===----------------------------------------------------------------------===//
1164 // Calling Convention Implementation
1165 //===----------------------------------------------------------------------===//
1167 #include "ARMGenCallingConv.inc"
1169 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1170 /// given CallingConvention value.
1171 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1173 bool isVarArg) const {
1176 llvm_unreachable("Unsupported calling convention");
1177 case CallingConv::Fast:
1178 if (Subtarget->hasVFP2() && !isVarArg) {
1179 if (!Subtarget->isAAPCS_ABI())
1180 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1181 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1182 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1185 case CallingConv::C: {
1186 // Use target triple & subtarget features to do actual dispatch.
1187 if (!Subtarget->isAAPCS_ABI())
1188 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1189 else if (Subtarget->hasVFP2() &&
1190 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1192 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1193 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1195 case CallingConv::ARM_AAPCS_VFP:
1197 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1199 case CallingConv::ARM_AAPCS:
1200 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1201 case CallingConv::ARM_APCS:
1202 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1203 case CallingConv::GHC:
1204 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1208 /// LowerCallResult - Lower the result values of a call into the
1209 /// appropriate copies out of appropriate physical registers.
1211 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1212 CallingConv::ID CallConv, bool isVarArg,
1213 const SmallVectorImpl<ISD::InputArg> &Ins,
1214 DebugLoc dl, SelectionDAG &DAG,
1215 SmallVectorImpl<SDValue> &InVals) const {
1217 // Assign locations to each value returned by this call.
1218 SmallVector<CCValAssign, 16> RVLocs;
1219 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1220 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1221 CCInfo.AnalyzeCallResult(Ins,
1222 CCAssignFnForNode(CallConv, /* Return*/ true,
1225 // Copy all of the result registers out of their specified physreg.
1226 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1227 CCValAssign VA = RVLocs[i];
1230 if (VA.needsCustom()) {
1231 // Handle f64 or half of a v2f64.
1232 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1234 Chain = Lo.getValue(1);
1235 InFlag = Lo.getValue(2);
1236 VA = RVLocs[++i]; // skip ahead to next loc
1237 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1239 Chain = Hi.getValue(1);
1240 InFlag = Hi.getValue(2);
1241 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1243 if (VA.getLocVT() == MVT::v2f64) {
1244 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1245 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1246 DAG.getConstant(0, MVT::i32));
1248 VA = RVLocs[++i]; // skip ahead to next loc
1249 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1250 Chain = Lo.getValue(1);
1251 InFlag = Lo.getValue(2);
1252 VA = RVLocs[++i]; // skip ahead to next loc
1253 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1254 Chain = Hi.getValue(1);
1255 InFlag = Hi.getValue(2);
1256 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1257 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1258 DAG.getConstant(1, MVT::i32));
1261 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1263 Chain = Val.getValue(1);
1264 InFlag = Val.getValue(2);
1267 switch (VA.getLocInfo()) {
1268 default: llvm_unreachable("Unknown loc info!");
1269 case CCValAssign::Full: break;
1270 case CCValAssign::BCvt:
1271 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1275 InVals.push_back(Val);
1281 /// LowerMemOpCallTo - Store the argument to the stack.
1283 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1284 SDValue StackPtr, SDValue Arg,
1285 DebugLoc dl, SelectionDAG &DAG,
1286 const CCValAssign &VA,
1287 ISD::ArgFlagsTy Flags) const {
1288 unsigned LocMemOffset = VA.getLocMemOffset();
1289 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1290 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1291 return DAG.getStore(Chain, dl, Arg, PtrOff,
1292 MachinePointerInfo::getStack(LocMemOffset),
1296 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1297 SDValue Chain, SDValue &Arg,
1298 RegsToPassVector &RegsToPass,
1299 CCValAssign &VA, CCValAssign &NextVA,
1301 SmallVector<SDValue, 8> &MemOpChains,
1302 ISD::ArgFlagsTy Flags) const {
1304 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1305 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1306 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1308 if (NextVA.isRegLoc())
1309 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1311 assert(NextVA.isMemLoc());
1312 if (StackPtr.getNode() == 0)
1313 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1315 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1321 /// LowerCall - Lowering a call into a callseq_start <-
1322 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1325 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1326 SmallVectorImpl<SDValue> &InVals) const {
1327 SelectionDAG &DAG = CLI.DAG;
1328 DebugLoc &dl = CLI.DL;
1329 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1330 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1331 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1332 SDValue Chain = CLI.Chain;
1333 SDValue Callee = CLI.Callee;
1334 bool &isTailCall = CLI.IsTailCall;
1335 CallingConv::ID CallConv = CLI.CallConv;
1336 bool doesNotRet = CLI.DoesNotReturn;
1337 bool isVarArg = CLI.IsVarArg;
1339 MachineFunction &MF = DAG.getMachineFunction();
1340 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1341 bool IsSibCall = false;
1342 // Disable tail calls if they're not supported.
1343 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1346 // Check if it's really possible to do a tail call.
1347 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1348 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1349 Outs, OutVals, Ins, DAG);
1350 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1351 // detected sibcalls.
1358 // Analyze operands of the call, assigning locations to each operand.
1359 SmallVector<CCValAssign, 16> ArgLocs;
1360 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1361 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1362 CCInfo.AnalyzeCallOperands(Outs,
1363 CCAssignFnForNode(CallConv, /* Return*/ false,
1366 // Get a count of how many bytes are to be pushed on the stack.
1367 unsigned NumBytes = CCInfo.getNextStackOffset();
1369 // For tail calls, memory operands are available in our caller's stack.
1373 // Adjust the stack pointer for the new arguments...
1374 // These operations are automatically eliminated by the prolog/epilog pass
1376 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1378 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1380 RegsToPassVector RegsToPass;
1381 SmallVector<SDValue, 8> MemOpChains;
1383 // Walk the register/memloc assignments, inserting copies/loads. In the case
1384 // of tail call optimization, arguments are handled later.
1385 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1387 ++i, ++realArgIdx) {
1388 CCValAssign &VA = ArgLocs[i];
1389 SDValue Arg = OutVals[realArgIdx];
1390 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1391 bool isByVal = Flags.isByVal();
1393 // Promote the value if needed.
1394 switch (VA.getLocInfo()) {
1395 default: llvm_unreachable("Unknown loc info!");
1396 case CCValAssign::Full: break;
1397 case CCValAssign::SExt:
1398 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1400 case CCValAssign::ZExt:
1401 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1403 case CCValAssign::AExt:
1404 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1406 case CCValAssign::BCvt:
1407 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1411 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1412 if (VA.needsCustom()) {
1413 if (VA.getLocVT() == MVT::v2f64) {
1414 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1415 DAG.getConstant(0, MVT::i32));
1416 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1417 DAG.getConstant(1, MVT::i32));
1419 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1420 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1422 VA = ArgLocs[++i]; // skip ahead to next loc
1423 if (VA.isRegLoc()) {
1424 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1425 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1427 assert(VA.isMemLoc());
1429 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1430 dl, DAG, VA, Flags));
1433 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1434 StackPtr, MemOpChains, Flags);
1436 } else if (VA.isRegLoc()) {
1437 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1438 } else if (isByVal) {
1439 assert(VA.isMemLoc());
1440 unsigned offset = 0;
1442 // True if this byval aggregate will be split between registers
1444 if (CCInfo.isFirstByValRegValid()) {
1445 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1447 for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1448 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1449 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1450 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1451 MachinePointerInfo(),
1452 false, false, false, 0);
1453 MemOpChains.push_back(Load.getValue(1));
1454 RegsToPass.push_back(std::make_pair(j, Load));
1456 offset = ARM::R4 - CCInfo.getFirstByValReg();
1457 CCInfo.clearFirstByValReg();
1460 if (Flags.getByValSize() - 4*offset > 0) {
1461 unsigned LocMemOffset = VA.getLocMemOffset();
1462 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1463 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1465 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1466 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1467 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1469 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1471 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1472 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1473 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1474 Ops, array_lengthof(Ops)));
1476 } else if (!IsSibCall) {
1477 assert(VA.isMemLoc());
1479 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1480 dl, DAG, VA, Flags));
1484 if (!MemOpChains.empty())
1485 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1486 &MemOpChains[0], MemOpChains.size());
1488 // Build a sequence of copy-to-reg nodes chained together with token chain
1489 // and flag operands which copy the outgoing args into the appropriate regs.
1491 // Tail call byval lowering might overwrite argument registers so in case of
1492 // tail call optimization the copies to registers are lowered later.
1494 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1495 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1496 RegsToPass[i].second, InFlag);
1497 InFlag = Chain.getValue(1);
1500 // For tail calls lower the arguments to the 'real' stack slot.
1502 // Force all the incoming stack arguments to be loaded from the stack
1503 // before any new outgoing arguments are stored to the stack, because the
1504 // outgoing stack slots may alias the incoming argument stack slots, and
1505 // the alias isn't otherwise explicit. This is slightly more conservative
1506 // than necessary, because it means that each store effectively depends
1507 // on every argument instead of just those arguments it would clobber.
1509 // Do not flag preceding copytoreg stuff together with the following stuff.
1511 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1512 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1513 RegsToPass[i].second, InFlag);
1514 InFlag = Chain.getValue(1);
1519 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1520 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1521 // node so that legalize doesn't hack it.
1522 bool isDirect = false;
1523 bool isARMFunc = false;
1524 bool isLocalARMFunc = false;
1525 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1527 if (EnableARMLongCalls) {
1528 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1529 && "long-calls with non-static relocation model!");
1530 // Handle a global address or an external symbol. If it's not one of
1531 // those, the target's already in a register, so we don't need to do
1533 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1534 const GlobalValue *GV = G->getGlobal();
1535 // Create a constant pool entry for the callee address
1536 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1537 ARMConstantPoolValue *CPV =
1538 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1540 // Get the address of the callee into a register
1541 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1542 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1543 Callee = DAG.getLoad(getPointerTy(), dl,
1544 DAG.getEntryNode(), CPAddr,
1545 MachinePointerInfo::getConstantPool(),
1546 false, false, false, 0);
1547 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1548 const char *Sym = S->getSymbol();
1550 // Create a constant pool entry for the callee address
1551 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1552 ARMConstantPoolValue *CPV =
1553 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1554 ARMPCLabelIndex, 0);
1555 // Get the address of the callee into a register
1556 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1557 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1558 Callee = DAG.getLoad(getPointerTy(), dl,
1559 DAG.getEntryNode(), CPAddr,
1560 MachinePointerInfo::getConstantPool(),
1561 false, false, false, 0);
1563 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1564 const GlobalValue *GV = G->getGlobal();
1566 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1567 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1568 getTargetMachine().getRelocationModel() != Reloc::Static;
1569 isARMFunc = !Subtarget->isThumb() || isStub;
1570 // ARM call to a local ARM function is predicable.
1571 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1572 // tBX takes a register source operand.
1573 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1574 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1575 ARMConstantPoolValue *CPV =
1576 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1577 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1578 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1579 Callee = DAG.getLoad(getPointerTy(), dl,
1580 DAG.getEntryNode(), CPAddr,
1581 MachinePointerInfo::getConstantPool(),
1582 false, false, false, 0);
1583 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1584 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1585 getPointerTy(), Callee, PICLabel);
1587 // On ELF targets for PIC code, direct calls should go through the PLT
1588 unsigned OpFlags = 0;
1589 if (Subtarget->isTargetELF() &&
1590 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1591 OpFlags = ARMII::MO_PLT;
1592 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1594 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1596 bool isStub = Subtarget->isTargetDarwin() &&
1597 getTargetMachine().getRelocationModel() != Reloc::Static;
1598 isARMFunc = !Subtarget->isThumb() || isStub;
1599 // tBX takes a register source operand.
1600 const char *Sym = S->getSymbol();
1601 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1602 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1603 ARMConstantPoolValue *CPV =
1604 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1605 ARMPCLabelIndex, 4);
1606 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1607 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1608 Callee = DAG.getLoad(getPointerTy(), dl,
1609 DAG.getEntryNode(), CPAddr,
1610 MachinePointerInfo::getConstantPool(),
1611 false, false, false, 0);
1612 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1613 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1614 getPointerTy(), Callee, PICLabel);
1616 unsigned OpFlags = 0;
1617 // On ELF targets for PIC code, direct calls should go through the PLT
1618 if (Subtarget->isTargetELF() &&
1619 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1620 OpFlags = ARMII::MO_PLT;
1621 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1625 // FIXME: handle tail calls differently.
1627 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1628 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1629 if (Subtarget->isThumb()) {
1630 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1631 CallOpc = ARMISD::CALL_NOLINK;
1633 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1635 if (!isDirect && !Subtarget->hasV5TOps())
1636 CallOpc = ARMISD::CALL_NOLINK;
1637 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1638 // Emit regular call when code size is the priority
1640 // "mov lr, pc; b _foo" to avoid confusing the RSP
1641 CallOpc = ARMISD::CALL_NOLINK;
1643 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1646 std::vector<SDValue> Ops;
1647 Ops.push_back(Chain);
1648 Ops.push_back(Callee);
1650 // Add argument registers to the end of the list so that they are known live
1652 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1653 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1654 RegsToPass[i].second.getValueType()));
1656 // Add a register mask operand representing the call-preserved registers.
1657 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1658 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1659 assert(Mask && "Missing call preserved mask for calling convention");
1660 Ops.push_back(DAG.getRegisterMask(Mask));
1662 if (InFlag.getNode())
1663 Ops.push_back(InFlag);
1665 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1667 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1669 // Returns a chain and a flag for retval copy to use.
1670 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1671 InFlag = Chain.getValue(1);
1673 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1674 DAG.getIntPtrConstant(0, true), InFlag);
1676 InFlag = Chain.getValue(1);
1678 // Handle result values, copying them out of physregs into vregs that we
1680 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1684 /// HandleByVal - Every parameter *after* a byval parameter is passed
1685 /// on the stack. Remember the next parameter register to allocate,
1686 /// and then confiscate the rest of the parameter registers to insure
1689 ARMTargetLowering::HandleByVal(
1690 CCState *State, unsigned &size, unsigned Align) const {
1691 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1692 assert((State->getCallOrPrologue() == Prologue ||
1693 State->getCallOrPrologue() == Call) &&
1694 "unhandled ParmContext");
1695 if ((!State->isFirstByValRegValid()) &&
1696 (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1697 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1698 unsigned AlignInRegs = Align / 4;
1699 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1700 for (unsigned i = 0; i < Waste; ++i)
1701 reg = State->AllocateReg(GPRArgRegs, 4);
1704 State->setFirstByValReg(reg);
1705 // At a call site, a byval parameter that is split between
1706 // registers and memory needs its size truncated here. In a
1707 // function prologue, such byval parameters are reassembled in
1708 // memory, and are not truncated.
1709 if (State->getCallOrPrologue() == Call) {
1710 unsigned excess = 4 * (ARM::R4 - reg);
1711 assert(size >= excess && "expected larger existing stack allocation");
1716 // Confiscate any remaining parameter registers to preclude their
1717 // assignment to subsequent parameters.
1718 while (State->AllocateReg(GPRArgRegs, 4))
1722 /// MatchingStackOffset - Return true if the given stack call argument is
1723 /// already available in the same position (relatively) of the caller's
1724 /// incoming argument stack.
1726 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1727 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1728 const TargetInstrInfo *TII) {
1729 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1731 if (Arg.getOpcode() == ISD::CopyFromReg) {
1732 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1733 if (!TargetRegisterInfo::isVirtualRegister(VR))
1735 MachineInstr *Def = MRI->getVRegDef(VR);
1738 if (!Flags.isByVal()) {
1739 if (!TII->isLoadFromStackSlot(Def, FI))
1744 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1745 if (Flags.isByVal())
1746 // ByVal argument is passed in as a pointer but it's now being
1747 // dereferenced. e.g.
1748 // define @foo(%struct.X* %A) {
1749 // tail call @bar(%struct.X* byval %A)
1752 SDValue Ptr = Ld->getBasePtr();
1753 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1756 FI = FINode->getIndex();
1760 assert(FI != INT_MAX);
1761 if (!MFI->isFixedObjectIndex(FI))
1763 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1766 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1767 /// for tail call optimization. Targets which want to do tail call
1768 /// optimization should implement this function.
1770 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1771 CallingConv::ID CalleeCC,
1773 bool isCalleeStructRet,
1774 bool isCallerStructRet,
1775 const SmallVectorImpl<ISD::OutputArg> &Outs,
1776 const SmallVectorImpl<SDValue> &OutVals,
1777 const SmallVectorImpl<ISD::InputArg> &Ins,
1778 SelectionDAG& DAG) const {
1779 const Function *CallerF = DAG.getMachineFunction().getFunction();
1780 CallingConv::ID CallerCC = CallerF->getCallingConv();
1781 bool CCMatch = CallerCC == CalleeCC;
1783 // Look for obvious safe cases to perform tail call optimization that do not
1784 // require ABI changes. This is what gcc calls sibcall.
1786 // Do not sibcall optimize vararg calls unless the call site is not passing
1788 if (isVarArg && !Outs.empty())
1791 // Also avoid sibcall optimization if either caller or callee uses struct
1792 // return semantics.
1793 if (isCalleeStructRet || isCallerStructRet)
1796 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1797 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1798 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1799 // support in the assembler and linker to be used. This would need to be
1800 // fixed to fully support tail calls in Thumb1.
1802 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1803 // LR. This means if we need to reload LR, it takes an extra instructions,
1804 // which outweighs the value of the tail call; but here we don't know yet
1805 // whether LR is going to be used. Probably the right approach is to
1806 // generate the tail call here and turn it back into CALL/RET in
1807 // emitEpilogue if LR is used.
1809 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1810 // but we need to make sure there are enough registers; the only valid
1811 // registers are the 4 used for parameters. We don't currently do this
1813 if (Subtarget->isThumb1Only())
1816 // If the calling conventions do not match, then we'd better make sure the
1817 // results are returned in the same way as what the caller expects.
1819 SmallVector<CCValAssign, 16> RVLocs1;
1820 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1821 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1822 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1824 SmallVector<CCValAssign, 16> RVLocs2;
1825 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1826 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1827 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1829 if (RVLocs1.size() != RVLocs2.size())
1831 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1832 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1834 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1836 if (RVLocs1[i].isRegLoc()) {
1837 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1840 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1846 // If Caller's vararg or byval argument has been split between registers and
1847 // stack, do not perform tail call, since part of the argument is in caller's
1849 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1850 getInfo<ARMFunctionInfo>();
1851 if (AFI_Caller->getVarArgsRegSaveSize())
1854 // If the callee takes no arguments then go on to check the results of the
1856 if (!Outs.empty()) {
1857 // Check if stack adjustment is needed. For now, do not do this if any
1858 // argument is passed on the stack.
1859 SmallVector<CCValAssign, 16> ArgLocs;
1860 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1861 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1862 CCInfo.AnalyzeCallOperands(Outs,
1863 CCAssignFnForNode(CalleeCC, false, isVarArg));
1864 if (CCInfo.getNextStackOffset()) {
1865 MachineFunction &MF = DAG.getMachineFunction();
1867 // Check if the arguments are already laid out in the right way as
1868 // the caller's fixed stack objects.
1869 MachineFrameInfo *MFI = MF.getFrameInfo();
1870 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1871 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1872 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1874 ++i, ++realArgIdx) {
1875 CCValAssign &VA = ArgLocs[i];
1876 EVT RegVT = VA.getLocVT();
1877 SDValue Arg = OutVals[realArgIdx];
1878 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1879 if (VA.getLocInfo() == CCValAssign::Indirect)
1881 if (VA.needsCustom()) {
1882 // f64 and vector types are split into multiple registers or
1883 // register/stack-slot combinations. The types will not match
1884 // the registers; give up on memory f64 refs until we figure
1885 // out what to do about this.
1888 if (!ArgLocs[++i].isRegLoc())
1890 if (RegVT == MVT::v2f64) {
1891 if (!ArgLocs[++i].isRegLoc())
1893 if (!ArgLocs[++i].isRegLoc())
1896 } else if (!VA.isRegLoc()) {
1897 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1909 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1910 MachineFunction &MF, bool isVarArg,
1911 const SmallVectorImpl<ISD::OutputArg> &Outs,
1912 LLVMContext &Context) const {
1913 SmallVector<CCValAssign, 16> RVLocs;
1914 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1915 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
1920 ARMTargetLowering::LowerReturn(SDValue Chain,
1921 CallingConv::ID CallConv, bool isVarArg,
1922 const SmallVectorImpl<ISD::OutputArg> &Outs,
1923 const SmallVectorImpl<SDValue> &OutVals,
1924 DebugLoc dl, SelectionDAG &DAG) const {
1926 // CCValAssign - represent the assignment of the return value to a location.
1927 SmallVector<CCValAssign, 16> RVLocs;
1929 // CCState - Info about the registers and stack slots.
1930 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1931 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1933 // Analyze outgoing return values.
1934 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1938 SmallVector<SDValue, 4> RetOps;
1939 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1941 // Copy the result values into the output registers.
1942 for (unsigned i = 0, realRVLocIdx = 0;
1944 ++i, ++realRVLocIdx) {
1945 CCValAssign &VA = RVLocs[i];
1946 assert(VA.isRegLoc() && "Can only return in registers!");
1948 SDValue Arg = OutVals[realRVLocIdx];
1950 switch (VA.getLocInfo()) {
1951 default: llvm_unreachable("Unknown loc info!");
1952 case CCValAssign::Full: break;
1953 case CCValAssign::BCvt:
1954 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1958 if (VA.needsCustom()) {
1959 if (VA.getLocVT() == MVT::v2f64) {
1960 // Extract the first half and return it in two registers.
1961 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1962 DAG.getConstant(0, MVT::i32));
1963 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1964 DAG.getVTList(MVT::i32, MVT::i32), Half);
1966 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1967 Flag = Chain.getValue(1);
1968 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1969 VA = RVLocs[++i]; // skip ahead to next loc
1970 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1971 HalfGPRs.getValue(1), Flag);
1972 Flag = Chain.getValue(1);
1973 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1974 VA = RVLocs[++i]; // skip ahead to next loc
1976 // Extract the 2nd half and fall through to handle it as an f64 value.
1977 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1978 DAG.getConstant(1, MVT::i32));
1980 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1982 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1983 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1984 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1985 Flag = Chain.getValue(1);
1986 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1987 VA = RVLocs[++i]; // skip ahead to next loc
1988 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1991 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1993 // Guarantee that all emitted copies are
1994 // stuck together, avoiding something bad.
1995 Flag = Chain.getValue(1);
1996 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1999 // Update chain and glue.
2002 RetOps.push_back(Flag);
2004 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2005 RetOps.data(), RetOps.size());
2008 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2009 if (N->getNumValues() != 1)
2011 if (!N->hasNUsesOfValue(1, 0))
2014 SDValue TCChain = Chain;
2015 SDNode *Copy = *N->use_begin();
2016 if (Copy->getOpcode() == ISD::CopyToReg) {
2017 // If the copy has a glue operand, we conservatively assume it isn't safe to
2018 // perform a tail call.
2019 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2021 TCChain = Copy->getOperand(0);
2022 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2023 SDNode *VMov = Copy;
2024 // f64 returned in a pair of GPRs.
2025 SmallPtrSet<SDNode*, 2> Copies;
2026 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2028 if (UI->getOpcode() != ISD::CopyToReg)
2032 if (Copies.size() > 2)
2035 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2037 SDValue UseChain = UI->getOperand(0);
2038 if (Copies.count(UseChain.getNode()))
2045 } else if (Copy->getOpcode() == ISD::BITCAST) {
2046 // f32 returned in a single GPR.
2047 if (!Copy->hasOneUse())
2049 Copy = *Copy->use_begin();
2050 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2052 Chain = Copy->getOperand(0);
2057 bool HasRet = false;
2058 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2060 if (UI->getOpcode() != ARMISD::RET_FLAG)
2072 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2073 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2076 if (!CI->isTailCall())
2079 return !Subtarget->isThumb1Only();
2082 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2083 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2084 // one of the above mentioned nodes. It has to be wrapped because otherwise
2085 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2086 // be used to form addressing mode. These wrapped nodes will be selected
2088 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2089 EVT PtrVT = Op.getValueType();
2090 // FIXME there is no actual debug info here
2091 DebugLoc dl = Op.getDebugLoc();
2092 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2094 if (CP->isMachineConstantPoolEntry())
2095 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2096 CP->getAlignment());
2098 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2099 CP->getAlignment());
2100 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2103 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2104 return MachineJumpTableInfo::EK_Inline;
2107 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2108 SelectionDAG &DAG) const {
2109 MachineFunction &MF = DAG.getMachineFunction();
2110 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2111 unsigned ARMPCLabelIndex = 0;
2112 DebugLoc DL = Op.getDebugLoc();
2113 EVT PtrVT = getPointerTy();
2114 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2115 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2117 if (RelocM == Reloc::Static) {
2118 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2120 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2121 ARMPCLabelIndex = AFI->createPICLabelUId();
2122 ARMConstantPoolValue *CPV =
2123 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2124 ARMCP::CPBlockAddress, PCAdj);
2125 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2127 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2128 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2129 MachinePointerInfo::getConstantPool(),
2130 false, false, false, 0);
2131 if (RelocM == Reloc::Static)
2133 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2134 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2137 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2139 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2140 SelectionDAG &DAG) const {
2141 DebugLoc dl = GA->getDebugLoc();
2142 EVT PtrVT = getPointerTy();
2143 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2144 MachineFunction &MF = DAG.getMachineFunction();
2145 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2146 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2147 ARMConstantPoolValue *CPV =
2148 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2149 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2150 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2151 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2152 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2153 MachinePointerInfo::getConstantPool(),
2154 false, false, false, 0);
2155 SDValue Chain = Argument.getValue(1);
2157 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2158 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2160 // call __tls_get_addr.
2163 Entry.Node = Argument;
2164 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2165 Args.push_back(Entry);
2166 // FIXME: is there useful debug info available here?
2167 TargetLowering::CallLoweringInfo CLI(Chain,
2168 (Type *) Type::getInt32Ty(*DAG.getContext()),
2169 false, false, false, false,
2170 0, CallingConv::C, /*isTailCall=*/false,
2171 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2172 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2173 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2174 return CallResult.first;
2177 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2178 // "local exec" model.
2180 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2182 TLSModel::Model model) const {
2183 const GlobalValue *GV = GA->getGlobal();
2184 DebugLoc dl = GA->getDebugLoc();
2186 SDValue Chain = DAG.getEntryNode();
2187 EVT PtrVT = getPointerTy();
2188 // Get the Thread Pointer
2189 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2191 if (model == TLSModel::InitialExec) {
2192 MachineFunction &MF = DAG.getMachineFunction();
2193 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2194 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2195 // Initial exec model.
2196 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2197 ARMConstantPoolValue *CPV =
2198 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2199 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2201 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2202 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2203 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2204 MachinePointerInfo::getConstantPool(),
2205 false, false, false, 0);
2206 Chain = Offset.getValue(1);
2208 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2209 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2211 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2212 MachinePointerInfo::getConstantPool(),
2213 false, false, false, 0);
2216 assert(model == TLSModel::LocalExec);
2217 ARMConstantPoolValue *CPV =
2218 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2219 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2220 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2221 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2222 MachinePointerInfo::getConstantPool(),
2223 false, false, false, 0);
2226 // The address of the thread local variable is the add of the thread
2227 // pointer with the offset of the variable.
2228 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2232 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2233 // TODO: implement the "local dynamic" model
2234 assert(Subtarget->isTargetELF() &&
2235 "TLS not implemented for non-ELF targets");
2236 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2238 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2241 case TLSModel::GeneralDynamic:
2242 case TLSModel::LocalDynamic:
2243 return LowerToTLSGeneralDynamicModel(GA, DAG);
2244 case TLSModel::InitialExec:
2245 case TLSModel::LocalExec:
2246 return LowerToTLSExecModels(GA, DAG, model);
2248 llvm_unreachable("bogus TLS model");
2251 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2252 SelectionDAG &DAG) const {
2253 EVT PtrVT = getPointerTy();
2254 DebugLoc dl = Op.getDebugLoc();
2255 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2256 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2257 if (RelocM == Reloc::PIC_) {
2258 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2259 ARMConstantPoolValue *CPV =
2260 ARMConstantPoolConstant::Create(GV,
2261 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2262 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2263 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2264 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2266 MachinePointerInfo::getConstantPool(),
2267 false, false, false, 0);
2268 SDValue Chain = Result.getValue(1);
2269 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2270 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2272 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2273 MachinePointerInfo::getGOT(),
2274 false, false, false, 0);
2278 // If we have T2 ops, we can materialize the address directly via movt/movw
2279 // pair. This is always cheaper.
2280 if (Subtarget->useMovt()) {
2282 // FIXME: Once remat is capable of dealing with instructions with register
2283 // operands, expand this into two nodes.
2284 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2285 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2287 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2288 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2289 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2290 MachinePointerInfo::getConstantPool(),
2291 false, false, false, 0);
2295 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2296 SelectionDAG &DAG) const {
2297 EVT PtrVT = getPointerTy();
2298 DebugLoc dl = Op.getDebugLoc();
2299 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2300 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2301 MachineFunction &MF = DAG.getMachineFunction();
2302 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2304 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2305 // update ARMFastISel::ARMMaterializeGV.
2306 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2308 // FIXME: Once remat is capable of dealing with instructions with register
2309 // operands, expand this into two nodes.
2310 if (RelocM == Reloc::Static)
2311 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2312 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2314 unsigned Wrapper = (RelocM == Reloc::PIC_)
2315 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2316 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2317 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2318 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2319 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2320 MachinePointerInfo::getGOT(),
2321 false, false, false, 0);
2325 unsigned ARMPCLabelIndex = 0;
2327 if (RelocM == Reloc::Static) {
2328 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2330 ARMPCLabelIndex = AFI->createPICLabelUId();
2331 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2332 ARMConstantPoolValue *CPV =
2333 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2335 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2337 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2339 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2340 MachinePointerInfo::getConstantPool(),
2341 false, false, false, 0);
2342 SDValue Chain = Result.getValue(1);
2344 if (RelocM == Reloc::PIC_) {
2345 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2346 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2349 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2350 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2351 false, false, false, 0);
2356 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2357 SelectionDAG &DAG) const {
2358 assert(Subtarget->isTargetELF() &&
2359 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2360 MachineFunction &MF = DAG.getMachineFunction();
2361 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2362 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2363 EVT PtrVT = getPointerTy();
2364 DebugLoc dl = Op.getDebugLoc();
2365 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2366 ARMConstantPoolValue *CPV =
2367 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2368 ARMPCLabelIndex, PCAdj);
2369 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2370 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2371 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2372 MachinePointerInfo::getConstantPool(),
2373 false, false, false, 0);
2374 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2375 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2379 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2380 DebugLoc dl = Op.getDebugLoc();
2381 SDValue Val = DAG.getConstant(0, MVT::i32);
2382 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2383 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2384 Op.getOperand(1), Val);
2388 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2389 DebugLoc dl = Op.getDebugLoc();
2390 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2391 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2395 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2396 const ARMSubtarget *Subtarget) const {
2397 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2398 DebugLoc dl = Op.getDebugLoc();
2400 default: return SDValue(); // Don't custom lower most intrinsics.
2401 case Intrinsic::arm_thread_pointer: {
2402 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2403 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2405 case Intrinsic::eh_sjlj_lsda: {
2406 MachineFunction &MF = DAG.getMachineFunction();
2407 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2408 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2409 EVT PtrVT = getPointerTy();
2410 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2412 unsigned PCAdj = (RelocM != Reloc::PIC_)
2413 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2414 ARMConstantPoolValue *CPV =
2415 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2416 ARMCP::CPLSDA, PCAdj);
2417 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2418 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2420 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2421 MachinePointerInfo::getConstantPool(),
2422 false, false, false, 0);
2424 if (RelocM == Reloc::PIC_) {
2425 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2426 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2430 case Intrinsic::arm_neon_vmulls:
2431 case Intrinsic::arm_neon_vmullu: {
2432 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2433 ? ARMISD::VMULLs : ARMISD::VMULLu;
2434 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2435 Op.getOperand(1), Op.getOperand(2));
2440 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2441 const ARMSubtarget *Subtarget) {
2442 DebugLoc dl = Op.getDebugLoc();
2443 if (!Subtarget->hasDataBarrier()) {
2444 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2445 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2447 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2448 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2449 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2450 DAG.getConstant(0, MVT::i32));
2453 SDValue Op5 = Op.getOperand(5);
2454 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2455 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2456 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2457 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2459 ARM_MB::MemBOpt DMBOpt;
2460 if (isDeviceBarrier)
2461 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2463 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2464 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2465 DAG.getConstant(DMBOpt, MVT::i32));
2469 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2470 const ARMSubtarget *Subtarget) {
2471 // FIXME: handle "fence singlethread" more efficiently.
2472 DebugLoc dl = Op.getDebugLoc();
2473 if (!Subtarget->hasDataBarrier()) {
2474 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2475 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2477 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2478 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2479 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2480 DAG.getConstant(0, MVT::i32));
2483 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2484 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2487 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2488 const ARMSubtarget *Subtarget) {
2489 // ARM pre v5TE and Thumb1 does not have preload instructions.
2490 if (!(Subtarget->isThumb2() ||
2491 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2492 // Just preserve the chain.
2493 return Op.getOperand(0);
2495 DebugLoc dl = Op.getDebugLoc();
2496 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2498 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2499 // ARMv7 with MP extension has PLDW.
2500 return Op.getOperand(0);
2502 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2503 if (Subtarget->isThumb()) {
2505 isRead = ~isRead & 1;
2506 isData = ~isData & 1;
2509 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2510 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2511 DAG.getConstant(isData, MVT::i32));
2514 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2515 MachineFunction &MF = DAG.getMachineFunction();
2516 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2518 // vastart just stores the address of the VarArgsFrameIndex slot into the
2519 // memory location argument.
2520 DebugLoc dl = Op.getDebugLoc();
2521 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2522 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2523 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2524 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2525 MachinePointerInfo(SV), false, false, 0);
2529 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2530 SDValue &Root, SelectionDAG &DAG,
2531 DebugLoc dl) const {
2532 MachineFunction &MF = DAG.getMachineFunction();
2533 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2535 const TargetRegisterClass *RC;
2536 if (AFI->isThumb1OnlyFunction())
2537 RC = &ARM::tGPRRegClass;
2539 RC = &ARM::GPRRegClass;
2541 // Transform the arguments stored in physical registers into virtual ones.
2542 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2543 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2546 if (NextVA.isMemLoc()) {
2547 MachineFrameInfo *MFI = MF.getFrameInfo();
2548 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2550 // Create load node to retrieve arguments from the stack.
2551 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2552 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2553 MachinePointerInfo::getFixedStack(FI),
2554 false, false, false, 0);
2556 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2557 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2560 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2564 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2565 unsigned &VARegSize, unsigned &VARegSaveSize)
2568 if (CCInfo.isFirstByValRegValid())
2569 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2571 unsigned int firstUnalloced;
2572 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2573 sizeof(GPRArgRegs) /
2574 sizeof(GPRArgRegs[0]));
2575 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2578 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2579 VARegSize = NumGPRs * 4;
2580 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2583 // The remaining GPRs hold either the beginning of variable-argument
2584 // data, or the beginning of an aggregate passed by value (usually
2585 // byval). Either way, we allocate stack slots adjacent to the data
2586 // provided by our caller, and store the unallocated registers there.
2587 // If this is a variadic function, the va_list pointer will begin with
2588 // these values; otherwise, this reassembles a (byval) structure that
2589 // was split between registers and memory.
2591 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2592 DebugLoc dl, SDValue &Chain,
2593 const Value *OrigArg,
2594 unsigned OffsetFromOrigArg,
2596 bool ForceMutable) const {
2597 MachineFunction &MF = DAG.getMachineFunction();
2598 MachineFrameInfo *MFI = MF.getFrameInfo();
2599 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2600 unsigned firstRegToSaveIndex;
2601 if (CCInfo.isFirstByValRegValid())
2602 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2604 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2605 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2608 unsigned VARegSize, VARegSaveSize;
2609 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2610 if (VARegSaveSize) {
2611 // If this function is vararg, store any remaining integer argument regs
2612 // to their spots on the stack so that they may be loaded by deferencing
2613 // the result of va_next.
2614 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2615 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2616 ArgOffset + VARegSaveSize
2619 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2622 SmallVector<SDValue, 4> MemOps;
2623 for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2624 const TargetRegisterClass *RC;
2625 if (AFI->isThumb1OnlyFunction())
2626 RC = &ARM::tGPRRegClass;
2628 RC = &ARM::GPRRegClass;
2630 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2631 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2633 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2634 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2636 MemOps.push_back(Store);
2637 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2638 DAG.getConstant(4, getPointerTy()));
2640 if (!MemOps.empty())
2641 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2642 &MemOps[0], MemOps.size());
2644 // This will point to the next argument passed via stack.
2645 AFI->setVarArgsFrameIndex(
2646 MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2650 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2651 CallingConv::ID CallConv, bool isVarArg,
2652 const SmallVectorImpl<ISD::InputArg>
2654 DebugLoc dl, SelectionDAG &DAG,
2655 SmallVectorImpl<SDValue> &InVals)
2657 MachineFunction &MF = DAG.getMachineFunction();
2658 MachineFrameInfo *MFI = MF.getFrameInfo();
2660 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2662 // Assign locations to all of the incoming arguments.
2663 SmallVector<CCValAssign, 16> ArgLocs;
2664 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2665 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2666 CCInfo.AnalyzeFormalArguments(Ins,
2667 CCAssignFnForNode(CallConv, /* Return*/ false,
2670 SmallVector<SDValue, 16> ArgValues;
2671 int lastInsIndex = -1;
2673 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2674 unsigned CurArgIdx = 0;
2675 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2676 CCValAssign &VA = ArgLocs[i];
2677 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2678 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2679 // Arguments stored in registers.
2680 if (VA.isRegLoc()) {
2681 EVT RegVT = VA.getLocVT();
2683 if (VA.needsCustom()) {
2684 // f64 and vector types are split up into multiple registers or
2685 // combinations of registers and stack slots.
2686 if (VA.getLocVT() == MVT::v2f64) {
2687 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2689 VA = ArgLocs[++i]; // skip ahead to next loc
2691 if (VA.isMemLoc()) {
2692 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2693 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2694 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2695 MachinePointerInfo::getFixedStack(FI),
2696 false, false, false, 0);
2698 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2701 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2702 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2703 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2704 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2705 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2707 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2710 const TargetRegisterClass *RC;
2712 if (RegVT == MVT::f32)
2713 RC = &ARM::SPRRegClass;
2714 else if (RegVT == MVT::f64)
2715 RC = &ARM::DPRRegClass;
2716 else if (RegVT == MVT::v2f64)
2717 RC = &ARM::QPRRegClass;
2718 else if (RegVT == MVT::i32)
2719 RC = AFI->isThumb1OnlyFunction() ?
2720 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2721 (const TargetRegisterClass*)&ARM::GPRRegClass;
2723 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2725 // Transform the arguments in physical registers into virtual ones.
2726 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2727 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2730 // If this is an 8 or 16-bit value, it is really passed promoted
2731 // to 32 bits. Insert an assert[sz]ext to capture this, then
2732 // truncate to the right size.
2733 switch (VA.getLocInfo()) {
2734 default: llvm_unreachable("Unknown loc info!");
2735 case CCValAssign::Full: break;
2736 case CCValAssign::BCvt:
2737 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2739 case CCValAssign::SExt:
2740 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2741 DAG.getValueType(VA.getValVT()));
2742 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2744 case CCValAssign::ZExt:
2745 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2746 DAG.getValueType(VA.getValVT()));
2747 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2751 InVals.push_back(ArgValue);
2753 } else { // VA.isRegLoc()
2756 assert(VA.isMemLoc());
2757 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2759 int index = ArgLocs[i].getValNo();
2761 // Some Ins[] entries become multiple ArgLoc[] entries.
2762 // Process them only once.
2763 if (index != lastInsIndex)
2765 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2766 // FIXME: For now, all byval parameter objects are marked mutable.
2767 // This can be changed with more analysis.
2768 // In case of tail call optimization mark all arguments mutable.
2769 // Since they could be overwritten by lowering of arguments in case of
2771 if (Flags.isByVal()) {
2772 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2773 if (!AFI->getVarArgsFrameIndex()) {
2774 VarArgStyleRegisters(CCInfo, DAG,
2775 dl, Chain, CurOrigArg,
2776 Ins[VA.getValNo()].PartOffset,
2777 VA.getLocMemOffset(),
2778 true /*force mutable frames*/);
2779 int VAFrameIndex = AFI->getVarArgsFrameIndex();
2780 InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2782 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2783 VA.getLocMemOffset(), false);
2784 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2787 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2788 VA.getLocMemOffset(), true);
2790 // Create load nodes to retrieve arguments from the stack.
2791 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2792 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2793 MachinePointerInfo::getFixedStack(FI),
2794 false, false, false, 0));
2796 lastInsIndex = index;
2803 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2804 CCInfo.getNextStackOffset());
2809 /// isFloatingPointZero - Return true if this is +0.0.
2810 static bool isFloatingPointZero(SDValue Op) {
2811 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2812 return CFP->getValueAPF().isPosZero();
2813 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2814 // Maybe this has already been legalized into the constant pool?
2815 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2816 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2817 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2818 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2819 return CFP->getValueAPF().isPosZero();
2825 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2826 /// the given operands.
2828 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2829 SDValue &ARMcc, SelectionDAG &DAG,
2830 DebugLoc dl) const {
2831 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2832 unsigned C = RHSC->getZExtValue();
2833 if (!isLegalICmpImmediate(C)) {
2834 // Constant does not fit, try adjusting it by one?
2839 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2840 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2841 RHS = DAG.getConstant(C-1, MVT::i32);
2846 if (C != 0 && isLegalICmpImmediate(C-1)) {
2847 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2848 RHS = DAG.getConstant(C-1, MVT::i32);
2853 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2854 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2855 RHS = DAG.getConstant(C+1, MVT::i32);
2860 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2861 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2862 RHS = DAG.getConstant(C+1, MVT::i32);
2869 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2870 ARMISD::NodeType CompareType;
2873 CompareType = ARMISD::CMP;
2878 CompareType = ARMISD::CMPZ;
2881 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2882 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2885 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2887 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2888 DebugLoc dl) const {
2890 if (!isFloatingPointZero(RHS))
2891 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2893 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2894 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2897 /// duplicateCmp - Glue values can have only one use, so this function
2898 /// duplicates a comparison node.
2900 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2901 unsigned Opc = Cmp.getOpcode();
2902 DebugLoc DL = Cmp.getDebugLoc();
2903 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2904 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2906 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2907 Cmp = Cmp.getOperand(0);
2908 Opc = Cmp.getOpcode();
2909 if (Opc == ARMISD::CMPFP)
2910 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2912 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2913 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2915 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2918 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2919 SDValue Cond = Op.getOperand(0);
2920 SDValue SelectTrue = Op.getOperand(1);
2921 SDValue SelectFalse = Op.getOperand(2);
2922 DebugLoc dl = Op.getDebugLoc();
2926 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2927 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2929 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2930 const ConstantSDNode *CMOVTrue =
2931 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2932 const ConstantSDNode *CMOVFalse =
2933 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2935 if (CMOVTrue && CMOVFalse) {
2936 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2937 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2941 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2943 False = SelectFalse;
2944 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2949 if (True.getNode() && False.getNode()) {
2950 EVT VT = Op.getValueType();
2951 SDValue ARMcc = Cond.getOperand(2);
2952 SDValue CCR = Cond.getOperand(3);
2953 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2954 assert(True.getValueType() == VT);
2955 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2960 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2961 // undefined bits before doing a full-word comparison with zero.
2962 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2963 DAG.getConstant(1, Cond.getValueType()));
2965 return DAG.getSelectCC(dl, Cond,
2966 DAG.getConstant(0, Cond.getValueType()),
2967 SelectTrue, SelectFalse, ISD::SETNE);
2970 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2971 EVT VT = Op.getValueType();
2972 SDValue LHS = Op.getOperand(0);
2973 SDValue RHS = Op.getOperand(1);
2974 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2975 SDValue TrueVal = Op.getOperand(2);
2976 SDValue FalseVal = Op.getOperand(3);
2977 DebugLoc dl = Op.getDebugLoc();
2979 if (LHS.getValueType() == MVT::i32) {
2981 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2982 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2983 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2986 ARMCC::CondCodes CondCode, CondCode2;
2987 FPCCToARMCC(CC, CondCode, CondCode2);
2989 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2990 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2991 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2992 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2994 if (CondCode2 != ARMCC::AL) {
2995 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2996 // FIXME: Needs another CMP because flag can have but one use.
2997 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2998 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2999 Result, TrueVal, ARMcc2, CCR, Cmp2);
3004 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3005 /// to morph to an integer compare sequence.
3006 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3007 const ARMSubtarget *Subtarget) {
3008 SDNode *N = Op.getNode();
3009 if (!N->hasOneUse())
3010 // Otherwise it requires moving the value from fp to integer registers.
3012 if (!N->getNumValues())
3014 EVT VT = Op.getValueType();
3015 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3016 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3017 // vmrs are very slow, e.g. cortex-a8.
3020 if (isFloatingPointZero(Op)) {
3024 return ISD::isNormalLoad(N);
3027 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3028 if (isFloatingPointZero(Op))
3029 return DAG.getConstant(0, MVT::i32);
3031 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3032 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3033 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3034 Ld->isVolatile(), Ld->isNonTemporal(),
3035 Ld->isInvariant(), Ld->getAlignment());
3037 llvm_unreachable("Unknown VFP cmp argument!");
3040 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3041 SDValue &RetVal1, SDValue &RetVal2) {
3042 if (isFloatingPointZero(Op)) {
3043 RetVal1 = DAG.getConstant(0, MVT::i32);
3044 RetVal2 = DAG.getConstant(0, MVT::i32);
3048 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3049 SDValue Ptr = Ld->getBasePtr();
3050 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3051 Ld->getChain(), Ptr,
3052 Ld->getPointerInfo(),
3053 Ld->isVolatile(), Ld->isNonTemporal(),
3054 Ld->isInvariant(), Ld->getAlignment());
3056 EVT PtrType = Ptr.getValueType();
3057 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3058 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3059 PtrType, Ptr, DAG.getConstant(4, PtrType));
3060 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3061 Ld->getChain(), NewPtr,
3062 Ld->getPointerInfo().getWithOffset(4),
3063 Ld->isVolatile(), Ld->isNonTemporal(),
3064 Ld->isInvariant(), NewAlign);
3068 llvm_unreachable("Unknown VFP cmp argument!");
3071 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3072 /// f32 and even f64 comparisons to integer ones.
3074 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3075 SDValue Chain = Op.getOperand(0);
3076 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3077 SDValue LHS = Op.getOperand(2);
3078 SDValue RHS = Op.getOperand(3);
3079 SDValue Dest = Op.getOperand(4);
3080 DebugLoc dl = Op.getDebugLoc();
3082 bool LHSSeenZero = false;
3083 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3084 bool RHSSeenZero = false;
3085 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3086 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3087 // If unsafe fp math optimization is enabled and there are no other uses of
3088 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3089 // to an integer comparison.
3090 if (CC == ISD::SETOEQ)
3092 else if (CC == ISD::SETUNE)
3095 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3097 if (LHS.getValueType() == MVT::f32) {
3098 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3099 bitcastf32Toi32(LHS, DAG), Mask);
3100 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3101 bitcastf32Toi32(RHS, DAG), Mask);
3102 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3103 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3104 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3105 Chain, Dest, ARMcc, CCR, Cmp);
3110 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3111 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3112 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3113 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3114 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3115 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3116 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3117 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3118 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3124 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3125 SDValue Chain = Op.getOperand(0);
3126 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3127 SDValue LHS = Op.getOperand(2);
3128 SDValue RHS = Op.getOperand(3);
3129 SDValue Dest = Op.getOperand(4);
3130 DebugLoc dl = Op.getDebugLoc();
3132 if (LHS.getValueType() == MVT::i32) {
3134 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3135 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3136 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3137 Chain, Dest, ARMcc, CCR, Cmp);
3140 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3142 if (getTargetMachine().Options.UnsafeFPMath &&
3143 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3144 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3145 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3146 if (Result.getNode())
3150 ARMCC::CondCodes CondCode, CondCode2;
3151 FPCCToARMCC(CC, CondCode, CondCode2);
3153 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3154 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3155 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3156 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3157 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3158 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3159 if (CondCode2 != ARMCC::AL) {
3160 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3161 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3162 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3167 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3168 SDValue Chain = Op.getOperand(0);
3169 SDValue Table = Op.getOperand(1);
3170 SDValue Index = Op.getOperand(2);
3171 DebugLoc dl = Op.getDebugLoc();
3173 EVT PTy = getPointerTy();
3174 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3175 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3176 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3177 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3178 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3179 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3180 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3181 if (Subtarget->isThumb2()) {
3182 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3183 // which does another jump to the destination. This also makes it easier
3184 // to translate it to TBB / TBH later.
3185 // FIXME: This might not work if the function is extremely large.
3186 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3187 Addr, Op.getOperand(2), JTI, UId);
3189 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3190 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3191 MachinePointerInfo::getJumpTable(),
3192 false, false, false, 0);
3193 Chain = Addr.getValue(1);
3194 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3195 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3197 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3198 MachinePointerInfo::getJumpTable(),
3199 false, false, false, 0);
3200 Chain = Addr.getValue(1);
3201 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3205 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3206 EVT VT = Op.getValueType();
3207 DebugLoc dl = Op.getDebugLoc();
3209 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3210 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3212 return DAG.UnrollVectorOp(Op.getNode());
3215 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3216 "Invalid type for custom lowering!");
3217 if (VT != MVT::v4i16)
3218 return DAG.UnrollVectorOp(Op.getNode());
3220 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3221 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3224 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3225 EVT VT = Op.getValueType();
3227 return LowerVectorFP_TO_INT(Op, DAG);
3229 DebugLoc dl = Op.getDebugLoc();
3232 switch (Op.getOpcode()) {
3233 default: llvm_unreachable("Invalid opcode!");
3234 case ISD::FP_TO_SINT:
3235 Opc = ARMISD::FTOSI;
3237 case ISD::FP_TO_UINT:
3238 Opc = ARMISD::FTOUI;
3241 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3242 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3245 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3246 EVT VT = Op.getValueType();
3247 DebugLoc dl = Op.getDebugLoc();
3249 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3250 if (VT.getVectorElementType() == MVT::f32)
3252 return DAG.UnrollVectorOp(Op.getNode());
3255 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3256 "Invalid type for custom lowering!");
3257 if (VT != MVT::v4f32)
3258 return DAG.UnrollVectorOp(Op.getNode());
3262 switch (Op.getOpcode()) {
3263 default: llvm_unreachable("Invalid opcode!");
3264 case ISD::SINT_TO_FP:
3265 CastOpc = ISD::SIGN_EXTEND;
3266 Opc = ISD::SINT_TO_FP;
3268 case ISD::UINT_TO_FP:
3269 CastOpc = ISD::ZERO_EXTEND;
3270 Opc = ISD::UINT_TO_FP;
3274 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3275 return DAG.getNode(Opc, dl, VT, Op);
3278 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3279 EVT VT = Op.getValueType();
3281 return LowerVectorINT_TO_FP(Op, DAG);
3283 DebugLoc dl = Op.getDebugLoc();
3286 switch (Op.getOpcode()) {
3287 default: llvm_unreachable("Invalid opcode!");
3288 case ISD::SINT_TO_FP:
3289 Opc = ARMISD::SITOF;
3291 case ISD::UINT_TO_FP:
3292 Opc = ARMISD::UITOF;
3296 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3297 return DAG.getNode(Opc, dl, VT, Op);
3300 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3301 // Implement fcopysign with a fabs and a conditional fneg.
3302 SDValue Tmp0 = Op.getOperand(0);
3303 SDValue Tmp1 = Op.getOperand(1);
3304 DebugLoc dl = Op.getDebugLoc();
3305 EVT VT = Op.getValueType();
3306 EVT SrcVT = Tmp1.getValueType();
3307 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3308 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3309 bool UseNEON = !InGPR && Subtarget->hasNEON();
3312 // Use VBSL to copy the sign bit.
3313 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3314 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3315 DAG.getTargetConstant(EncodedVal, MVT::i32));
3316 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3318 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3319 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3320 DAG.getConstant(32, MVT::i32));
3321 else /*if (VT == MVT::f32)*/
3322 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3323 if (SrcVT == MVT::f32) {
3324 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3326 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3327 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3328 DAG.getConstant(32, MVT::i32));
3329 } else if (VT == MVT::f32)
3330 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3331 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3332 DAG.getConstant(32, MVT::i32));
3333 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3334 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3336 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3338 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3339 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3340 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3342 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3343 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3344 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3345 if (VT == MVT::f32) {
3346 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3347 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3348 DAG.getConstant(0, MVT::i32));
3350 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3356 // Bitcast operand 1 to i32.
3357 if (SrcVT == MVT::f64)
3358 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3359 &Tmp1, 1).getValue(1);
3360 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3362 // Or in the signbit with integer operations.
3363 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3364 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3365 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3366 if (VT == MVT::f32) {
3367 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3368 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3369 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3370 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3373 // f64: Or the high part with signbit and then combine two parts.
3374 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3376 SDValue Lo = Tmp0.getValue(0);
3377 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3378 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3379 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3382 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3383 MachineFunction &MF = DAG.getMachineFunction();
3384 MachineFrameInfo *MFI = MF.getFrameInfo();
3385 MFI->setReturnAddressIsTaken(true);
3387 EVT VT = Op.getValueType();
3388 DebugLoc dl = Op.getDebugLoc();
3389 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3391 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3392 SDValue Offset = DAG.getConstant(4, MVT::i32);
3393 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3394 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3395 MachinePointerInfo(), false, false, false, 0);
3398 // Return LR, which contains the return address. Mark it an implicit live-in.
3399 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3400 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3403 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3404 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3405 MFI->setFrameAddressIsTaken(true);
3407 EVT VT = Op.getValueType();
3408 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3409 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3410 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3411 ? ARM::R7 : ARM::R11;
3412 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3414 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3415 MachinePointerInfo(),
3416 false, false, false, 0);
3420 /// ExpandBITCAST - If the target supports VFP, this function is called to
3421 /// expand a bit convert where either the source or destination type is i64 to
3422 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3423 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3424 /// vectors), since the legalizer won't know what to do with that.
3425 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3426 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3427 DebugLoc dl = N->getDebugLoc();
3428 SDValue Op = N->getOperand(0);
3430 // This function is only supposed to be called for i64 types, either as the
3431 // source or destination of the bit convert.
3432 EVT SrcVT = Op.getValueType();
3433 EVT DstVT = N->getValueType(0);
3434 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3435 "ExpandBITCAST called for non-i64 type");
3437 // Turn i64->f64 into VMOVDRR.
3438 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3439 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3440 DAG.getConstant(0, MVT::i32));
3441 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3442 DAG.getConstant(1, MVT::i32));
3443 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3444 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3447 // Turn f64->i64 into VMOVRRD.
3448 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3449 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3450 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3451 // Merge the pieces into a single i64 value.
3452 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3458 /// getZeroVector - Returns a vector of specified type with all zero elements.
3459 /// Zero vectors are used to represent vector negation and in those cases
3460 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3461 /// not support i64 elements, so sometimes the zero vectors will need to be
3462 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3464 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3465 assert(VT.isVector() && "Expected a vector type");
3466 // The canonical modified immediate encoding of a zero vector is....0!
3467 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3468 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3469 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3470 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3473 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3474 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3475 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3476 SelectionDAG &DAG) const {
3477 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3478 EVT VT = Op.getValueType();
3479 unsigned VTBits = VT.getSizeInBits();
3480 DebugLoc dl = Op.getDebugLoc();
3481 SDValue ShOpLo = Op.getOperand(0);
3482 SDValue ShOpHi = Op.getOperand(1);
3483 SDValue ShAmt = Op.getOperand(2);
3485 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3487 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3489 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3490 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3491 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3492 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3493 DAG.getConstant(VTBits, MVT::i32));
3494 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3495 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3496 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3498 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3499 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3501 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3502 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3505 SDValue Ops[2] = { Lo, Hi };
3506 return DAG.getMergeValues(Ops, 2, dl);
3509 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3510 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3511 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3512 SelectionDAG &DAG) const {
3513 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3514 EVT VT = Op.getValueType();
3515 unsigned VTBits = VT.getSizeInBits();
3516 DebugLoc dl = Op.getDebugLoc();
3517 SDValue ShOpLo = Op.getOperand(0);
3518 SDValue ShOpHi = Op.getOperand(1);
3519 SDValue ShAmt = Op.getOperand(2);
3522 assert(Op.getOpcode() == ISD::SHL_PARTS);
3523 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3524 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3525 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3526 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3527 DAG.getConstant(VTBits, MVT::i32));
3528 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3529 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3531 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3532 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3533 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3535 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3536 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3539 SDValue Ops[2] = { Lo, Hi };
3540 return DAG.getMergeValues(Ops, 2, dl);
3543 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3544 SelectionDAG &DAG) const {
3545 // The rounding mode is in bits 23:22 of the FPSCR.
3546 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3547 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3548 // so that the shift + and get folded into a bitfield extract.
3549 DebugLoc dl = Op.getDebugLoc();
3550 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3551 DAG.getConstant(Intrinsic::arm_get_fpscr,
3553 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3554 DAG.getConstant(1U << 22, MVT::i32));
3555 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3556 DAG.getConstant(22, MVT::i32));
3557 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3558 DAG.getConstant(3, MVT::i32));
3561 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3562 const ARMSubtarget *ST) {
3563 EVT VT = N->getValueType(0);
3564 DebugLoc dl = N->getDebugLoc();
3566 if (!ST->hasV6T2Ops())
3569 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3570 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3573 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3574 /// for each 16-bit element from operand, repeated. The basic idea is to
3575 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3577 /// Trace for v4i16:
3578 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3579 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3580 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3581 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3582 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3583 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3584 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3585 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3586 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3587 EVT VT = N->getValueType(0);
3588 DebugLoc DL = N->getDebugLoc();
3590 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3591 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3592 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3593 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3594 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3595 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3598 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3599 /// bit-count for each 16-bit element from the operand. We need slightly
3600 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3601 /// 64/128-bit registers.
3603 /// Trace for v4i16:
3604 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3605 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3606 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3607 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3608 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3609 EVT VT = N->getValueType(0);
3610 DebugLoc DL = N->getDebugLoc();
3612 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3613 if (VT.is64BitVector()) {
3614 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3615 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3616 DAG.getIntPtrConstant(0));
3618 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3619 BitCounts, DAG.getIntPtrConstant(0));
3620 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3624 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3625 /// bit-count for each 32-bit element from the operand. The idea here is
3626 /// to split the vector into 16-bit elements, leverage the 16-bit count
3627 /// routine, and then combine the results.
3629 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3630 /// input = [v0 v1 ] (vi: 32-bit elements)
3631 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3632 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3633 /// vrev: N0 = [k1 k0 k3 k2 ]
3635 /// N1 =+[k1 k0 k3 k2 ]
3637 /// N2 =+[k1 k3 k0 k2 ]
3639 /// Extended =+[k1 k3 k0 k2 ]
3641 /// Extracted=+[k1 k3 ]
3643 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3644 EVT VT = N->getValueType(0);
3645 DebugLoc DL = N->getDebugLoc();
3647 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3649 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3650 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3651 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3652 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3653 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3655 if (VT.is64BitVector()) {
3656 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3657 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3658 DAG.getIntPtrConstant(0));
3660 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3661 DAG.getIntPtrConstant(0));
3662 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3666 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3667 const ARMSubtarget *ST) {
3668 EVT VT = N->getValueType(0);
3670 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3671 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3672 VT == MVT::v4i16 || VT == MVT::v8i16) &&
3673 "Unexpected type for custom ctpop lowering");
3675 if (VT.getVectorElementType() == MVT::i32)
3676 return lowerCTPOP32BitElements(N, DAG);
3678 return lowerCTPOP16BitElements(N, DAG);
3681 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3682 const ARMSubtarget *ST) {
3683 EVT VT = N->getValueType(0);
3684 DebugLoc dl = N->getDebugLoc();
3689 // Lower vector shifts on NEON to use VSHL.
3690 assert(ST->hasNEON() && "unexpected vector shift");
3692 // Left shifts translate directly to the vshiftu intrinsic.
3693 if (N->getOpcode() == ISD::SHL)
3694 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3695 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3696 N->getOperand(0), N->getOperand(1));
3698 assert((N->getOpcode() == ISD::SRA ||
3699 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3701 // NEON uses the same intrinsics for both left and right shifts. For
3702 // right shifts, the shift amounts are negative, so negate the vector of
3704 EVT ShiftVT = N->getOperand(1).getValueType();
3705 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3706 getZeroVector(ShiftVT, DAG, dl),
3708 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3709 Intrinsic::arm_neon_vshifts :
3710 Intrinsic::arm_neon_vshiftu);
3711 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3712 DAG.getConstant(vshiftInt, MVT::i32),
3713 N->getOperand(0), NegatedCount);
3716 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3717 const ARMSubtarget *ST) {
3718 EVT VT = N->getValueType(0);
3719 DebugLoc dl = N->getDebugLoc();
3721 // We can get here for a node like i32 = ISD::SHL i32, i64
3725 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3726 "Unknown shift to lower!");
3728 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3729 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3730 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3733 // If we are in thumb mode, we don't have RRX.
3734 if (ST->isThumb1Only()) return SDValue();
3736 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3737 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3738 DAG.getConstant(0, MVT::i32));
3739 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3740 DAG.getConstant(1, MVT::i32));
3742 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3743 // captures the result into a carry flag.
3744 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3745 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3747 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3748 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3750 // Merge the pieces into a single i64 value.
3751 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3754 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3755 SDValue TmpOp0, TmpOp1;
3756 bool Invert = false;
3760 SDValue Op0 = Op.getOperand(0);
3761 SDValue Op1 = Op.getOperand(1);
3762 SDValue CC = Op.getOperand(2);
3763 EVT VT = Op.getValueType();
3764 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3765 DebugLoc dl = Op.getDebugLoc();
3767 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3768 switch (SetCCOpcode) {
3769 default: llvm_unreachable("Illegal FP comparison");
3771 case ISD::SETNE: Invert = true; // Fallthrough
3773 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3775 case ISD::SETLT: Swap = true; // Fallthrough
3777 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3779 case ISD::SETLE: Swap = true; // Fallthrough
3781 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3782 case ISD::SETUGE: Swap = true; // Fallthrough
3783 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3784 case ISD::SETUGT: Swap = true; // Fallthrough
3785 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3786 case ISD::SETUEQ: Invert = true; // Fallthrough
3788 // Expand this to (OLT | OGT).
3792 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3793 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3795 case ISD::SETUO: Invert = true; // Fallthrough
3797 // Expand this to (OLT | OGE).
3801 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3802 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3806 // Integer comparisons.
3807 switch (SetCCOpcode) {
3808 default: llvm_unreachable("Illegal integer comparison");
3809 case ISD::SETNE: Invert = true;
3810 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3811 case ISD::SETLT: Swap = true;
3812 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3813 case ISD::SETLE: Swap = true;
3814 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3815 case ISD::SETULT: Swap = true;
3816 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3817 case ISD::SETULE: Swap = true;
3818 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3821 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3822 if (Opc == ARMISD::VCEQ) {
3825 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3827 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3830 // Ignore bitconvert.
3831 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3832 AndOp = AndOp.getOperand(0);
3834 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3836 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3837 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3844 std::swap(Op0, Op1);
3846 // If one of the operands is a constant vector zero, attempt to fold the
3847 // comparison to a specialized compare-against-zero form.
3849 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3851 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3852 if (Opc == ARMISD::VCGE)
3853 Opc = ARMISD::VCLEZ;
3854 else if (Opc == ARMISD::VCGT)
3855 Opc = ARMISD::VCLTZ;
3860 if (SingleOp.getNode()) {
3863 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3865 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3867 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3869 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3871 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3873 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3876 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3880 Result = DAG.getNOT(dl, Result, VT);
3885 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3886 /// valid vector constant for a NEON instruction with a "modified immediate"
3887 /// operand (e.g., VMOV). If so, return the encoded value.
3888 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3889 unsigned SplatBitSize, SelectionDAG &DAG,
3890 EVT &VT, bool is128Bits, NEONModImmType type) {
3891 unsigned OpCmode, Imm;
3893 // SplatBitSize is set to the smallest size that splats the vector, so a
3894 // zero vector will always have SplatBitSize == 8. However, NEON modified
3895 // immediate instructions others than VMOV do not support the 8-bit encoding
3896 // of a zero vector, and the default encoding of zero is supposed to be the
3901 switch (SplatBitSize) {
3903 if (type != VMOVModImm)
3905 // Any 1-byte value is OK. Op=0, Cmode=1110.
3906 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3909 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3913 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3914 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3915 if ((SplatBits & ~0xff) == 0) {
3916 // Value = 0x00nn: Op=x, Cmode=100x.
3921 if ((SplatBits & ~0xff00) == 0) {
3922 // Value = 0xnn00: Op=x, Cmode=101x.
3924 Imm = SplatBits >> 8;
3930 // NEON's 32-bit VMOV supports splat values where:
3931 // * only one byte is nonzero, or
3932 // * the least significant byte is 0xff and the second byte is nonzero, or
3933 // * the least significant 2 bytes are 0xff and the third is nonzero.
3934 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3935 if ((SplatBits & ~0xff) == 0) {
3936 // Value = 0x000000nn: Op=x, Cmode=000x.
3941 if ((SplatBits & ~0xff00) == 0) {
3942 // Value = 0x0000nn00: Op=x, Cmode=001x.
3944 Imm = SplatBits >> 8;
3947 if ((SplatBits & ~0xff0000) == 0) {
3948 // Value = 0x00nn0000: Op=x, Cmode=010x.
3950 Imm = SplatBits >> 16;
3953 if ((SplatBits & ~0xff000000) == 0) {
3954 // Value = 0xnn000000: Op=x, Cmode=011x.
3956 Imm = SplatBits >> 24;
3960 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3961 if (type == OtherModImm) return SDValue();
3963 if ((SplatBits & ~0xffff) == 0 &&
3964 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3965 // Value = 0x0000nnff: Op=x, Cmode=1100.
3967 Imm = SplatBits >> 8;
3972 if ((SplatBits & ~0xffffff) == 0 &&
3973 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3974 // Value = 0x00nnffff: Op=x, Cmode=1101.
3976 Imm = SplatBits >> 16;
3977 SplatBits |= 0xffff;
3981 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3982 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3983 // VMOV.I32. A (very) minor optimization would be to replicate the value
3984 // and fall through here to test for a valid 64-bit splat. But, then the
3985 // caller would also need to check and handle the change in size.
3989 if (type != VMOVModImm)
3991 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3992 uint64_t BitMask = 0xff;
3994 unsigned ImmMask = 1;
3996 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3997 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4000 } else if ((SplatBits & BitMask) != 0) {
4006 // Op=1, Cmode=1110.
4009 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4014 llvm_unreachable("unexpected size for isNEONModifiedImm");
4017 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4018 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4021 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4022 const ARMSubtarget *ST) const {
4023 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4026 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4027 assert(Op.getValueType() == MVT::f32 &&
4028 "ConstantFP custom lowering should only occur for f32.");
4030 // Try splatting with a VMOV.f32...
4031 APFloat FPVal = CFP->getValueAPF();
4032 int ImmVal = ARM_AM::getFP32Imm(FPVal);
4034 DebugLoc DL = Op.getDebugLoc();
4035 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4036 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4038 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4039 DAG.getConstant(0, MVT::i32));
4042 // If that fails, try a VMOV.i32
4044 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4045 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4047 if (NewVal != SDValue()) {
4048 DebugLoc DL = Op.getDebugLoc();
4049 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4051 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4053 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4054 DAG.getConstant(0, MVT::i32));
4057 // Finally, try a VMVN.i32
4058 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4060 if (NewVal != SDValue()) {
4061 DebugLoc DL = Op.getDebugLoc();
4062 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4063 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4065 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4066 DAG.getConstant(0, MVT::i32));
4072 // check if an VEXT instruction can handle the shuffle mask when the
4073 // vector sources of the shuffle are the same.
4074 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4075 unsigned NumElts = VT.getVectorNumElements();
4077 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4083 // If this is a VEXT shuffle, the immediate value is the index of the first
4084 // element. The other shuffle indices must be the successive elements after
4086 unsigned ExpectedElt = Imm;
4087 for (unsigned i = 1; i < NumElts; ++i) {
4088 // Increment the expected index. If it wraps around, just follow it
4089 // back to index zero and keep going.
4091 if (ExpectedElt == NumElts)
4094 if (M[i] < 0) continue; // ignore UNDEF indices
4095 if (ExpectedElt != static_cast<unsigned>(M[i]))
4103 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4104 bool &ReverseVEXT, unsigned &Imm) {
4105 unsigned NumElts = VT.getVectorNumElements();
4106 ReverseVEXT = false;
4108 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4114 // If this is a VEXT shuffle, the immediate value is the index of the first
4115 // element. The other shuffle indices must be the successive elements after
4117 unsigned ExpectedElt = Imm;
4118 for (unsigned i = 1; i < NumElts; ++i) {
4119 // Increment the expected index. If it wraps around, it may still be
4120 // a VEXT but the source vectors must be swapped.
4122 if (ExpectedElt == NumElts * 2) {
4127 if (M[i] < 0) continue; // ignore UNDEF indices
4128 if (ExpectedElt != static_cast<unsigned>(M[i]))
4132 // Adjust the index value if the source operands will be swapped.
4139 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4140 /// instruction with the specified blocksize. (The order of the elements
4141 /// within each block of the vector is reversed.)
4142 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4143 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4144 "Only possible block sizes for VREV are: 16, 32, 64");
4146 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4150 unsigned NumElts = VT.getVectorNumElements();
4151 unsigned BlockElts = M[0] + 1;
4152 // If the first shuffle index is UNDEF, be optimistic.
4154 BlockElts = BlockSize / EltSz;
4156 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4159 for (unsigned i = 0; i < NumElts; ++i) {
4160 if (M[i] < 0) continue; // ignore UNDEF indices
4161 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4168 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4169 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4170 // range, then 0 is placed into the resulting vector. So pretty much any mask
4171 // of 8 elements can work here.
4172 return VT == MVT::v8i8 && M.size() == 8;
4175 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4176 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4180 unsigned NumElts = VT.getVectorNumElements();
4181 WhichResult = (M[0] == 0 ? 0 : 1);
4182 for (unsigned i = 0; i < NumElts; i += 2) {
4183 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4184 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4190 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4191 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4192 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4193 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4194 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4198 unsigned NumElts = VT.getVectorNumElements();
4199 WhichResult = (M[0] == 0 ? 0 : 1);
4200 for (unsigned i = 0; i < NumElts; i += 2) {
4201 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4202 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4208 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4209 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4213 unsigned NumElts = VT.getVectorNumElements();
4214 WhichResult = (M[0] == 0 ? 0 : 1);
4215 for (unsigned i = 0; i != NumElts; ++i) {
4216 if (M[i] < 0) continue; // ignore UNDEF indices
4217 if ((unsigned) M[i] != 2 * i + WhichResult)
4221 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4222 if (VT.is64BitVector() && EltSz == 32)
4228 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4229 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4230 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4231 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4232 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4236 unsigned Half = VT.getVectorNumElements() / 2;
4237 WhichResult = (M[0] == 0 ? 0 : 1);
4238 for (unsigned j = 0; j != 2; ++j) {
4239 unsigned Idx = WhichResult;
4240 for (unsigned i = 0; i != Half; ++i) {
4241 int MIdx = M[i + j * Half];
4242 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4248 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4249 if (VT.is64BitVector() && EltSz == 32)
4255 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4256 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4260 unsigned NumElts = VT.getVectorNumElements();
4261 WhichResult = (M[0] == 0 ? 0 : 1);
4262 unsigned Idx = WhichResult * NumElts / 2;
4263 for (unsigned i = 0; i != NumElts; i += 2) {
4264 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4265 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4270 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4271 if (VT.is64BitVector() && EltSz == 32)
4277 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4278 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4279 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4280 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4281 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4285 unsigned NumElts = VT.getVectorNumElements();
4286 WhichResult = (M[0] == 0 ? 0 : 1);
4287 unsigned Idx = WhichResult * NumElts / 2;
4288 for (unsigned i = 0; i != NumElts; i += 2) {
4289 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4290 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4295 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4296 if (VT.is64BitVector() && EltSz == 32)
4302 /// \return true if this is a reverse operation on an vector.
4303 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4304 unsigned NumElts = VT.getVectorNumElements();
4305 // Make sure the mask has the right size.
4306 if (NumElts != M.size())
4309 // Look for <15, ..., 3, -1, 1, 0>.
4310 for (unsigned i = 0; i != NumElts; ++i)
4311 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4317 // If N is an integer constant that can be moved into a register in one
4318 // instruction, return an SDValue of such a constant (will become a MOV
4319 // instruction). Otherwise return null.
4320 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4321 const ARMSubtarget *ST, DebugLoc dl) {
4323 if (!isa<ConstantSDNode>(N))
4325 Val = cast<ConstantSDNode>(N)->getZExtValue();
4327 if (ST->isThumb1Only()) {
4328 if (Val <= 255 || ~Val <= 255)
4329 return DAG.getConstant(Val, MVT::i32);
4331 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4332 return DAG.getConstant(Val, MVT::i32);
4337 // If this is a case we can't handle, return null and let the default
4338 // expansion code take care of it.
4339 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4340 const ARMSubtarget *ST) const {
4341 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4342 DebugLoc dl = Op.getDebugLoc();
4343 EVT VT = Op.getValueType();
4345 APInt SplatBits, SplatUndef;
4346 unsigned SplatBitSize;
4348 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4349 if (SplatBitSize <= 64) {
4350 // Check if an immediate VMOV works.
4352 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4353 SplatUndef.getZExtValue(), SplatBitSize,
4354 DAG, VmovVT, VT.is128BitVector(),
4356 if (Val.getNode()) {
4357 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4358 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4361 // Try an immediate VMVN.
4362 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4363 Val = isNEONModifiedImm(NegatedImm,
4364 SplatUndef.getZExtValue(), SplatBitSize,
4365 DAG, VmovVT, VT.is128BitVector(),
4367 if (Val.getNode()) {
4368 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4369 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4372 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4373 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4374 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4376 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4377 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4383 // Scan through the operands to see if only one value is used.
4385 // As an optimisation, even if more than one value is used it may be more
4386 // profitable to splat with one value then change some lanes.
4388 // Heuristically we decide to do this if the vector has a "dominant" value,
4389 // defined as splatted to more than half of the lanes.
4390 unsigned NumElts = VT.getVectorNumElements();
4391 bool isOnlyLowElement = true;
4392 bool usesOnlyOneValue = true;
4393 bool hasDominantValue = false;
4394 bool isConstant = true;
4396 // Map of the number of times a particular SDValue appears in the
4398 DenseMap<SDValue, unsigned> ValueCounts;
4400 for (unsigned i = 0; i < NumElts; ++i) {
4401 SDValue V = Op.getOperand(i);
4402 if (V.getOpcode() == ISD::UNDEF)
4405 isOnlyLowElement = false;
4406 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4409 ValueCounts.insert(std::make_pair(V, 0));
4410 unsigned &Count = ValueCounts[V];
4412 // Is this value dominant? (takes up more than half of the lanes)
4413 if (++Count > (NumElts / 2)) {
4414 hasDominantValue = true;
4418 if (ValueCounts.size() != 1)
4419 usesOnlyOneValue = false;
4420 if (!Value.getNode() && ValueCounts.size() > 0)
4421 Value = ValueCounts.begin()->first;
4423 if (ValueCounts.size() == 0)
4424 return DAG.getUNDEF(VT);
4426 if (isOnlyLowElement)
4427 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4429 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4431 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4432 // i32 and try again.
4433 if (hasDominantValue && EltSize <= 32) {
4437 // If we are VDUPing a value that comes directly from a vector, that will
4438 // cause an unnecessary move to and from a GPR, where instead we could
4439 // just use VDUPLANE.
4440 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4441 // We need to create a new undef vector to use for the VDUPLANE if the
4442 // size of the vector from which we get the value is different than the
4443 // size of the vector that we need to create. We will insert the element
4444 // such that the register coalescer will remove unnecessary copies.
4445 if (VT != Value->getOperand(0).getValueType()) {
4446 ConstantSDNode *constIndex;
4447 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4448 assert(constIndex && "The index is not a constant!");
4449 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4450 VT.getVectorNumElements();
4451 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4452 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4453 Value, DAG.getConstant(index, MVT::i32)),
4454 DAG.getConstant(index, MVT::i32));
4456 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4457 Value->getOperand(0), Value->getOperand(1));
4461 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4463 if (!usesOnlyOneValue) {
4464 // The dominant value was splatted as 'N', but we now have to insert
4465 // all differing elements.
4466 for (unsigned I = 0; I < NumElts; ++I) {
4467 if (Op.getOperand(I) == Value)
4469 SmallVector<SDValue, 3> Ops;
4471 Ops.push_back(Op.getOperand(I));
4472 Ops.push_back(DAG.getConstant(I, MVT::i32));
4473 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4478 if (VT.getVectorElementType().isFloatingPoint()) {
4479 SmallVector<SDValue, 8> Ops;
4480 for (unsigned i = 0; i < NumElts; ++i)
4481 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4483 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4484 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4485 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4487 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4489 if (usesOnlyOneValue) {
4490 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4491 if (isConstant && Val.getNode())
4492 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4496 // If all elements are constants and the case above didn't get hit, fall back
4497 // to the default expansion, which will generate a load from the constant
4502 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4504 SDValue shuffle = ReconstructShuffle(Op, DAG);
4505 if (shuffle != SDValue())
4509 // Vectors with 32- or 64-bit elements can be built by directly assigning
4510 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4511 // will be legalized.
4512 if (EltSize >= 32) {
4513 // Do the expansion with floating-point types, since that is what the VFP
4514 // registers are defined to use, and since i64 is not legal.
4515 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4516 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4517 SmallVector<SDValue, 8> Ops;
4518 for (unsigned i = 0; i < NumElts; ++i)
4519 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4520 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4521 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4527 // Gather data to see if the operation can be modelled as a
4528 // shuffle in combination with VEXTs.
4529 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4530 SelectionDAG &DAG) const {
4531 DebugLoc dl = Op.getDebugLoc();
4532 EVT VT = Op.getValueType();
4533 unsigned NumElts = VT.getVectorNumElements();
4535 SmallVector<SDValue, 2> SourceVecs;
4536 SmallVector<unsigned, 2> MinElts;
4537 SmallVector<unsigned, 2> MaxElts;
4539 for (unsigned i = 0; i < NumElts; ++i) {
4540 SDValue V = Op.getOperand(i);
4541 if (V.getOpcode() == ISD::UNDEF)
4543 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4544 // A shuffle can only come from building a vector from various
4545 // elements of other vectors.
4547 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4548 VT.getVectorElementType()) {
4549 // This code doesn't know how to handle shuffles where the vector
4550 // element types do not match (this happens because type legalization
4551 // promotes the return type of EXTRACT_VECTOR_ELT).
4552 // FIXME: It might be appropriate to extend this code to handle
4553 // mismatched types.
4557 // Record this extraction against the appropriate vector if possible...
4558 SDValue SourceVec = V.getOperand(0);
4559 // If the element number isn't a constant, we can't effectively
4560 // analyze what's going on.
4561 if (!isa<ConstantSDNode>(V.getOperand(1)))
4563 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4564 bool FoundSource = false;
4565 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4566 if (SourceVecs[j] == SourceVec) {
4567 if (MinElts[j] > EltNo)
4569 if (MaxElts[j] < EltNo)
4576 // Or record a new source if not...
4578 SourceVecs.push_back(SourceVec);
4579 MinElts.push_back(EltNo);
4580 MaxElts.push_back(EltNo);
4584 // Currently only do something sane when at most two source vectors
4586 if (SourceVecs.size() > 2)
4589 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4590 int VEXTOffsets[2] = {0, 0};
4592 // This loop extracts the usage patterns of the source vectors
4593 // and prepares appropriate SDValues for a shuffle if possible.
4594 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4595 if (SourceVecs[i].getValueType() == VT) {
4596 // No VEXT necessary
4597 ShuffleSrcs[i] = SourceVecs[i];
4600 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4601 // It probably isn't worth padding out a smaller vector just to
4602 // break it down again in a shuffle.
4606 // Since only 64-bit and 128-bit vectors are legal on ARM and
4607 // we've eliminated the other cases...
4608 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4609 "unexpected vector sizes in ReconstructShuffle");
4611 if (MaxElts[i] - MinElts[i] >= NumElts) {
4612 // Span too large for a VEXT to cope
4616 if (MinElts[i] >= NumElts) {
4617 // The extraction can just take the second half
4618 VEXTOffsets[i] = NumElts;
4619 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4621 DAG.getIntPtrConstant(NumElts));
4622 } else if (MaxElts[i] < NumElts) {
4623 // The extraction can just take the first half
4625 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4627 DAG.getIntPtrConstant(0));
4629 // An actual VEXT is needed
4630 VEXTOffsets[i] = MinElts[i];
4631 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4633 DAG.getIntPtrConstant(0));
4634 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4636 DAG.getIntPtrConstant(NumElts));
4637 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4638 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4642 SmallVector<int, 8> Mask;
4644 for (unsigned i = 0; i < NumElts; ++i) {
4645 SDValue Entry = Op.getOperand(i);
4646 if (Entry.getOpcode() == ISD::UNDEF) {
4651 SDValue ExtractVec = Entry.getOperand(0);
4652 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4653 .getOperand(1))->getSExtValue();
4654 if (ExtractVec == SourceVecs[0]) {
4655 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4657 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4661 // Final check before we try to produce nonsense...
4662 if (isShuffleMaskLegal(Mask, VT))
4663 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4669 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4670 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4671 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4672 /// are assumed to be legal.
4674 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4676 if (VT.getVectorNumElements() == 4 &&
4677 (VT.is128BitVector() || VT.is64BitVector())) {
4678 unsigned PFIndexes[4];
4679 for (unsigned i = 0; i != 4; ++i) {
4683 PFIndexes[i] = M[i];
4686 // Compute the index in the perfect shuffle table.
4687 unsigned PFTableIndex =
4688 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4689 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4690 unsigned Cost = (PFEntry >> 30);
4697 unsigned Imm, WhichResult;
4699 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4700 return (EltSize >= 32 ||
4701 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4702 isVREVMask(M, VT, 64) ||
4703 isVREVMask(M, VT, 32) ||
4704 isVREVMask(M, VT, 16) ||
4705 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4706 isVTBLMask(M, VT) ||
4707 isVTRNMask(M, VT, WhichResult) ||
4708 isVUZPMask(M, VT, WhichResult) ||
4709 isVZIPMask(M, VT, WhichResult) ||
4710 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4711 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4712 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4713 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4716 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4717 /// the specified operations to build the shuffle.
4718 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4719 SDValue RHS, SelectionDAG &DAG,
4721 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4722 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4723 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4726 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4735 OP_VUZPL, // VUZP, left result
4736 OP_VUZPR, // VUZP, right result
4737 OP_VZIPL, // VZIP, left result
4738 OP_VZIPR, // VZIP, right result
4739 OP_VTRNL, // VTRN, left result
4740 OP_VTRNR // VTRN, right result
4743 if (OpNum == OP_COPY) {
4744 if (LHSID == (1*9+2)*9+3) return LHS;
4745 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4749 SDValue OpLHS, OpRHS;
4750 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4751 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4752 EVT VT = OpLHS.getValueType();
4755 default: llvm_unreachable("Unknown shuffle opcode!");
4757 // VREV divides the vector in half and swaps within the half.
4758 if (VT.getVectorElementType() == MVT::i32 ||
4759 VT.getVectorElementType() == MVT::f32)
4760 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4761 // vrev <4 x i16> -> VREV32
4762 if (VT.getVectorElementType() == MVT::i16)
4763 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4764 // vrev <4 x i8> -> VREV16
4765 assert(VT.getVectorElementType() == MVT::i8);
4766 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4771 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4772 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4776 return DAG.getNode(ARMISD::VEXT, dl, VT,
4778 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4781 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4782 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4785 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4786 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4789 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4790 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4794 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4795 ArrayRef<int> ShuffleMask,
4796 SelectionDAG &DAG) {
4797 // Check to see if we can use the VTBL instruction.
4798 SDValue V1 = Op.getOperand(0);
4799 SDValue V2 = Op.getOperand(1);
4800 DebugLoc DL = Op.getDebugLoc();
4802 SmallVector<SDValue, 8> VTBLMask;
4803 for (ArrayRef<int>::iterator
4804 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4805 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4807 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4808 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4809 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4812 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4813 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4817 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
4818 SelectionDAG &DAG) {
4819 DebugLoc DL = Op.getDebugLoc();
4820 SDValue OpLHS = Op.getOperand(0);
4821 EVT VT = OpLHS.getValueType();
4823 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
4824 "Expect an v8i16/v16i8 type");
4825 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
4826 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
4827 // extract the first 8 bytes into the top double word and the last 8 bytes
4828 // into the bottom double word. The v8i16 case is similar.
4829 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
4830 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
4831 DAG.getConstant(ExtractNum, MVT::i32));
4834 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4835 SDValue V1 = Op.getOperand(0);
4836 SDValue V2 = Op.getOperand(1);
4837 DebugLoc dl = Op.getDebugLoc();
4838 EVT VT = Op.getValueType();
4839 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4841 // Convert shuffles that are directly supported on NEON to target-specific
4842 // DAG nodes, instead of keeping them as shuffles and matching them again
4843 // during code selection. This is more efficient and avoids the possibility
4844 // of inconsistencies between legalization and selection.
4845 // FIXME: floating-point vectors should be canonicalized to integer vectors
4846 // of the same time so that they get CSEd properly.
4847 ArrayRef<int> ShuffleMask = SVN->getMask();
4849 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4850 if (EltSize <= 32) {
4851 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4852 int Lane = SVN->getSplatIndex();
4853 // If this is undef splat, generate it via "just" vdup, if possible.
4854 if (Lane == -1) Lane = 0;
4856 // Test if V1 is a SCALAR_TO_VECTOR.
4857 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4858 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4860 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4861 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4863 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4864 !isa<ConstantSDNode>(V1.getOperand(0))) {
4865 bool IsScalarToVector = true;
4866 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4867 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4868 IsScalarToVector = false;
4871 if (IsScalarToVector)
4872 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4874 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4875 DAG.getConstant(Lane, MVT::i32));
4880 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4883 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4884 DAG.getConstant(Imm, MVT::i32));
4887 if (isVREVMask(ShuffleMask, VT, 64))
4888 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4889 if (isVREVMask(ShuffleMask, VT, 32))
4890 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4891 if (isVREVMask(ShuffleMask, VT, 16))
4892 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4894 if (V2->getOpcode() == ISD::UNDEF &&
4895 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4896 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4897 DAG.getConstant(Imm, MVT::i32));
4900 // Check for Neon shuffles that modify both input vectors in place.
4901 // If both results are used, i.e., if there are two shuffles with the same
4902 // source operands and with masks corresponding to both results of one of
4903 // these operations, DAG memoization will ensure that a single node is
4904 // used for both shuffles.
4905 unsigned WhichResult;
4906 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4907 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4908 V1, V2).getValue(WhichResult);
4909 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4910 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4911 V1, V2).getValue(WhichResult);
4912 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4913 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4914 V1, V2).getValue(WhichResult);
4916 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4917 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4918 V1, V1).getValue(WhichResult);
4919 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4920 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4921 V1, V1).getValue(WhichResult);
4922 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4923 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4924 V1, V1).getValue(WhichResult);
4927 // If the shuffle is not directly supported and it has 4 elements, use
4928 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4929 unsigned NumElts = VT.getVectorNumElements();
4931 unsigned PFIndexes[4];
4932 for (unsigned i = 0; i != 4; ++i) {
4933 if (ShuffleMask[i] < 0)
4936 PFIndexes[i] = ShuffleMask[i];
4939 // Compute the index in the perfect shuffle table.
4940 unsigned PFTableIndex =
4941 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4942 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4943 unsigned Cost = (PFEntry >> 30);
4946 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4949 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4950 if (EltSize >= 32) {
4951 // Do the expansion with floating-point types, since that is what the VFP
4952 // registers are defined to use, and since i64 is not legal.
4953 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4954 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4955 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4956 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4957 SmallVector<SDValue, 8> Ops;
4958 for (unsigned i = 0; i < NumElts; ++i) {
4959 if (ShuffleMask[i] < 0)
4960 Ops.push_back(DAG.getUNDEF(EltVT));
4962 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4963 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4964 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4967 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4968 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4971 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
4972 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
4974 if (VT == MVT::v8i8) {
4975 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4976 if (NewOp.getNode())
4983 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4984 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4985 SDValue Lane = Op.getOperand(2);
4986 if (!isa<ConstantSDNode>(Lane))
4992 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4993 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4994 SDValue Lane = Op.getOperand(1);
4995 if (!isa<ConstantSDNode>(Lane))
4998 SDValue Vec = Op.getOperand(0);
4999 if (Op.getValueType() == MVT::i32 &&
5000 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5001 DebugLoc dl = Op.getDebugLoc();
5002 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5008 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5009 // The only time a CONCAT_VECTORS operation can have legal types is when
5010 // two 64-bit vectors are concatenated to a 128-bit vector.
5011 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5012 "unexpected CONCAT_VECTORS");
5013 DebugLoc dl = Op.getDebugLoc();
5014 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5015 SDValue Op0 = Op.getOperand(0);
5016 SDValue Op1 = Op.getOperand(1);
5017 if (Op0.getOpcode() != ISD::UNDEF)
5018 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5019 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5020 DAG.getIntPtrConstant(0));
5021 if (Op1.getOpcode() != ISD::UNDEF)
5022 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5023 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5024 DAG.getIntPtrConstant(1));
5025 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5028 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5029 /// element has been zero/sign-extended, depending on the isSigned parameter,
5030 /// from an integer type half its size.
5031 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5033 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5034 EVT VT = N->getValueType(0);
5035 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5036 SDNode *BVN = N->getOperand(0).getNode();
5037 if (BVN->getValueType(0) != MVT::v4i32 ||
5038 BVN->getOpcode() != ISD::BUILD_VECTOR)
5040 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5041 unsigned HiElt = 1 - LoElt;
5042 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5043 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5044 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5045 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5046 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5049 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5050 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5053 if (Hi0->isNullValue() && Hi1->isNullValue())
5059 if (N->getOpcode() != ISD::BUILD_VECTOR)
5062 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5063 SDNode *Elt = N->getOperand(i).getNode();
5064 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5065 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5066 unsigned HalfSize = EltSize / 2;
5068 if (!isIntN(HalfSize, C->getSExtValue()))
5071 if (!isUIntN(HalfSize, C->getZExtValue()))
5082 /// isSignExtended - Check if a node is a vector value that is sign-extended
5083 /// or a constant BUILD_VECTOR with sign-extended elements.
5084 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5085 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5087 if (isExtendedBUILD_VECTOR(N, DAG, true))
5092 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5093 /// or a constant BUILD_VECTOR with zero-extended elements.
5094 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5095 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5097 if (isExtendedBUILD_VECTOR(N, DAG, false))
5102 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5103 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5104 /// We insert the required extension here to get the vector to fill a D register.
5105 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5108 unsigned ExtOpcode) {
5109 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5110 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5111 // 64-bits we need to insert a new extension so that it will be 64-bits.
5112 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5113 if (OrigTy.getSizeInBits() >= 64)
5116 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5117 MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5119 switch (OrigSimpleTy) {
5120 default: llvm_unreachable("Unexpected Orig Vector Type");
5129 return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5132 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5133 /// does not do any sign/zero extension. If the original vector is less
5134 /// than 64 bits, an appropriate extension will be added after the load to
5135 /// reach a total size of 64 bits. We have to add the extension separately
5136 /// because ARM does not have a sign/zero extending load for vectors.
5137 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5138 SDValue NonExtendingLoad =
5139 DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5140 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5141 LD->isNonTemporal(), LD->isInvariant(),
5142 LD->getAlignment());
5144 switch (LD->getExtensionType()) {
5145 default: llvm_unreachable("Unexpected LoadExtType");
5147 case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5148 case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5150 MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5151 MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5152 return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5153 MemType, ExtType, ExtOp);
5156 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5157 /// extending load, or BUILD_VECTOR with extended elements, return the
5158 /// unextended value. The unextended vector should be 64 bits so that it can
5159 /// be used as an operand to a VMULL instruction. If the original vector size
5160 /// before extension is less than 64 bits we add a an extension to resize
5161 /// the vector to 64 bits.
5162 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5163 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5164 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5165 N->getOperand(0)->getValueType(0),
5169 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5170 return SkipLoadExtensionForVMULL(LD, DAG);
5172 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5173 // have been legalized as a BITCAST from v4i32.
5174 if (N->getOpcode() == ISD::BITCAST) {
5175 SDNode *BVN = N->getOperand(0).getNode();
5176 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5177 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5178 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5179 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5180 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5182 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5183 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5184 EVT VT = N->getValueType(0);
5185 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5186 unsigned NumElts = VT.getVectorNumElements();
5187 MVT TruncVT = MVT::getIntegerVT(EltSize);
5188 SmallVector<SDValue, 8> Ops;
5189 for (unsigned i = 0; i != NumElts; ++i) {
5190 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5191 const APInt &CInt = C->getAPIntValue();
5192 // Element types smaller than 32 bits are not legal, so use i32 elements.
5193 // The values are implicitly truncated so sext vs. zext doesn't matter.
5194 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5196 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5197 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5200 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5201 unsigned Opcode = N->getOpcode();
5202 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5203 SDNode *N0 = N->getOperand(0).getNode();
5204 SDNode *N1 = N->getOperand(1).getNode();
5205 return N0->hasOneUse() && N1->hasOneUse() &&
5206 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5211 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5212 unsigned Opcode = N->getOpcode();
5213 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5214 SDNode *N0 = N->getOperand(0).getNode();
5215 SDNode *N1 = N->getOperand(1).getNode();
5216 return N0->hasOneUse() && N1->hasOneUse() &&
5217 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5222 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5223 // Multiplications are only custom-lowered for 128-bit vectors so that
5224 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5225 EVT VT = Op.getValueType();
5226 assert(VT.is128BitVector() && VT.isInteger() &&
5227 "unexpected type for custom-lowering ISD::MUL");
5228 SDNode *N0 = Op.getOperand(0).getNode();
5229 SDNode *N1 = Op.getOperand(1).getNode();
5230 unsigned NewOpc = 0;
5232 bool isN0SExt = isSignExtended(N0, DAG);
5233 bool isN1SExt = isSignExtended(N1, DAG);
5234 if (isN0SExt && isN1SExt)
5235 NewOpc = ARMISD::VMULLs;
5237 bool isN0ZExt = isZeroExtended(N0, DAG);
5238 bool isN1ZExt = isZeroExtended(N1, DAG);
5239 if (isN0ZExt && isN1ZExt)
5240 NewOpc = ARMISD::VMULLu;
5241 else if (isN1SExt || isN1ZExt) {
5242 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5243 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5244 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5245 NewOpc = ARMISD::VMULLs;
5247 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5248 NewOpc = ARMISD::VMULLu;
5250 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5252 NewOpc = ARMISD::VMULLu;
5258 if (VT == MVT::v2i64)
5259 // Fall through to expand this. It is not legal.
5262 // Other vector multiplications are legal.
5267 // Legalize to a VMULL instruction.
5268 DebugLoc DL = Op.getDebugLoc();
5270 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5272 Op0 = SkipExtensionForVMULL(N0, DAG);
5273 assert(Op0.getValueType().is64BitVector() &&
5274 Op1.getValueType().is64BitVector() &&
5275 "unexpected types for extended operands to VMULL");
5276 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5279 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5280 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5287 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5288 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5289 EVT Op1VT = Op1.getValueType();
5290 return DAG.getNode(N0->getOpcode(), DL, VT,
5291 DAG.getNode(NewOpc, DL, VT,
5292 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5293 DAG.getNode(NewOpc, DL, VT,
5294 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5298 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5300 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5301 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5302 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5303 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5304 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5305 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5306 // Get reciprocal estimate.
5307 // float4 recip = vrecpeq_f32(yf);
5308 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5309 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5310 // Because char has a smaller range than uchar, we can actually get away
5311 // without any newton steps. This requires that we use a weird bias
5312 // of 0xb000, however (again, this has been exhaustively tested).
5313 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5314 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5315 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5316 Y = DAG.getConstant(0xb000, MVT::i32);
5317 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5318 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5319 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5320 // Convert back to short.
5321 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5322 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5327 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5329 // Convert to float.
5330 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5331 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5332 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5333 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5334 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5335 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5337 // Use reciprocal estimate and one refinement step.
5338 // float4 recip = vrecpeq_f32(yf);
5339 // recip *= vrecpsq_f32(yf, recip);
5340 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5341 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5342 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5343 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5345 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5346 // Because short has a smaller range than ushort, we can actually get away
5347 // with only a single newton step. This requires that we use a weird bias
5348 // of 89, however (again, this has been exhaustively tested).
5349 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5350 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5351 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5352 N1 = DAG.getConstant(0x89, MVT::i32);
5353 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5354 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5355 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5356 // Convert back to integer and return.
5357 // return vmovn_s32(vcvt_s32_f32(result));
5358 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5359 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5363 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5364 EVT VT = Op.getValueType();
5365 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5366 "unexpected type for custom-lowering ISD::SDIV");
5368 DebugLoc dl = Op.getDebugLoc();
5369 SDValue N0 = Op.getOperand(0);
5370 SDValue N1 = Op.getOperand(1);
5373 if (VT == MVT::v8i8) {
5374 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5375 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5377 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5378 DAG.getIntPtrConstant(4));
5379 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5380 DAG.getIntPtrConstant(4));
5381 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5382 DAG.getIntPtrConstant(0));
5383 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5384 DAG.getIntPtrConstant(0));
5386 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5387 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5389 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5390 N0 = LowerCONCAT_VECTORS(N0, DAG);
5392 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5395 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5398 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5399 EVT VT = Op.getValueType();
5400 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5401 "unexpected type for custom-lowering ISD::UDIV");
5403 DebugLoc dl = Op.getDebugLoc();
5404 SDValue N0 = Op.getOperand(0);
5405 SDValue N1 = Op.getOperand(1);
5408 if (VT == MVT::v8i8) {
5409 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5410 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5412 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5413 DAG.getIntPtrConstant(4));
5414 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5415 DAG.getIntPtrConstant(4));
5416 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5417 DAG.getIntPtrConstant(0));
5418 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5419 DAG.getIntPtrConstant(0));
5421 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5422 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5424 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5425 N0 = LowerCONCAT_VECTORS(N0, DAG);
5427 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5428 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5433 // v4i16 sdiv ... Convert to float.
5434 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5435 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5436 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5437 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5438 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5439 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5441 // Use reciprocal estimate and two refinement steps.
5442 // float4 recip = vrecpeq_f32(yf);
5443 // recip *= vrecpsq_f32(yf, recip);
5444 // recip *= vrecpsq_f32(yf, recip);
5445 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5446 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5447 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5448 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5450 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5451 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5452 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5454 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5455 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5456 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5457 // and that it will never cause us to return an answer too large).
5458 // float4 result = as_float4(as_int4(xf*recip) + 2);
5459 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5460 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5461 N1 = DAG.getConstant(2, MVT::i32);
5462 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5463 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5464 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5465 // Convert back to integer and return.
5466 // return vmovn_u32(vcvt_s32_f32(result));
5467 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5468 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5472 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5473 EVT VT = Op.getNode()->getValueType(0);
5474 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5477 bool ExtraOp = false;
5478 switch (Op.getOpcode()) {
5479 default: llvm_unreachable("Invalid code");
5480 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5481 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5482 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5483 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5487 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5489 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5490 Op.getOperand(1), Op.getOperand(2));
5493 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5494 // Monotonic load/store is legal for all targets
5495 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5498 // Aquire/Release load/store is not legal for targets without a
5499 // dmb or equivalent available.
5505 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5506 SelectionDAG &DAG, unsigned NewOp) {
5507 DebugLoc dl = Node->getDebugLoc();
5508 assert (Node->getValueType(0) == MVT::i64 &&
5509 "Only know how to expand i64 atomics");
5511 SmallVector<SDValue, 6> Ops;
5512 Ops.push_back(Node->getOperand(0)); // Chain
5513 Ops.push_back(Node->getOperand(1)); // Ptr
5515 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5516 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5517 // High part of Val1
5518 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5519 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5520 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5521 // High part of Val1
5522 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5523 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5524 // High part of Val2
5525 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5526 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5528 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5530 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5531 cast<MemSDNode>(Node)->getMemOperand());
5532 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5533 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5534 Results.push_back(Result.getValue(2));
5537 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5538 switch (Op.getOpcode()) {
5539 default: llvm_unreachable("Don't know how to custom lower this!");
5540 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5541 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5542 case ISD::GlobalAddress:
5543 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5544 LowerGlobalAddressELF(Op, DAG);
5545 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5546 case ISD::SELECT: return LowerSELECT(Op, DAG);
5547 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5548 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5549 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5550 case ISD::VASTART: return LowerVASTART(Op, DAG);
5551 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5552 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5553 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5554 case ISD::SINT_TO_FP:
5555 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5556 case ISD::FP_TO_SINT:
5557 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5558 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5559 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5560 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5561 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5562 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5563 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5564 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5566 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5569 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5570 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5571 case ISD::SRL_PARTS:
5572 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5573 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5574 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5575 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5576 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5577 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5578 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5579 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5580 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5581 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5582 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5583 case ISD::MUL: return LowerMUL(Op, DAG);
5584 case ISD::SDIV: return LowerSDIV(Op, DAG);
5585 case ISD::UDIV: return LowerUDIV(Op, DAG);
5589 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5590 case ISD::ATOMIC_LOAD:
5591 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5595 /// ReplaceNodeResults - Replace the results of node with an illegal result
5596 /// type with new values built out of custom code.
5597 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5598 SmallVectorImpl<SDValue>&Results,
5599 SelectionDAG &DAG) const {
5601 switch (N->getOpcode()) {
5603 llvm_unreachable("Don't know how to custom expand this!");
5605 Res = ExpandBITCAST(N, DAG);
5609 Res = Expand64BitShift(N, DAG, Subtarget);
5611 case ISD::ATOMIC_LOAD_ADD:
5612 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5614 case ISD::ATOMIC_LOAD_AND:
5615 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5617 case ISD::ATOMIC_LOAD_NAND:
5618 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5620 case ISD::ATOMIC_LOAD_OR:
5621 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5623 case ISD::ATOMIC_LOAD_SUB:
5624 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5626 case ISD::ATOMIC_LOAD_XOR:
5627 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5629 case ISD::ATOMIC_SWAP:
5630 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5632 case ISD::ATOMIC_CMP_SWAP:
5633 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5635 case ISD::ATOMIC_LOAD_MIN:
5636 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5638 case ISD::ATOMIC_LOAD_UMIN:
5639 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5641 case ISD::ATOMIC_LOAD_MAX:
5642 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5644 case ISD::ATOMIC_LOAD_UMAX:
5645 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5649 Results.push_back(Res);
5652 //===----------------------------------------------------------------------===//
5653 // ARM Scheduler Hooks
5654 //===----------------------------------------------------------------------===//
5657 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5658 MachineBasicBlock *BB,
5659 unsigned Size) const {
5660 unsigned dest = MI->getOperand(0).getReg();
5661 unsigned ptr = MI->getOperand(1).getReg();
5662 unsigned oldval = MI->getOperand(2).getReg();
5663 unsigned newval = MI->getOperand(3).getReg();
5664 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5665 DebugLoc dl = MI->getDebugLoc();
5666 bool isThumb2 = Subtarget->isThumb2();
5668 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5669 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5670 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5671 (const TargetRegisterClass*)&ARM::GPRRegClass);
5674 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5675 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5676 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5679 unsigned ldrOpc, strOpc;
5681 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5683 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5684 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5687 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5688 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5691 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5692 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5696 MachineFunction *MF = BB->getParent();
5697 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5698 MachineFunction::iterator It = BB;
5699 ++It; // insert the new blocks after the current block
5701 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5702 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5703 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5704 MF->insert(It, loop1MBB);
5705 MF->insert(It, loop2MBB);
5706 MF->insert(It, exitMBB);
5708 // Transfer the remainder of BB and its successor edges to exitMBB.
5709 exitMBB->splice(exitMBB->begin(), BB,
5710 llvm::next(MachineBasicBlock::iterator(MI)),
5712 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5716 // fallthrough --> loop1MBB
5717 BB->addSuccessor(loop1MBB);
5720 // ldrex dest, [ptr]
5724 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5725 if (ldrOpc == ARM::t2LDREX)
5727 AddDefaultPred(MIB);
5728 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5729 .addReg(dest).addReg(oldval));
5730 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5731 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5732 BB->addSuccessor(loop2MBB);
5733 BB->addSuccessor(exitMBB);
5736 // strex scratch, newval, [ptr]
5740 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5741 if (strOpc == ARM::t2STREX)
5743 AddDefaultPred(MIB);
5744 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5745 .addReg(scratch).addImm(0));
5746 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5747 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5748 BB->addSuccessor(loop1MBB);
5749 BB->addSuccessor(exitMBB);
5755 MI->eraseFromParent(); // The instruction is gone now.
5761 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5762 unsigned Size, unsigned BinOpcode) const {
5763 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5764 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5766 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5767 MachineFunction *MF = BB->getParent();
5768 MachineFunction::iterator It = BB;
5771 unsigned dest = MI->getOperand(0).getReg();
5772 unsigned ptr = MI->getOperand(1).getReg();
5773 unsigned incr = MI->getOperand(2).getReg();
5774 DebugLoc dl = MI->getDebugLoc();
5775 bool isThumb2 = Subtarget->isThumb2();
5777 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5779 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5780 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5783 unsigned ldrOpc, strOpc;
5785 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5787 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5788 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5791 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5792 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5795 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5796 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5800 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5801 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5802 MF->insert(It, loopMBB);
5803 MF->insert(It, exitMBB);
5805 // Transfer the remainder of BB and its successor edges to exitMBB.
5806 exitMBB->splice(exitMBB->begin(), BB,
5807 llvm::next(MachineBasicBlock::iterator(MI)),
5809 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5811 const TargetRegisterClass *TRC = isThumb2 ?
5812 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5813 (const TargetRegisterClass*)&ARM::GPRRegClass;
5814 unsigned scratch = MRI.createVirtualRegister(TRC);
5815 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5819 // fallthrough --> loopMBB
5820 BB->addSuccessor(loopMBB);
5824 // <binop> scratch2, dest, incr
5825 // strex scratch, scratch2, ptr
5828 // fallthrough --> exitMBB
5830 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5831 if (ldrOpc == ARM::t2LDREX)
5833 AddDefaultPred(MIB);
5835 // operand order needs to go the other way for NAND
5836 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5837 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5838 addReg(incr).addReg(dest)).addReg(0);
5840 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5841 addReg(dest).addReg(incr)).addReg(0);
5844 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5845 if (strOpc == ARM::t2STREX)
5847 AddDefaultPred(MIB);
5848 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5849 .addReg(scratch).addImm(0));
5850 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5851 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5853 BB->addSuccessor(loopMBB);
5854 BB->addSuccessor(exitMBB);
5860 MI->eraseFromParent(); // The instruction is gone now.
5866 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5867 MachineBasicBlock *BB,
5870 ARMCC::CondCodes Cond) const {
5871 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5873 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5874 MachineFunction *MF = BB->getParent();
5875 MachineFunction::iterator It = BB;
5878 unsigned dest = MI->getOperand(0).getReg();
5879 unsigned ptr = MI->getOperand(1).getReg();
5880 unsigned incr = MI->getOperand(2).getReg();
5881 unsigned oldval = dest;
5882 DebugLoc dl = MI->getDebugLoc();
5883 bool isThumb2 = Subtarget->isThumb2();
5885 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5887 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5888 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5891 unsigned ldrOpc, strOpc, extendOpc;
5893 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5895 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5896 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5897 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5900 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5901 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5902 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5905 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5906 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5911 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5912 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5913 MF->insert(It, loopMBB);
5914 MF->insert(It, exitMBB);
5916 // Transfer the remainder of BB and its successor edges to exitMBB.
5917 exitMBB->splice(exitMBB->begin(), BB,
5918 llvm::next(MachineBasicBlock::iterator(MI)),
5920 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5922 const TargetRegisterClass *TRC = isThumb2 ?
5923 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5924 (const TargetRegisterClass*)&ARM::GPRRegClass;
5925 unsigned scratch = MRI.createVirtualRegister(TRC);
5926 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5930 // fallthrough --> loopMBB
5931 BB->addSuccessor(loopMBB);
5935 // (sign extend dest, if required)
5937 // cmov.cond scratch2, incr, dest
5938 // strex scratch, scratch2, ptr
5941 // fallthrough --> exitMBB
5943 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5944 if (ldrOpc == ARM::t2LDREX)
5946 AddDefaultPred(MIB);
5948 // Sign extend the value, if necessary.
5949 if (signExtend && extendOpc) {
5950 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5951 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5956 // Build compare and cmov instructions.
5957 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5958 .addReg(oldval).addReg(incr));
5959 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5960 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5962 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5963 if (strOpc == ARM::t2STREX)
5965 AddDefaultPred(MIB);
5966 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5967 .addReg(scratch).addImm(0));
5968 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5969 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5971 BB->addSuccessor(loopMBB);
5972 BB->addSuccessor(exitMBB);
5978 MI->eraseFromParent(); // The instruction is gone now.
5984 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5985 unsigned Op1, unsigned Op2,
5986 bool NeedsCarry, bool IsCmpxchg,
5987 bool IsMinMax, ARMCC::CondCodes CC) const {
5988 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5989 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5991 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5992 MachineFunction *MF = BB->getParent();
5993 MachineFunction::iterator It = BB;
5996 unsigned destlo = MI->getOperand(0).getReg();
5997 unsigned desthi = MI->getOperand(1).getReg();
5998 unsigned ptr = MI->getOperand(2).getReg();
5999 unsigned vallo = MI->getOperand(3).getReg();
6000 unsigned valhi = MI->getOperand(4).getReg();
6001 DebugLoc dl = MI->getDebugLoc();
6002 bool isThumb2 = Subtarget->isThumb2();
6004 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6006 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6007 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6008 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6011 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6012 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6013 if (IsCmpxchg || IsMinMax)
6014 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6016 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6017 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6019 MF->insert(It, loopMBB);
6020 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6021 if (IsCmpxchg) MF->insert(It, cont2BB);
6022 MF->insert(It, exitMBB);
6024 // Transfer the remainder of BB and its successor edges to exitMBB.
6025 exitMBB->splice(exitMBB->begin(), BB,
6026 llvm::next(MachineBasicBlock::iterator(MI)),
6028 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6030 const TargetRegisterClass *TRC = isThumb2 ?
6031 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6032 (const TargetRegisterClass*)&ARM::GPRRegClass;
6033 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6037 // fallthrough --> loopMBB
6038 BB->addSuccessor(loopMBB);
6041 // ldrexd r2, r3, ptr
6042 // <binopa> r0, r2, incr
6043 // <binopb> r1, r3, incr
6044 // strexd storesuccess, r0, r1, ptr
6045 // cmp storesuccess, #0
6047 // fallthrough --> exitMBB
6052 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6053 .addReg(destlo, RegState::Define)
6054 .addReg(desthi, RegState::Define)
6057 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6058 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6059 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6060 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6061 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6062 .addReg(GPRPair0, 0, ARM::gsub_0);
6063 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6064 .addReg(GPRPair0, 0, ARM::gsub_1);
6067 unsigned StoreLo, StoreHi;
6070 for (unsigned i = 0; i < 2; i++) {
6071 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6073 .addReg(i == 0 ? destlo : desthi)
6074 .addReg(i == 0 ? vallo : valhi));
6075 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6076 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6077 BB->addSuccessor(exitMBB);
6078 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6079 BB = (i == 0 ? contBB : cont2BB);
6082 // Copy to physregs for strexd
6083 StoreLo = MI->getOperand(5).getReg();
6084 StoreHi = MI->getOperand(6).getReg();
6086 // Perform binary operation
6087 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6088 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6089 .addReg(destlo).addReg(vallo))
6090 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6091 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6092 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6093 .addReg(desthi).addReg(valhi))
6094 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6099 // Copy to physregs for strexd
6104 // Compare and branch to exit block.
6105 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6106 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6107 BB->addSuccessor(exitMBB);
6108 BB->addSuccessor(contBB);
6116 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6117 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6119 // Marshal a pair...
6120 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6121 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6122 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6123 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6124 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6127 .addImm(ARM::gsub_0);
6128 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6131 .addImm(ARM::gsub_1);
6134 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6135 .addReg(StorePair).addReg(ptr));
6138 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6139 .addReg(storesuccess).addImm(0));
6140 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6141 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6143 BB->addSuccessor(loopMBB);
6144 BB->addSuccessor(exitMBB);
6150 MI->eraseFromParent(); // The instruction is gone now.
6155 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6156 /// registers the function context.
6157 void ARMTargetLowering::
6158 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6159 MachineBasicBlock *DispatchBB, int FI) const {
6160 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6161 DebugLoc dl = MI->getDebugLoc();
6162 MachineFunction *MF = MBB->getParent();
6163 MachineRegisterInfo *MRI = &MF->getRegInfo();
6164 MachineConstantPool *MCP = MF->getConstantPool();
6165 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6166 const Function *F = MF->getFunction();
6168 bool isThumb = Subtarget->isThumb();
6169 bool isThumb2 = Subtarget->isThumb2();
6171 unsigned PCLabelId = AFI->createPICLabelUId();
6172 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6173 ARMConstantPoolValue *CPV =
6174 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6175 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6177 const TargetRegisterClass *TRC = isThumb ?
6178 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6179 (const TargetRegisterClass*)&ARM::GPRRegClass;
6181 // Grab constant pool and fixed stack memory operands.
6182 MachineMemOperand *CPMMO =
6183 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6184 MachineMemOperand::MOLoad, 4, 4);
6186 MachineMemOperand *FIMMOSt =
6187 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6188 MachineMemOperand::MOStore, 4, 4);
6190 // Load the address of the dispatch MBB into the jump buffer.
6192 // Incoming value: jbuf
6193 // ldr.n r5, LCPI1_1
6196 // str r5, [$jbuf, #+4] ; &jbuf[1]
6197 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6198 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6199 .addConstantPoolIndex(CPI)
6200 .addMemOperand(CPMMO));
6201 // Set the low bit because of thumb mode.
6202 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6204 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6205 .addReg(NewVReg1, RegState::Kill)
6207 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6208 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6209 .addReg(NewVReg2, RegState::Kill)
6211 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6212 .addReg(NewVReg3, RegState::Kill)
6214 .addImm(36) // &jbuf[1] :: pc
6215 .addMemOperand(FIMMOSt));
6216 } else if (isThumb) {
6217 // Incoming value: jbuf
6218 // ldr.n r1, LCPI1_4
6222 // add r2, $jbuf, #+4 ; &jbuf[1]
6224 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6225 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6226 .addConstantPoolIndex(CPI)
6227 .addMemOperand(CPMMO));
6228 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6229 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6230 .addReg(NewVReg1, RegState::Kill)
6232 // Set the low bit because of thumb mode.
6233 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6234 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6235 .addReg(ARM::CPSR, RegState::Define)
6237 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6238 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6239 .addReg(ARM::CPSR, RegState::Define)
6240 .addReg(NewVReg2, RegState::Kill)
6241 .addReg(NewVReg3, RegState::Kill));
6242 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6243 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6245 .addImm(36)); // &jbuf[1] :: pc
6246 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6247 .addReg(NewVReg4, RegState::Kill)
6248 .addReg(NewVReg5, RegState::Kill)
6250 .addMemOperand(FIMMOSt));
6252 // Incoming value: jbuf
6255 // str r1, [$jbuf, #+4] ; &jbuf[1]
6256 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6257 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6258 .addConstantPoolIndex(CPI)
6260 .addMemOperand(CPMMO));
6261 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6262 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6263 .addReg(NewVReg1, RegState::Kill)
6264 .addImm(PCLabelId));
6265 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6266 .addReg(NewVReg2, RegState::Kill)
6268 .addImm(36) // &jbuf[1] :: pc
6269 .addMemOperand(FIMMOSt));
6273 MachineBasicBlock *ARMTargetLowering::
6274 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6275 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6276 DebugLoc dl = MI->getDebugLoc();
6277 MachineFunction *MF = MBB->getParent();
6278 MachineRegisterInfo *MRI = &MF->getRegInfo();
6279 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6280 MachineFrameInfo *MFI = MF->getFrameInfo();
6281 int FI = MFI->getFunctionContextIndex();
6283 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6284 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6285 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6287 // Get a mapping of the call site numbers to all of the landing pads they're
6289 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6290 unsigned MaxCSNum = 0;
6291 MachineModuleInfo &MMI = MF->getMMI();
6292 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6294 if (!BB->isLandingPad()) continue;
6296 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6298 for (MachineBasicBlock::iterator
6299 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6300 if (!II->isEHLabel()) continue;
6302 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6303 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6305 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6306 for (SmallVectorImpl<unsigned>::iterator
6307 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6308 CSI != CSE; ++CSI) {
6309 CallSiteNumToLPad[*CSI].push_back(BB);
6310 MaxCSNum = std::max(MaxCSNum, *CSI);
6316 // Get an ordered list of the machine basic blocks for the jump table.
6317 std::vector<MachineBasicBlock*> LPadList;
6318 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6319 LPadList.reserve(CallSiteNumToLPad.size());
6320 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6321 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6322 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6323 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6324 LPadList.push_back(*II);
6325 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6329 assert(!LPadList.empty() &&
6330 "No landing pad destinations for the dispatch jump table!");
6332 // Create the jump table and associated information.
6333 MachineJumpTableInfo *JTI =
6334 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6335 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6336 unsigned UId = AFI->createJumpTableUId();
6338 // Create the MBBs for the dispatch code.
6340 // Shove the dispatch's address into the return slot in the function context.
6341 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6342 DispatchBB->setIsLandingPad();
6344 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6345 unsigned trap_opcode;
6346 if (Subtarget->isThumb()) {
6347 trap_opcode = ARM::tTRAP;
6349 if (Subtarget->useNaClTrap())
6350 trap_opcode = ARM::TRAPNaCl;
6352 trap_opcode = ARM::TRAP;
6354 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6355 DispatchBB->addSuccessor(TrapBB);
6357 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6358 DispatchBB->addSuccessor(DispContBB);
6361 MF->insert(MF->end(), DispatchBB);
6362 MF->insert(MF->end(), DispContBB);
6363 MF->insert(MF->end(), TrapBB);
6365 // Insert code into the entry block that creates and registers the function
6367 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6369 MachineMemOperand *FIMMOLd =
6370 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6371 MachineMemOperand::MOLoad |
6372 MachineMemOperand::MOVolatile, 4, 4);
6374 MachineInstrBuilder MIB;
6375 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6377 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6378 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6380 // Add a register mask with no preserved registers. This results in all
6381 // registers being marked as clobbered.
6382 MIB.addRegMask(RI.getNoPreservedMask());
6384 unsigned NumLPads = LPadList.size();
6385 if (Subtarget->isThumb2()) {
6386 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6387 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6390 .addMemOperand(FIMMOLd));
6392 if (NumLPads < 256) {
6393 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6395 .addImm(LPadList.size()));
6397 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6398 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6399 .addImm(NumLPads & 0xFFFF));
6401 unsigned VReg2 = VReg1;
6402 if ((NumLPads & 0xFFFF0000) != 0) {
6403 VReg2 = MRI->createVirtualRegister(TRC);
6404 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6406 .addImm(NumLPads >> 16));
6409 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6414 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6419 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6420 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6421 .addJumpTableIndex(MJTI)
6424 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6427 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6428 .addReg(NewVReg3, RegState::Kill)
6430 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6432 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6433 .addReg(NewVReg4, RegState::Kill)
6435 .addJumpTableIndex(MJTI)
6437 } else if (Subtarget->isThumb()) {
6438 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6439 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6442 .addMemOperand(FIMMOLd));
6444 if (NumLPads < 256) {
6445 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6449 MachineConstantPool *ConstantPool = MF->getConstantPool();
6450 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6451 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6453 // MachineConstantPool wants an explicit alignment.
6454 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6456 Align = getDataLayout()->getTypeAllocSize(C->getType());
6457 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6459 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6460 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6461 .addReg(VReg1, RegState::Define)
6462 .addConstantPoolIndex(Idx));
6463 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6468 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6473 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6474 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6475 .addReg(ARM::CPSR, RegState::Define)
6479 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6480 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6481 .addJumpTableIndex(MJTI)
6484 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6485 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6486 .addReg(ARM::CPSR, RegState::Define)
6487 .addReg(NewVReg2, RegState::Kill)
6490 MachineMemOperand *JTMMOLd =
6491 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6492 MachineMemOperand::MOLoad, 4, 4);
6494 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6495 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6496 .addReg(NewVReg4, RegState::Kill)
6498 .addMemOperand(JTMMOLd));
6500 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6501 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6502 .addReg(ARM::CPSR, RegState::Define)
6503 .addReg(NewVReg5, RegState::Kill)
6506 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6507 .addReg(NewVReg6, RegState::Kill)
6508 .addJumpTableIndex(MJTI)
6511 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6512 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6515 .addMemOperand(FIMMOLd));
6517 if (NumLPads < 256) {
6518 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6521 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6522 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6523 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6524 .addImm(NumLPads & 0xFFFF));
6526 unsigned VReg2 = VReg1;
6527 if ((NumLPads & 0xFFFF0000) != 0) {
6528 VReg2 = MRI->createVirtualRegister(TRC);
6529 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6531 .addImm(NumLPads >> 16));
6534 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6538 MachineConstantPool *ConstantPool = MF->getConstantPool();
6539 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6540 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6542 // MachineConstantPool wants an explicit alignment.
6543 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6545 Align = getDataLayout()->getTypeAllocSize(C->getType());
6546 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6548 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6549 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6550 .addReg(VReg1, RegState::Define)
6551 .addConstantPoolIndex(Idx)
6553 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6555 .addReg(VReg1, RegState::Kill));
6558 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6563 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6565 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6567 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6568 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6569 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6570 .addJumpTableIndex(MJTI)
6573 MachineMemOperand *JTMMOLd =
6574 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6575 MachineMemOperand::MOLoad, 4, 4);
6576 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6578 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6579 .addReg(NewVReg3, RegState::Kill)
6582 .addMemOperand(JTMMOLd));
6584 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6585 .addReg(NewVReg5, RegState::Kill)
6587 .addJumpTableIndex(MJTI)
6591 // Add the jump table entries as successors to the MBB.
6592 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6593 for (std::vector<MachineBasicBlock*>::iterator
6594 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6595 MachineBasicBlock *CurMBB = *I;
6596 if (SeenMBBs.insert(CurMBB))
6597 DispContBB->addSuccessor(CurMBB);
6600 // N.B. the order the invoke BBs are processed in doesn't matter here.
6601 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6602 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6603 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6604 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6605 MachineBasicBlock *BB = *I;
6607 // Remove the landing pad successor from the invoke block and replace it
6608 // with the new dispatch block.
6609 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6611 while (!Successors.empty()) {
6612 MachineBasicBlock *SMBB = Successors.pop_back_val();
6613 if (SMBB->isLandingPad()) {
6614 BB->removeSuccessor(SMBB);
6615 MBBLPads.push_back(SMBB);
6619 BB->addSuccessor(DispatchBB);
6621 // Find the invoke call and mark all of the callee-saved registers as
6622 // 'implicit defined' so that they're spilled. This prevents code from
6623 // moving instructions to before the EH block, where they will never be
6625 for (MachineBasicBlock::reverse_iterator
6626 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6627 if (!II->isCall()) continue;
6629 DenseMap<unsigned, bool> DefRegs;
6630 for (MachineInstr::mop_iterator
6631 OI = II->operands_begin(), OE = II->operands_end();
6633 if (!OI->isReg()) continue;
6634 DefRegs[OI->getReg()] = true;
6637 MachineInstrBuilder MIB(*MF, &*II);
6639 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6640 unsigned Reg = SavedRegs[i];
6641 if (Subtarget->isThumb2() &&
6642 !ARM::tGPRRegClass.contains(Reg) &&
6643 !ARM::hGPRRegClass.contains(Reg))
6645 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6647 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6650 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6657 // Mark all former landing pads as non-landing pads. The dispatch is the only
6659 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6660 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6661 (*I)->setIsLandingPad(false);
6663 // The instruction is gone now.
6664 MI->eraseFromParent();
6670 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6671 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6672 E = MBB->succ_end(); I != E; ++I)
6675 llvm_unreachable("Expecting a BB with two successors!");
6678 MachineBasicBlock *ARMTargetLowering::
6679 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6680 // This pseudo instruction has 3 operands: dst, src, size
6681 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6682 // Otherwise, we will generate unrolled scalar copies.
6683 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6684 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6685 MachineFunction::iterator It = BB;
6688 unsigned dest = MI->getOperand(0).getReg();
6689 unsigned src = MI->getOperand(1).getReg();
6690 unsigned SizeVal = MI->getOperand(2).getImm();
6691 unsigned Align = MI->getOperand(3).getImm();
6692 DebugLoc dl = MI->getDebugLoc();
6694 bool isThumb2 = Subtarget->isThumb2();
6695 MachineFunction *MF = BB->getParent();
6696 MachineRegisterInfo &MRI = MF->getRegInfo();
6697 unsigned ldrOpc, strOpc, UnitSize = 0;
6699 const TargetRegisterClass *TRC = isThumb2 ?
6700 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6701 (const TargetRegisterClass*)&ARM::GPRRegClass;
6702 const TargetRegisterClass *TRC_Vec = 0;
6705 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6706 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6708 } else if (Align & 2) {
6709 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6710 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6713 // Check whether we can use NEON instructions.
6714 if (!MF->getFunction()->getAttributes().
6715 hasAttribute(AttributeSet::FunctionIndex,
6716 Attribute::NoImplicitFloat) &&
6717 Subtarget->hasNEON()) {
6718 if ((Align % 16 == 0) && SizeVal >= 16) {
6719 ldrOpc = ARM::VLD1q32wb_fixed;
6720 strOpc = ARM::VST1q32wb_fixed;
6722 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6724 else if ((Align % 8 == 0) && SizeVal >= 8) {
6725 ldrOpc = ARM::VLD1d32wb_fixed;
6726 strOpc = ARM::VST1d32wb_fixed;
6728 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6731 // Can't use NEON instructions.
6732 if (UnitSize == 0) {
6733 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6734 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6739 unsigned BytesLeft = SizeVal % UnitSize;
6740 unsigned LoopSize = SizeVal - BytesLeft;
6742 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6743 // Use LDR and STR to copy.
6744 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6745 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6746 unsigned srcIn = src;
6747 unsigned destIn = dest;
6748 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6749 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6750 unsigned srcOut = MRI.createVirtualRegister(TRC);
6751 unsigned destOut = MRI.createVirtualRegister(TRC);
6752 if (UnitSize >= 8) {
6753 AddDefaultPred(BuildMI(*BB, MI, dl,
6754 TII->get(ldrOpc), scratch)
6755 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6757 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6758 .addReg(destIn).addImm(0).addReg(scratch));
6759 } else if (isThumb2) {
6760 AddDefaultPred(BuildMI(*BB, MI, dl,
6761 TII->get(ldrOpc), scratch)
6762 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6764 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6765 .addReg(scratch).addReg(destIn)
6768 AddDefaultPred(BuildMI(*BB, MI, dl,
6769 TII->get(ldrOpc), scratch)
6770 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6773 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6774 .addReg(scratch).addReg(destIn)
6775 .addReg(0).addImm(UnitSize));
6781 // Handle the leftover bytes with LDRB and STRB.
6782 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6783 // [destOut] = STRB_POST(scratch, destIn, 1)
6784 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6785 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6786 for (unsigned i = 0; i < BytesLeft; i++) {
6787 unsigned scratch = MRI.createVirtualRegister(TRC);
6788 unsigned srcOut = MRI.createVirtualRegister(TRC);
6789 unsigned destOut = MRI.createVirtualRegister(TRC);
6791 AddDefaultPred(BuildMI(*BB, MI, dl,
6792 TII->get(ldrOpc),scratch)
6793 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6795 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6796 .addReg(scratch).addReg(destIn)
6797 .addReg(0).addImm(1));
6799 AddDefaultPred(BuildMI(*BB, MI, dl,
6800 TII->get(ldrOpc),scratch)
6801 .addReg(srcOut, RegState::Define).addReg(srcIn)
6802 .addReg(0).addImm(1));
6804 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6805 .addReg(scratch).addReg(destIn)
6806 .addReg(0).addImm(1));
6811 MI->eraseFromParent(); // The instruction is gone now.
6815 // Expand the pseudo op to a loop.
6818 // movw varEnd, # --> with thumb2
6820 // ldrcp varEnd, idx --> without thumb2
6821 // fallthrough --> loopMBB
6823 // PHI varPhi, varEnd, varLoop
6824 // PHI srcPhi, src, srcLoop
6825 // PHI destPhi, dst, destLoop
6826 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6827 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6828 // subs varLoop, varPhi, #UnitSize
6830 // fallthrough --> exitMBB
6832 // epilogue to handle left-over bytes
6833 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6834 // [destOut] = STRB_POST(scratch, destLoop, 1)
6835 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6836 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6837 MF->insert(It, loopMBB);
6838 MF->insert(It, exitMBB);
6840 // Transfer the remainder of BB and its successor edges to exitMBB.
6841 exitMBB->splice(exitMBB->begin(), BB,
6842 llvm::next(MachineBasicBlock::iterator(MI)),
6844 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6846 // Load an immediate to varEnd.
6847 unsigned varEnd = MRI.createVirtualRegister(TRC);
6849 unsigned VReg1 = varEnd;
6850 if ((LoopSize & 0xFFFF0000) != 0)
6851 VReg1 = MRI.createVirtualRegister(TRC);
6852 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6853 .addImm(LoopSize & 0xFFFF));
6855 if ((LoopSize & 0xFFFF0000) != 0)
6856 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6858 .addImm(LoopSize >> 16));
6860 MachineConstantPool *ConstantPool = MF->getConstantPool();
6861 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6862 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6864 // MachineConstantPool wants an explicit alignment.
6865 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6867 Align = getDataLayout()->getTypeAllocSize(C->getType());
6868 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6870 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6871 .addReg(varEnd, RegState::Define)
6872 .addConstantPoolIndex(Idx)
6875 BB->addSuccessor(loopMBB);
6877 // Generate the loop body:
6878 // varPhi = PHI(varLoop, varEnd)
6879 // srcPhi = PHI(srcLoop, src)
6880 // destPhi = PHI(destLoop, dst)
6881 MachineBasicBlock *entryBB = BB;
6883 unsigned varLoop = MRI.createVirtualRegister(TRC);
6884 unsigned varPhi = MRI.createVirtualRegister(TRC);
6885 unsigned srcLoop = MRI.createVirtualRegister(TRC);
6886 unsigned srcPhi = MRI.createVirtualRegister(TRC);
6887 unsigned destLoop = MRI.createVirtualRegister(TRC);
6888 unsigned destPhi = MRI.createVirtualRegister(TRC);
6890 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6891 .addReg(varLoop).addMBB(loopMBB)
6892 .addReg(varEnd).addMBB(entryBB);
6893 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6894 .addReg(srcLoop).addMBB(loopMBB)
6895 .addReg(src).addMBB(entryBB);
6896 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6897 .addReg(destLoop).addMBB(loopMBB)
6898 .addReg(dest).addMBB(entryBB);
6900 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6901 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6902 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6903 if (UnitSize >= 8) {
6904 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6905 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6907 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6908 .addReg(destPhi).addImm(0).addReg(scratch));
6909 } else if (isThumb2) {
6910 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6911 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6913 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6914 .addReg(scratch).addReg(destPhi)
6917 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6918 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6921 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6922 .addReg(scratch).addReg(destPhi)
6923 .addReg(0).addImm(UnitSize));
6926 // Decrement loop variable by UnitSize.
6927 MachineInstrBuilder MIB = BuildMI(BB, dl,
6928 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6929 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6930 MIB->getOperand(5).setReg(ARM::CPSR);
6931 MIB->getOperand(5).setIsDef(true);
6933 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6934 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6936 // loopMBB can loop back to loopMBB or fall through to exitMBB.
6937 BB->addSuccessor(loopMBB);
6938 BB->addSuccessor(exitMBB);
6940 // Add epilogue to handle BytesLeft.
6942 MachineInstr *StartOfExit = exitMBB->begin();
6943 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6944 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6946 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6947 // [destOut] = STRB_POST(scratch, destLoop, 1)
6948 unsigned srcIn = srcLoop;
6949 unsigned destIn = destLoop;
6950 for (unsigned i = 0; i < BytesLeft; i++) {
6951 unsigned scratch = MRI.createVirtualRegister(TRC);
6952 unsigned srcOut = MRI.createVirtualRegister(TRC);
6953 unsigned destOut = MRI.createVirtualRegister(TRC);
6955 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6956 TII->get(ldrOpc),scratch)
6957 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6959 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6960 .addReg(scratch).addReg(destIn)
6963 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6964 TII->get(ldrOpc),scratch)
6965 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6967 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6968 .addReg(scratch).addReg(destIn)
6969 .addReg(0).addImm(1));
6975 MI->eraseFromParent(); // The instruction is gone now.
6980 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6981 MachineBasicBlock *BB) const {
6982 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6983 DebugLoc dl = MI->getDebugLoc();
6984 bool isThumb2 = Subtarget->isThumb2();
6985 switch (MI->getOpcode()) {
6988 llvm_unreachable("Unexpected instr type to insert");
6990 // The Thumb2 pre-indexed stores have the same MI operands, they just
6991 // define them differently in the .td files from the isel patterns, so
6992 // they need pseudos.
6993 case ARM::t2STR_preidx:
6994 MI->setDesc(TII->get(ARM::t2STR_PRE));
6996 case ARM::t2STRB_preidx:
6997 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6999 case ARM::t2STRH_preidx:
7000 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7003 case ARM::STRi_preidx:
7004 case ARM::STRBi_preidx: {
7005 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7006 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7007 // Decode the offset.
7008 unsigned Offset = MI->getOperand(4).getImm();
7009 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7010 Offset = ARM_AM::getAM2Offset(Offset);
7014 MachineMemOperand *MMO = *MI->memoperands_begin();
7015 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7016 .addOperand(MI->getOperand(0)) // Rn_wb
7017 .addOperand(MI->getOperand(1)) // Rt
7018 .addOperand(MI->getOperand(2)) // Rn
7019 .addImm(Offset) // offset (skip GPR==zero_reg)
7020 .addOperand(MI->getOperand(5)) // pred
7021 .addOperand(MI->getOperand(6))
7022 .addMemOperand(MMO);
7023 MI->eraseFromParent();
7026 case ARM::STRr_preidx:
7027 case ARM::STRBr_preidx:
7028 case ARM::STRH_preidx: {
7030 switch (MI->getOpcode()) {
7031 default: llvm_unreachable("unexpected opcode!");
7032 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7033 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7034 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7036 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7037 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7038 MIB.addOperand(MI->getOperand(i));
7039 MI->eraseFromParent();
7042 case ARM::ATOMIC_LOAD_ADD_I8:
7043 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7044 case ARM::ATOMIC_LOAD_ADD_I16:
7045 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7046 case ARM::ATOMIC_LOAD_ADD_I32:
7047 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7049 case ARM::ATOMIC_LOAD_AND_I8:
7050 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7051 case ARM::ATOMIC_LOAD_AND_I16:
7052 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7053 case ARM::ATOMIC_LOAD_AND_I32:
7054 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7056 case ARM::ATOMIC_LOAD_OR_I8:
7057 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7058 case ARM::ATOMIC_LOAD_OR_I16:
7059 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7060 case ARM::ATOMIC_LOAD_OR_I32:
7061 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7063 case ARM::ATOMIC_LOAD_XOR_I8:
7064 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7065 case ARM::ATOMIC_LOAD_XOR_I16:
7066 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7067 case ARM::ATOMIC_LOAD_XOR_I32:
7068 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7070 case ARM::ATOMIC_LOAD_NAND_I8:
7071 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7072 case ARM::ATOMIC_LOAD_NAND_I16:
7073 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7074 case ARM::ATOMIC_LOAD_NAND_I32:
7075 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7077 case ARM::ATOMIC_LOAD_SUB_I8:
7078 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7079 case ARM::ATOMIC_LOAD_SUB_I16:
7080 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7081 case ARM::ATOMIC_LOAD_SUB_I32:
7082 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7084 case ARM::ATOMIC_LOAD_MIN_I8:
7085 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7086 case ARM::ATOMIC_LOAD_MIN_I16:
7087 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7088 case ARM::ATOMIC_LOAD_MIN_I32:
7089 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7091 case ARM::ATOMIC_LOAD_MAX_I8:
7092 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7093 case ARM::ATOMIC_LOAD_MAX_I16:
7094 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7095 case ARM::ATOMIC_LOAD_MAX_I32:
7096 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7098 case ARM::ATOMIC_LOAD_UMIN_I8:
7099 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7100 case ARM::ATOMIC_LOAD_UMIN_I16:
7101 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7102 case ARM::ATOMIC_LOAD_UMIN_I32:
7103 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7105 case ARM::ATOMIC_LOAD_UMAX_I8:
7106 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7107 case ARM::ATOMIC_LOAD_UMAX_I16:
7108 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7109 case ARM::ATOMIC_LOAD_UMAX_I32:
7110 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7112 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7113 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7114 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7116 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7117 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7118 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7121 case ARM::ATOMADD6432:
7122 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7123 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7124 /*NeedsCarry*/ true);
7125 case ARM::ATOMSUB6432:
7126 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7127 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7128 /*NeedsCarry*/ true);
7129 case ARM::ATOMOR6432:
7130 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7131 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7132 case ARM::ATOMXOR6432:
7133 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7134 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7135 case ARM::ATOMAND6432:
7136 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7137 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7138 case ARM::ATOMSWAP6432:
7139 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7140 case ARM::ATOMCMPXCHG6432:
7141 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7142 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7143 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7144 case ARM::ATOMMIN6432:
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::LT);
7149 case ARM::ATOMMAX6432:
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::GE);
7154 case ARM::ATOMUMIN6432:
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::LO);
7159 case ARM::ATOMUMAX6432:
7160 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7161 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7162 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7163 /*IsMinMax*/ true, ARMCC::HS);
7165 case ARM::tMOVCCr_pseudo: {
7166 // To "insert" a SELECT_CC instruction, we actually have to insert the
7167 // diamond control-flow pattern. The incoming instruction knows the
7168 // destination vreg to set, the condition code register to branch on, the
7169 // true/false values to select between, and a branch opcode to use.
7170 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7171 MachineFunction::iterator It = BB;
7177 // cmpTY ccX, r1, r2
7179 // fallthrough --> copy0MBB
7180 MachineBasicBlock *thisMBB = BB;
7181 MachineFunction *F = BB->getParent();
7182 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7183 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7184 F->insert(It, copy0MBB);
7185 F->insert(It, sinkMBB);
7187 // Transfer the remainder of BB and its successor edges to sinkMBB.
7188 sinkMBB->splice(sinkMBB->begin(), BB,
7189 llvm::next(MachineBasicBlock::iterator(MI)),
7191 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7193 BB->addSuccessor(copy0MBB);
7194 BB->addSuccessor(sinkMBB);
7196 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7197 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7200 // %FalseValue = ...
7201 // # fallthrough to sinkMBB
7204 // Update machine-CFG edges
7205 BB->addSuccessor(sinkMBB);
7208 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7211 BuildMI(*BB, BB->begin(), dl,
7212 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7213 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7214 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7216 MI->eraseFromParent(); // The pseudo instruction is gone now.
7221 case ARM::BCCZi64: {
7222 // If there is an unconditional branch to the other successor, remove it.
7223 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7225 // Compare both parts that make up the double comparison separately for
7227 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7229 unsigned LHS1 = MI->getOperand(1).getReg();
7230 unsigned LHS2 = MI->getOperand(2).getReg();
7232 AddDefaultPred(BuildMI(BB, dl,
7233 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7234 .addReg(LHS1).addImm(0));
7235 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7236 .addReg(LHS2).addImm(0)
7237 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7239 unsigned RHS1 = MI->getOperand(3).getReg();
7240 unsigned RHS2 = MI->getOperand(4).getReg();
7241 AddDefaultPred(BuildMI(BB, dl,
7242 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7243 .addReg(LHS1).addReg(RHS1));
7244 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7245 .addReg(LHS2).addReg(RHS2)
7246 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7249 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7250 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7251 if (MI->getOperand(0).getImm() == ARMCC::NE)
7252 std::swap(destMBB, exitMBB);
7254 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7255 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7257 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7259 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7261 MI->eraseFromParent(); // The pseudo instruction is gone now.
7265 case ARM::Int_eh_sjlj_setjmp:
7266 case ARM::Int_eh_sjlj_setjmp_nofp:
7267 case ARM::tInt_eh_sjlj_setjmp:
7268 case ARM::t2Int_eh_sjlj_setjmp:
7269 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7270 EmitSjLjDispatchBlock(MI, BB);
7275 // To insert an ABS instruction, we have to insert the
7276 // diamond control-flow pattern. The incoming instruction knows the
7277 // source vreg to test against 0, the destination vreg to set,
7278 // the condition code register to branch on, the
7279 // true/false values to select between, and a branch opcode to use.
7284 // BCC (branch to SinkBB if V0 >= 0)
7285 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7286 // SinkBB: V1 = PHI(V2, V3)
7287 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7288 MachineFunction::iterator BBI = BB;
7290 MachineFunction *Fn = BB->getParent();
7291 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7292 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7293 Fn->insert(BBI, RSBBB);
7294 Fn->insert(BBI, SinkBB);
7296 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7297 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7298 bool isThumb2 = Subtarget->isThumb2();
7299 MachineRegisterInfo &MRI = Fn->getRegInfo();
7300 // In Thumb mode S must not be specified if source register is the SP or
7301 // PC and if destination register is the SP, so restrict register class
7302 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7303 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7304 (const TargetRegisterClass*)&ARM::GPRRegClass);
7306 // Transfer the remainder of BB and its successor edges to sinkMBB.
7307 SinkBB->splice(SinkBB->begin(), BB,
7308 llvm::next(MachineBasicBlock::iterator(MI)),
7310 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7312 BB->addSuccessor(RSBBB);
7313 BB->addSuccessor(SinkBB);
7315 // fall through to SinkMBB
7316 RSBBB->addSuccessor(SinkBB);
7318 // insert a cmp at the end of BB
7319 AddDefaultPred(BuildMI(BB, dl,
7320 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7321 .addReg(ABSSrcReg).addImm(0));
7323 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7325 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7326 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7328 // insert rsbri in RSBBB
7329 // Note: BCC and rsbri will be converted into predicated rsbmi
7330 // by if-conversion pass
7331 BuildMI(*RSBBB, RSBBB->begin(), dl,
7332 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7333 .addReg(ABSSrcReg, RegState::Kill)
7334 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7336 // insert PHI in SinkBB,
7337 // reuse ABSDstReg to not change uses of ABS instruction
7338 BuildMI(*SinkBB, SinkBB->begin(), dl,
7339 TII->get(ARM::PHI), ABSDstReg)
7340 .addReg(NewRsbDstReg).addMBB(RSBBB)
7341 .addReg(ABSSrcReg).addMBB(BB);
7343 // remove ABS instruction
7344 MI->eraseFromParent();
7346 // return last added BB
7349 case ARM::COPY_STRUCT_BYVAL_I32:
7351 return EmitStructByval(MI, BB);
7355 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7356 SDNode *Node) const {
7357 if (!MI->hasPostISelHook()) {
7358 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7359 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7363 const MCInstrDesc *MCID = &MI->getDesc();
7364 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7365 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7366 // operand is still set to noreg. If needed, set the optional operand's
7367 // register to CPSR, and remove the redundant implicit def.
7369 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7371 // Rename pseudo opcodes.
7372 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7374 const ARMBaseInstrInfo *TII =
7375 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7376 MCID = &TII->get(NewOpc);
7378 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7379 "converted opcode should be the same except for cc_out");
7383 // Add the optional cc_out operand
7384 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7386 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7388 // Any ARM instruction that sets the 's' bit should specify an optional
7389 // "cc_out" operand in the last operand position.
7390 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7391 assert(!NewOpc && "Optional cc_out operand required");
7394 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7395 // since we already have an optional CPSR def.
7396 bool definesCPSR = false;
7397 bool deadCPSR = false;
7398 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7400 const MachineOperand &MO = MI->getOperand(i);
7401 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7405 MI->RemoveOperand(i);
7410 assert(!NewOpc && "Optional cc_out operand required");
7413 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7415 assert(!MI->getOperand(ccOutIdx).getReg() &&
7416 "expect uninitialized optional cc_out operand");
7420 // If this instruction was defined with an optional CPSR def and its dag node
7421 // had a live implicit CPSR def, then activate the optional CPSR def.
7422 MachineOperand &MO = MI->getOperand(ccOutIdx);
7423 MO.setReg(ARM::CPSR);
7427 //===----------------------------------------------------------------------===//
7428 // ARM Optimization Hooks
7429 //===----------------------------------------------------------------------===//
7431 // Helper function that checks if N is a null or all ones constant.
7432 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7433 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7436 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7439 // Return true if N is conditionally 0 or all ones.
7440 // Detects these expressions where cc is an i1 value:
7442 // (select cc 0, y) [AllOnes=0]
7443 // (select cc y, 0) [AllOnes=0]
7444 // (zext cc) [AllOnes=0]
7445 // (sext cc) [AllOnes=0/1]
7446 // (select cc -1, y) [AllOnes=1]
7447 // (select cc y, -1) [AllOnes=1]
7449 // Invert is set when N is the null/all ones constant when CC is false.
7450 // OtherOp is set to the alternative value of N.
7451 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7452 SDValue &CC, bool &Invert,
7454 SelectionDAG &DAG) {
7455 switch (N->getOpcode()) {
7456 default: return false;
7458 CC = N->getOperand(0);
7459 SDValue N1 = N->getOperand(1);
7460 SDValue N2 = N->getOperand(2);
7461 if (isZeroOrAllOnes(N1, AllOnes)) {
7466 if (isZeroOrAllOnes(N2, AllOnes)) {
7473 case ISD::ZERO_EXTEND:
7474 // (zext cc) can never be the all ones value.
7478 case ISD::SIGN_EXTEND: {
7479 EVT VT = N->getValueType(0);
7480 CC = N->getOperand(0);
7481 if (CC.getValueType() != MVT::i1)
7485 // When looking for an AllOnes constant, N is an sext, and the 'other'
7487 OtherOp = DAG.getConstant(0, VT);
7488 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7489 // When looking for a 0 constant, N can be zext or sext.
7490 OtherOp = DAG.getConstant(1, VT);
7492 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7498 // Combine a constant select operand into its use:
7500 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7501 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7502 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7503 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7504 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7506 // The transform is rejected if the select doesn't have a constant operand that
7507 // is null, or all ones when AllOnes is set.
7509 // Also recognize sext/zext from i1:
7511 // (add (zext cc), x) -> (select cc (add x, 1), x)
7512 // (add (sext cc), x) -> (select cc (add x, -1), x)
7514 // These transformations eventually create predicated instructions.
7516 // @param N The node to transform.
7517 // @param Slct The N operand that is a select.
7518 // @param OtherOp The other N operand (x above).
7519 // @param DCI Context.
7520 // @param AllOnes Require the select constant to be all ones instead of null.
7521 // @returns The new node, or SDValue() on failure.
7523 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7524 TargetLowering::DAGCombinerInfo &DCI,
7525 bool AllOnes = false) {
7526 SelectionDAG &DAG = DCI.DAG;
7527 EVT VT = N->getValueType(0);
7528 SDValue NonConstantVal;
7531 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7532 NonConstantVal, DAG))
7535 // Slct is now know to be the desired identity constant when CC is true.
7536 SDValue TrueVal = OtherOp;
7537 SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7538 OtherOp, NonConstantVal);
7539 // Unless SwapSelectOps says CC should be false.
7541 std::swap(TrueVal, FalseVal);
7543 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7544 CCOp, TrueVal, FalseVal);
7547 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7549 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7550 TargetLowering::DAGCombinerInfo &DCI) {
7551 SDValue N0 = N->getOperand(0);
7552 SDValue N1 = N->getOperand(1);
7553 if (N0.getNode()->hasOneUse()) {
7554 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7555 if (Result.getNode())
7558 if (N1.getNode()->hasOneUse()) {
7559 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7560 if (Result.getNode())
7566 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7567 // (only after legalization).
7568 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7569 TargetLowering::DAGCombinerInfo &DCI,
7570 const ARMSubtarget *Subtarget) {
7572 // Only perform optimization if after legalize, and if NEON is available. We
7573 // also expected both operands to be BUILD_VECTORs.
7574 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7575 || N0.getOpcode() != ISD::BUILD_VECTOR
7576 || N1.getOpcode() != ISD::BUILD_VECTOR)
7579 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7580 EVT VT = N->getValueType(0);
7581 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7584 // Check that the vector operands are of the right form.
7585 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7586 // operands, where N is the size of the formed vector.
7587 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7588 // index such that we have a pair wise add pattern.
7590 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7591 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7593 SDValue Vec = N0->getOperand(0)->getOperand(0);
7594 SDNode *V = Vec.getNode();
7595 unsigned nextIndex = 0;
7597 // For each operands to the ADD which are BUILD_VECTORs,
7598 // check to see if each of their operands are an EXTRACT_VECTOR with
7599 // the same vector and appropriate index.
7600 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7601 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7602 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7604 SDValue ExtVec0 = N0->getOperand(i);
7605 SDValue ExtVec1 = N1->getOperand(i);
7607 // First operand is the vector, verify its the same.
7608 if (V != ExtVec0->getOperand(0).getNode() ||
7609 V != ExtVec1->getOperand(0).getNode())
7612 // Second is the constant, verify its correct.
7613 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7614 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7616 // For the constant, we want to see all the even or all the odd.
7617 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7618 || C1->getZExtValue() != nextIndex+1)
7627 // Create VPADDL node.
7628 SelectionDAG &DAG = DCI.DAG;
7629 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7631 // Build operand list.
7632 SmallVector<SDValue, 8> Ops;
7633 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7634 TLI.getPointerTy()));
7636 // Input is the vector.
7639 // Get widened type and narrowed type.
7641 unsigned numElem = VT.getVectorNumElements();
7642 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7643 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7644 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7645 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7647 llvm_unreachable("Invalid vector element type for padd optimization.");
7650 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7651 widenType, &Ops[0], Ops.size());
7652 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7655 static SDValue findMUL_LOHI(SDValue V) {
7656 if (V->getOpcode() == ISD::UMUL_LOHI ||
7657 V->getOpcode() == ISD::SMUL_LOHI)
7662 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7663 TargetLowering::DAGCombinerInfo &DCI,
7664 const ARMSubtarget *Subtarget) {
7666 if (Subtarget->isThumb1Only()) return SDValue();
7668 // Only perform the checks after legalize when the pattern is available.
7669 if (DCI.isBeforeLegalize()) return SDValue();
7671 // Look for multiply add opportunities.
7672 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7673 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7674 // a glue link from the first add to the second add.
7675 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7676 // a S/UMLAL instruction.
7679 // \ / \ [no multiline comment]
7685 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7686 SDValue AddcOp0 = AddcNode->getOperand(0);
7687 SDValue AddcOp1 = AddcNode->getOperand(1);
7689 // Check if the two operands are from the same mul_lohi node.
7690 if (AddcOp0.getNode() == AddcOp1.getNode())
7693 assert(AddcNode->getNumValues() == 2 &&
7694 AddcNode->getValueType(0) == MVT::i32 &&
7695 AddcNode->getValueType(1) == MVT::Glue &&
7696 "Expect ADDC with two result values: i32, glue");
7698 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7699 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7700 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7701 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7702 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7705 // Look for the glued ADDE.
7706 SDNode* AddeNode = AddcNode->getGluedUser();
7707 if (AddeNode == NULL)
7710 // Make sure it is really an ADDE.
7711 if (AddeNode->getOpcode() != ISD::ADDE)
7714 assert(AddeNode->getNumOperands() == 3 &&
7715 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7716 "ADDE node has the wrong inputs");
7718 // Check for the triangle shape.
7719 SDValue AddeOp0 = AddeNode->getOperand(0);
7720 SDValue AddeOp1 = AddeNode->getOperand(1);
7722 // Make sure that the ADDE operands are not coming from the same node.
7723 if (AddeOp0.getNode() == AddeOp1.getNode())
7726 // Find the MUL_LOHI node walking up ADDE's operands.
7727 bool IsLeftOperandMUL = false;
7728 SDValue MULOp = findMUL_LOHI(AddeOp0);
7729 if (MULOp == SDValue())
7730 MULOp = findMUL_LOHI(AddeOp1);
7732 IsLeftOperandMUL = true;
7733 if (MULOp == SDValue())
7736 // Figure out the right opcode.
7737 unsigned Opc = MULOp->getOpcode();
7738 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7740 // Figure out the high and low input values to the MLAL node.
7741 SDValue* HiMul = &MULOp;
7742 SDValue* HiAdd = NULL;
7743 SDValue* LoMul = NULL;
7744 SDValue* LowAdd = NULL;
7746 if (IsLeftOperandMUL)
7752 if (AddcOp0->getOpcode() == Opc) {
7756 if (AddcOp1->getOpcode() == Opc) {
7764 if (LoMul->getNode() != HiMul->getNode())
7767 // Create the merged node.
7768 SelectionDAG &DAG = DCI.DAG;
7770 // Build operand list.
7771 SmallVector<SDValue, 8> Ops;
7772 Ops.push_back(LoMul->getOperand(0));
7773 Ops.push_back(LoMul->getOperand(1));
7774 Ops.push_back(*LowAdd);
7775 Ops.push_back(*HiAdd);
7777 SDValue MLALNode = DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7778 DAG.getVTList(MVT::i32, MVT::i32),
7779 &Ops[0], Ops.size());
7781 // Replace the ADDs' nodes uses by the MLA node's values.
7782 SDValue HiMLALResult(MLALNode.getNode(), 1);
7783 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7785 SDValue LoMLALResult(MLALNode.getNode(), 0);
7786 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7788 // Return original node to notify the driver to stop replacing.
7789 SDValue resNode(AddcNode, 0);
7793 /// PerformADDCCombine - Target-specific dag combine transform from
7794 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7795 static SDValue PerformADDCCombine(SDNode *N,
7796 TargetLowering::DAGCombinerInfo &DCI,
7797 const ARMSubtarget *Subtarget) {
7799 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7803 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7804 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7805 /// called with the default operands, and if that fails, with commuted
7807 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7808 TargetLowering::DAGCombinerInfo &DCI,
7809 const ARMSubtarget *Subtarget){
7811 // Attempt to create vpaddl for this add.
7812 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7813 if (Result.getNode())
7816 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7817 if (N0.getNode()->hasOneUse()) {
7818 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7819 if (Result.getNode()) return Result;
7824 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7826 static SDValue PerformADDCombine(SDNode *N,
7827 TargetLowering::DAGCombinerInfo &DCI,
7828 const ARMSubtarget *Subtarget) {
7829 SDValue N0 = N->getOperand(0);
7830 SDValue N1 = N->getOperand(1);
7832 // First try with the default operand order.
7833 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7834 if (Result.getNode())
7837 // If that didn't work, try again with the operands commuted.
7838 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7841 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7843 static SDValue PerformSUBCombine(SDNode *N,
7844 TargetLowering::DAGCombinerInfo &DCI) {
7845 SDValue N0 = N->getOperand(0);
7846 SDValue N1 = N->getOperand(1);
7848 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7849 if (N1.getNode()->hasOneUse()) {
7850 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7851 if (Result.getNode()) return Result;
7857 /// PerformVMULCombine
7858 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7859 /// special multiplier accumulator forwarding.
7865 static SDValue PerformVMULCombine(SDNode *N,
7866 TargetLowering::DAGCombinerInfo &DCI,
7867 const ARMSubtarget *Subtarget) {
7868 if (!Subtarget->hasVMLxForwarding())
7871 SelectionDAG &DAG = DCI.DAG;
7872 SDValue N0 = N->getOperand(0);
7873 SDValue N1 = N->getOperand(1);
7874 unsigned Opcode = N0.getOpcode();
7875 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7876 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7877 Opcode = N1.getOpcode();
7878 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7879 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7884 EVT VT = N->getValueType(0);
7885 DebugLoc DL = N->getDebugLoc();
7886 SDValue N00 = N0->getOperand(0);
7887 SDValue N01 = N0->getOperand(1);
7888 return DAG.getNode(Opcode, DL, VT,
7889 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7890 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7893 static SDValue PerformMULCombine(SDNode *N,
7894 TargetLowering::DAGCombinerInfo &DCI,
7895 const ARMSubtarget *Subtarget) {
7896 SelectionDAG &DAG = DCI.DAG;
7898 if (Subtarget->isThumb1Only())
7901 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7904 EVT VT = N->getValueType(0);
7905 if (VT.is64BitVector() || VT.is128BitVector())
7906 return PerformVMULCombine(N, DCI, Subtarget);
7910 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7914 int64_t MulAmt = C->getSExtValue();
7915 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7917 ShiftAmt = ShiftAmt & (32 - 1);
7918 SDValue V = N->getOperand(0);
7919 DebugLoc DL = N->getDebugLoc();
7922 MulAmt >>= ShiftAmt;
7925 if (isPowerOf2_32(MulAmt - 1)) {
7926 // (mul x, 2^N + 1) => (add (shl x, N), x)
7927 Res = DAG.getNode(ISD::ADD, DL, VT,
7929 DAG.getNode(ISD::SHL, DL, VT,
7931 DAG.getConstant(Log2_32(MulAmt - 1),
7933 } else if (isPowerOf2_32(MulAmt + 1)) {
7934 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7935 Res = DAG.getNode(ISD::SUB, DL, VT,
7936 DAG.getNode(ISD::SHL, DL, VT,
7938 DAG.getConstant(Log2_32(MulAmt + 1),
7944 uint64_t MulAmtAbs = -MulAmt;
7945 if (isPowerOf2_32(MulAmtAbs + 1)) {
7946 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7947 Res = DAG.getNode(ISD::SUB, DL, VT,
7949 DAG.getNode(ISD::SHL, DL, VT,
7951 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7953 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7954 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7955 Res = DAG.getNode(ISD::ADD, DL, VT,
7957 DAG.getNode(ISD::SHL, DL, VT,
7959 DAG.getConstant(Log2_32(MulAmtAbs-1),
7961 Res = DAG.getNode(ISD::SUB, DL, VT,
7962 DAG.getConstant(0, MVT::i32),Res);
7969 Res = DAG.getNode(ISD::SHL, DL, VT,
7970 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7972 // Do not add new nodes to DAG combiner worklist.
7973 DCI.CombineTo(N, Res, false);
7977 static SDValue PerformANDCombine(SDNode *N,
7978 TargetLowering::DAGCombinerInfo &DCI,
7979 const ARMSubtarget *Subtarget) {
7981 // Attempt to use immediate-form VBIC
7982 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7983 DebugLoc dl = N->getDebugLoc();
7984 EVT VT = N->getValueType(0);
7985 SelectionDAG &DAG = DCI.DAG;
7987 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7990 APInt SplatBits, SplatUndef;
7991 unsigned SplatBitSize;
7994 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7995 if (SplatBitSize <= 64) {
7997 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7998 SplatUndef.getZExtValue(), SplatBitSize,
7999 DAG, VbicVT, VT.is128BitVector(),
8001 if (Val.getNode()) {
8003 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8004 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8005 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8010 if (!Subtarget->isThumb1Only()) {
8011 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8012 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8013 if (Result.getNode())
8020 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8021 static SDValue PerformORCombine(SDNode *N,
8022 TargetLowering::DAGCombinerInfo &DCI,
8023 const ARMSubtarget *Subtarget) {
8024 // Attempt to use immediate-form VORR
8025 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8026 DebugLoc dl = N->getDebugLoc();
8027 EVT VT = N->getValueType(0);
8028 SelectionDAG &DAG = DCI.DAG;
8030 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8033 APInt SplatBits, SplatUndef;
8034 unsigned SplatBitSize;
8036 if (BVN && Subtarget->hasNEON() &&
8037 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8038 if (SplatBitSize <= 64) {
8040 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8041 SplatUndef.getZExtValue(), SplatBitSize,
8042 DAG, VorrVT, VT.is128BitVector(),
8044 if (Val.getNode()) {
8046 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8047 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8048 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8053 if (!Subtarget->isThumb1Only()) {
8054 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8055 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8056 if (Result.getNode())
8060 // The code below optimizes (or (and X, Y), Z).
8061 // The AND operand needs to have a single user to make these optimizations
8063 SDValue N0 = N->getOperand(0);
8064 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8066 SDValue N1 = N->getOperand(1);
8068 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8069 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8070 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8072 unsigned SplatBitSize;
8075 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8077 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8078 HasAnyUndefs) && !HasAnyUndefs) {
8079 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8081 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8082 HasAnyUndefs) && !HasAnyUndefs &&
8083 SplatBits0 == ~SplatBits1) {
8084 // Canonicalize the vector type to make instruction selection simpler.
8085 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8086 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8087 N0->getOperand(1), N0->getOperand(0),
8089 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8094 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8097 // BFI is only available on V6T2+
8098 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8101 DebugLoc DL = N->getDebugLoc();
8102 // 1) or (and A, mask), val => ARMbfi A, val, mask
8103 // iff (val & mask) == val
8105 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8106 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8107 // && mask == ~mask2
8108 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8109 // && ~mask == mask2
8110 // (i.e., copy a bitfield value into another bitfield of the same width)
8115 SDValue N00 = N0.getOperand(0);
8117 // The value and the mask need to be constants so we can verify this is
8118 // actually a bitfield set. If the mask is 0xffff, we can do better
8119 // via a movt instruction, so don't use BFI in that case.
8120 SDValue MaskOp = N0.getOperand(1);
8121 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8124 unsigned Mask = MaskC->getZExtValue();
8128 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8129 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8131 unsigned Val = N1C->getZExtValue();
8132 if ((Val & ~Mask) != Val)
8135 if (ARM::isBitFieldInvertedMask(Mask)) {
8136 Val >>= CountTrailingZeros_32(~Mask);
8138 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8139 DAG.getConstant(Val, MVT::i32),
8140 DAG.getConstant(Mask, MVT::i32));
8142 // Do not add new nodes to DAG combiner worklist.
8143 DCI.CombineTo(N, Res, false);
8146 } else if (N1.getOpcode() == ISD::AND) {
8147 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8148 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8151 unsigned Mask2 = N11C->getZExtValue();
8153 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8155 if (ARM::isBitFieldInvertedMask(Mask) &&
8157 // The pack halfword instruction works better for masks that fit it,
8158 // so use that when it's available.
8159 if (Subtarget->hasT2ExtractPack() &&
8160 (Mask == 0xffff || Mask == 0xffff0000))
8163 unsigned amt = CountTrailingZeros_32(Mask2);
8164 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8165 DAG.getConstant(amt, MVT::i32));
8166 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8167 DAG.getConstant(Mask, MVT::i32));
8168 // Do not add new nodes to DAG combiner worklist.
8169 DCI.CombineTo(N, Res, false);
8171 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8173 // The pack halfword instruction works better for masks that fit it,
8174 // so use that when it's available.
8175 if (Subtarget->hasT2ExtractPack() &&
8176 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8179 unsigned lsb = CountTrailingZeros_32(Mask);
8180 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8181 DAG.getConstant(lsb, MVT::i32));
8182 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8183 DAG.getConstant(Mask2, MVT::i32));
8184 // Do not add new nodes to DAG combiner worklist.
8185 DCI.CombineTo(N, Res, false);
8190 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8191 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8192 ARM::isBitFieldInvertedMask(~Mask)) {
8193 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8194 // where lsb(mask) == #shamt and masked bits of B are known zero.
8195 SDValue ShAmt = N00.getOperand(1);
8196 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8197 unsigned LSB = CountTrailingZeros_32(Mask);
8201 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8202 DAG.getConstant(~Mask, MVT::i32));
8204 // Do not add new nodes to DAG combiner worklist.
8205 DCI.CombineTo(N, Res, false);
8211 static SDValue PerformXORCombine(SDNode *N,
8212 TargetLowering::DAGCombinerInfo &DCI,
8213 const ARMSubtarget *Subtarget) {
8214 EVT VT = N->getValueType(0);
8215 SelectionDAG &DAG = DCI.DAG;
8217 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8220 if (!Subtarget->isThumb1Only()) {
8221 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8222 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8223 if (Result.getNode())
8230 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8231 /// the bits being cleared by the AND are not demanded by the BFI.
8232 static SDValue PerformBFICombine(SDNode *N,
8233 TargetLowering::DAGCombinerInfo &DCI) {
8234 SDValue N1 = N->getOperand(1);
8235 if (N1.getOpcode() == ISD::AND) {
8236 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8239 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8240 unsigned LSB = CountTrailingZeros_32(~InvMask);
8241 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8242 unsigned Mask = (1 << Width)-1;
8243 unsigned Mask2 = N11C->getZExtValue();
8244 if ((Mask & (~Mask2)) == 0)
8245 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8246 N->getOperand(0), N1.getOperand(0),
8252 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8253 /// ARMISD::VMOVRRD.
8254 static SDValue PerformVMOVRRDCombine(SDNode *N,
8255 TargetLowering::DAGCombinerInfo &DCI) {
8256 // vmovrrd(vmovdrr x, y) -> x,y
8257 SDValue InDouble = N->getOperand(0);
8258 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8259 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8261 // vmovrrd(load f64) -> (load i32), (load i32)
8262 SDNode *InNode = InDouble.getNode();
8263 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8264 InNode->getValueType(0) == MVT::f64 &&
8265 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8266 !cast<LoadSDNode>(InNode)->isVolatile()) {
8267 // TODO: Should this be done for non-FrameIndex operands?
8268 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8270 SelectionDAG &DAG = DCI.DAG;
8271 DebugLoc DL = LD->getDebugLoc();
8272 SDValue BasePtr = LD->getBasePtr();
8273 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8274 LD->getPointerInfo(), LD->isVolatile(),
8275 LD->isNonTemporal(), LD->isInvariant(),
8276 LD->getAlignment());
8278 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8279 DAG.getConstant(4, MVT::i32));
8280 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8281 LD->getPointerInfo(), LD->isVolatile(),
8282 LD->isNonTemporal(), LD->isInvariant(),
8283 std::min(4U, LD->getAlignment() / 2));
8285 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8286 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8287 DCI.RemoveFromWorklist(LD);
8295 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8296 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8297 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8298 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8299 SDValue Op0 = N->getOperand(0);
8300 SDValue Op1 = N->getOperand(1);
8301 if (Op0.getOpcode() == ISD::BITCAST)
8302 Op0 = Op0.getOperand(0);
8303 if (Op1.getOpcode() == ISD::BITCAST)
8304 Op1 = Op1.getOperand(0);
8305 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8306 Op0.getNode() == Op1.getNode() &&
8307 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8308 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8309 N->getValueType(0), Op0.getOperand(0));
8313 /// PerformSTORECombine - Target-specific dag combine xforms for
8315 static SDValue PerformSTORECombine(SDNode *N,
8316 TargetLowering::DAGCombinerInfo &DCI) {
8317 StoreSDNode *St = cast<StoreSDNode>(N);
8318 if (St->isVolatile())
8321 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8322 // pack all of the elements in one place. Next, store to memory in fewer
8324 SDValue StVal = St->getValue();
8325 EVT VT = StVal.getValueType();
8326 if (St->isTruncatingStore() && VT.isVector()) {
8327 SelectionDAG &DAG = DCI.DAG;
8328 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8329 EVT StVT = St->getMemoryVT();
8330 unsigned NumElems = VT.getVectorNumElements();
8331 assert(StVT != VT && "Cannot truncate to the same type");
8332 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8333 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8335 // From, To sizes and ElemCount must be pow of two
8336 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8338 // We are going to use the original vector elt for storing.
8339 // Accumulated smaller vector elements must be a multiple of the store size.
8340 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8342 unsigned SizeRatio = FromEltSz / ToEltSz;
8343 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8345 // Create a type on which we perform the shuffle.
8346 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8347 NumElems*SizeRatio);
8348 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8350 DebugLoc DL = St->getDebugLoc();
8351 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8352 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8353 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8355 // Can't shuffle using an illegal type.
8356 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8358 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8359 DAG.getUNDEF(WideVec.getValueType()),
8361 // At this point all of the data is stored at the bottom of the
8362 // register. We now need to save it to mem.
8364 // Find the largest store unit
8365 MVT StoreType = MVT::i8;
8366 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8367 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8368 MVT Tp = (MVT::SimpleValueType)tp;
8369 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8372 // Didn't find a legal store type.
8373 if (!TLI.isTypeLegal(StoreType))
8376 // Bitcast the original vector into a vector of store-size units
8377 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8378 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8379 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8380 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8381 SmallVector<SDValue, 8> Chains;
8382 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8383 TLI.getPointerTy());
8384 SDValue BasePtr = St->getBasePtr();
8386 // Perform one or more big stores into memory.
8387 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8388 for (unsigned I = 0; I < E; I++) {
8389 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8390 StoreType, ShuffWide,
8391 DAG.getIntPtrConstant(I));
8392 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8393 St->getPointerInfo(), St->isVolatile(),
8394 St->isNonTemporal(), St->getAlignment());
8395 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8397 Chains.push_back(Ch);
8399 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8403 if (!ISD::isNormalStore(St))
8406 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8407 // ARM stores of arguments in the same cache line.
8408 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8409 StVal.getNode()->hasOneUse()) {
8410 SelectionDAG &DAG = DCI.DAG;
8411 DebugLoc DL = St->getDebugLoc();
8412 SDValue BasePtr = St->getBasePtr();
8413 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8414 StVal.getNode()->getOperand(0), BasePtr,
8415 St->getPointerInfo(), St->isVolatile(),
8416 St->isNonTemporal(), St->getAlignment());
8418 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8419 DAG.getConstant(4, MVT::i32));
8420 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8421 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8422 St->isNonTemporal(),
8423 std::min(4U, St->getAlignment() / 2));
8426 if (StVal.getValueType() != MVT::i64 ||
8427 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8430 // Bitcast an i64 store extracted from a vector to f64.
8431 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8432 SelectionDAG &DAG = DCI.DAG;
8433 DebugLoc dl = StVal.getDebugLoc();
8434 SDValue IntVec = StVal.getOperand(0);
8435 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8436 IntVec.getValueType().getVectorNumElements());
8437 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8438 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8439 Vec, StVal.getOperand(1));
8440 dl = N->getDebugLoc();
8441 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8442 // Make the DAGCombiner fold the bitcasts.
8443 DCI.AddToWorklist(Vec.getNode());
8444 DCI.AddToWorklist(ExtElt.getNode());
8445 DCI.AddToWorklist(V.getNode());
8446 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8447 St->getPointerInfo(), St->isVolatile(),
8448 St->isNonTemporal(), St->getAlignment(),
8452 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8453 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8454 /// i64 vector to have f64 elements, since the value can then be loaded
8455 /// directly into a VFP register.
8456 static bool hasNormalLoadOperand(SDNode *N) {
8457 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8458 for (unsigned i = 0; i < NumElts; ++i) {
8459 SDNode *Elt = N->getOperand(i).getNode();
8460 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8466 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8467 /// ISD::BUILD_VECTOR.
8468 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8469 TargetLowering::DAGCombinerInfo &DCI){
8470 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8471 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8472 // into a pair of GPRs, which is fine when the value is used as a scalar,
8473 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8474 SelectionDAG &DAG = DCI.DAG;
8475 if (N->getNumOperands() == 2) {
8476 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8481 // Load i64 elements as f64 values so that type legalization does not split
8482 // them up into i32 values.
8483 EVT VT = N->getValueType(0);
8484 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8486 DebugLoc dl = N->getDebugLoc();
8487 SmallVector<SDValue, 8> Ops;
8488 unsigned NumElts = VT.getVectorNumElements();
8489 for (unsigned i = 0; i < NumElts; ++i) {
8490 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8492 // Make the DAGCombiner fold the bitcast.
8493 DCI.AddToWorklist(V.getNode());
8495 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8496 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8497 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8500 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8501 /// ISD::INSERT_VECTOR_ELT.
8502 static SDValue PerformInsertEltCombine(SDNode *N,
8503 TargetLowering::DAGCombinerInfo &DCI) {
8504 // Bitcast an i64 load inserted into a vector to f64.
8505 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8506 EVT VT = N->getValueType(0);
8507 SDNode *Elt = N->getOperand(1).getNode();
8508 if (VT.getVectorElementType() != MVT::i64 ||
8509 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8512 SelectionDAG &DAG = DCI.DAG;
8513 DebugLoc dl = N->getDebugLoc();
8514 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8515 VT.getVectorNumElements());
8516 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8517 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8518 // Make the DAGCombiner fold the bitcasts.
8519 DCI.AddToWorklist(Vec.getNode());
8520 DCI.AddToWorklist(V.getNode());
8521 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8522 Vec, V, N->getOperand(2));
8523 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8526 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8527 /// ISD::VECTOR_SHUFFLE.
8528 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8529 // The LLVM shufflevector instruction does not require the shuffle mask
8530 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8531 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8532 // operands do not match the mask length, they are extended by concatenating
8533 // them with undef vectors. That is probably the right thing for other
8534 // targets, but for NEON it is better to concatenate two double-register
8535 // size vector operands into a single quad-register size vector. Do that
8536 // transformation here:
8537 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8538 // shuffle(concat(v1, v2), undef)
8539 SDValue Op0 = N->getOperand(0);
8540 SDValue Op1 = N->getOperand(1);
8541 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8542 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8543 Op0.getNumOperands() != 2 ||
8544 Op1.getNumOperands() != 2)
8546 SDValue Concat0Op1 = Op0.getOperand(1);
8547 SDValue Concat1Op1 = Op1.getOperand(1);
8548 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8549 Concat1Op1.getOpcode() != ISD::UNDEF)
8551 // Skip the transformation if any of the types are illegal.
8552 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8553 EVT VT = N->getValueType(0);
8554 if (!TLI.isTypeLegal(VT) ||
8555 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8556 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8559 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8560 Op0.getOperand(0), Op1.getOperand(0));
8561 // Translate the shuffle mask.
8562 SmallVector<int, 16> NewMask;
8563 unsigned NumElts = VT.getVectorNumElements();
8564 unsigned HalfElts = NumElts/2;
8565 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8566 for (unsigned n = 0; n < NumElts; ++n) {
8567 int MaskElt = SVN->getMaskElt(n);
8569 if (MaskElt < (int)HalfElts)
8571 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8572 NewElt = HalfElts + MaskElt - NumElts;
8573 NewMask.push_back(NewElt);
8575 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8576 DAG.getUNDEF(VT), NewMask.data());
8579 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8580 /// NEON load/store intrinsics to merge base address updates.
8581 static SDValue CombineBaseUpdate(SDNode *N,
8582 TargetLowering::DAGCombinerInfo &DCI) {
8583 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8586 SelectionDAG &DAG = DCI.DAG;
8587 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8588 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8589 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8590 SDValue Addr = N->getOperand(AddrOpIdx);
8592 // Search for a use of the address operand that is an increment.
8593 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8594 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8596 if (User->getOpcode() != ISD::ADD ||
8597 UI.getUse().getResNo() != Addr.getResNo())
8600 // Check that the add is independent of the load/store. Otherwise, folding
8601 // it would create a cycle.
8602 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8605 // Find the new opcode for the updating load/store.
8607 bool isLaneOp = false;
8608 unsigned NewOpc = 0;
8609 unsigned NumVecs = 0;
8611 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8613 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8614 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8616 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8618 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8620 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8622 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8623 NumVecs = 2; isLaneOp = true; break;
8624 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8625 NumVecs = 3; isLaneOp = true; break;
8626 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8627 NumVecs = 4; isLaneOp = true; break;
8628 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8629 NumVecs = 1; isLoad = false; break;
8630 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8631 NumVecs = 2; isLoad = false; break;
8632 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8633 NumVecs = 3; isLoad = false; break;
8634 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8635 NumVecs = 4; isLoad = false; break;
8636 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8637 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8638 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8639 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8640 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8641 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8645 switch (N->getOpcode()) {
8646 default: llvm_unreachable("unexpected opcode for Neon base update");
8647 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8648 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8649 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8653 // Find the size of memory referenced by the load/store.
8656 VecTy = N->getValueType(0);
8658 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8659 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8661 NumBytes /= VecTy.getVectorNumElements();
8663 // If the increment is a constant, it must match the memory ref size.
8664 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8665 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8666 uint64_t IncVal = CInc->getZExtValue();
8667 if (IncVal != NumBytes)
8669 } else if (NumBytes >= 3 * 16) {
8670 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8671 // separate instructions that make it harder to use a non-constant update.
8675 // Create the new updating load/store node.
8677 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8679 for (n = 0; n < NumResultVecs; ++n)
8681 Tys[n++] = MVT::i32;
8682 Tys[n] = MVT::Other;
8683 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8684 SmallVector<SDValue, 8> Ops;
8685 Ops.push_back(N->getOperand(0)); // incoming chain
8686 Ops.push_back(N->getOperand(AddrOpIdx));
8688 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8689 Ops.push_back(N->getOperand(i));
8691 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8692 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8693 Ops.data(), Ops.size(),
8694 MemInt->getMemoryVT(),
8695 MemInt->getMemOperand());
8698 std::vector<SDValue> NewResults;
8699 for (unsigned i = 0; i < NumResultVecs; ++i) {
8700 NewResults.push_back(SDValue(UpdN.getNode(), i));
8702 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8703 DCI.CombineTo(N, NewResults);
8704 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8711 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8712 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8713 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8715 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8716 SelectionDAG &DAG = DCI.DAG;
8717 EVT VT = N->getValueType(0);
8718 // vldN-dup instructions only support 64-bit vectors for N > 1.
8719 if (!VT.is64BitVector())
8722 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8723 SDNode *VLD = N->getOperand(0).getNode();
8724 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8726 unsigned NumVecs = 0;
8727 unsigned NewOpc = 0;
8728 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8729 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8731 NewOpc = ARMISD::VLD2DUP;
8732 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8734 NewOpc = ARMISD::VLD3DUP;
8735 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8737 NewOpc = ARMISD::VLD4DUP;
8742 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8743 // numbers match the load.
8744 unsigned VLDLaneNo =
8745 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8746 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8748 // Ignore uses of the chain result.
8749 if (UI.getUse().getResNo() == NumVecs)
8752 if (User->getOpcode() != ARMISD::VDUPLANE ||
8753 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8757 // Create the vldN-dup node.
8760 for (n = 0; n < NumVecs; ++n)
8762 Tys[n] = MVT::Other;
8763 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8764 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8765 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8766 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8767 Ops, 2, VLDMemInt->getMemoryVT(),
8768 VLDMemInt->getMemOperand());
8771 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8773 unsigned ResNo = UI.getUse().getResNo();
8774 // Ignore uses of the chain result.
8775 if (ResNo == NumVecs)
8778 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8781 // Now the vldN-lane intrinsic is dead except for its chain result.
8782 // Update uses of the chain.
8783 std::vector<SDValue> VLDDupResults;
8784 for (unsigned n = 0; n < NumVecs; ++n)
8785 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8786 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8787 DCI.CombineTo(VLD, VLDDupResults);
8792 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8793 /// ARMISD::VDUPLANE.
8794 static SDValue PerformVDUPLANECombine(SDNode *N,
8795 TargetLowering::DAGCombinerInfo &DCI) {
8796 SDValue Op = N->getOperand(0);
8798 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8799 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8800 if (CombineVLDDUP(N, DCI))
8801 return SDValue(N, 0);
8803 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8804 // redundant. Ignore bit_converts for now; element sizes are checked below.
8805 while (Op.getOpcode() == ISD::BITCAST)
8806 Op = Op.getOperand(0);
8807 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8810 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8811 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8812 // The canonical VMOV for a zero vector uses a 32-bit element size.
8813 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8815 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8817 EVT VT = N->getValueType(0);
8818 if (EltSize > VT.getVectorElementType().getSizeInBits())
8821 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8824 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8825 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8826 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8830 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8832 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8837 APFloat APF = C->getValueAPF();
8838 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8839 != APFloat::opOK || !isExact)
8842 c0 = (I == 0) ? cN : c0;
8843 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8850 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8851 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8852 /// when the VMUL has a constant operand that is a power of 2.
8854 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8855 /// vmul.f32 d16, d17, d16
8856 /// vcvt.s32.f32 d16, d16
8858 /// vcvt.s32.f32 d16, d16, #3
8859 static SDValue PerformVCVTCombine(SDNode *N,
8860 TargetLowering::DAGCombinerInfo &DCI,
8861 const ARMSubtarget *Subtarget) {
8862 SelectionDAG &DAG = DCI.DAG;
8863 SDValue Op = N->getOperand(0);
8865 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8866 Op.getOpcode() != ISD::FMUL)
8870 SDValue N0 = Op->getOperand(0);
8871 SDValue ConstVec = Op->getOperand(1);
8872 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8874 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8875 !isConstVecPow2(ConstVec, isSigned, C))
8878 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8879 Intrinsic::arm_neon_vcvtfp2fxu;
8880 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8882 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8883 DAG.getConstant(Log2_64(C), MVT::i32));
8886 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8887 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8888 /// when the VDIV has a constant operand that is a power of 2.
8890 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8891 /// vcvt.f32.s32 d16, d16
8892 /// vdiv.f32 d16, d17, d16
8894 /// vcvt.f32.s32 d16, d16, #3
8895 static SDValue PerformVDIVCombine(SDNode *N,
8896 TargetLowering::DAGCombinerInfo &DCI,
8897 const ARMSubtarget *Subtarget) {
8898 SelectionDAG &DAG = DCI.DAG;
8899 SDValue Op = N->getOperand(0);
8900 unsigned OpOpcode = Op.getNode()->getOpcode();
8902 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8903 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8907 SDValue ConstVec = N->getOperand(1);
8908 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8910 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8911 !isConstVecPow2(ConstVec, isSigned, C))
8914 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8915 Intrinsic::arm_neon_vcvtfxu2fp;
8916 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8918 DAG.getConstant(IntrinsicOpcode, MVT::i32),
8919 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8922 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8923 /// operand of a vector shift operation, where all the elements of the
8924 /// build_vector must have the same constant integer value.
8925 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8926 // Ignore bit_converts.
8927 while (Op.getOpcode() == ISD::BITCAST)
8928 Op = Op.getOperand(0);
8929 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8930 APInt SplatBits, SplatUndef;
8931 unsigned SplatBitSize;
8933 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8934 HasAnyUndefs, ElementBits) ||
8935 SplatBitSize > ElementBits)
8937 Cnt = SplatBits.getSExtValue();
8941 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8942 /// operand of a vector shift left operation. That value must be in the range:
8943 /// 0 <= Value < ElementBits for a left shift; or
8944 /// 0 <= Value <= ElementBits for a long left shift.
8945 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8946 assert(VT.isVector() && "vector shift count is not a vector type");
8947 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8948 if (! getVShiftImm(Op, ElementBits, Cnt))
8950 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8953 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8954 /// operand of a vector shift right operation. For a shift opcode, the value
8955 /// is positive, but for an intrinsic the value count must be negative. The
8956 /// absolute value must be in the range:
8957 /// 1 <= |Value| <= ElementBits for a right shift; or
8958 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8959 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8961 assert(VT.isVector() && "vector shift count is not a vector type");
8962 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8963 if (! getVShiftImm(Op, ElementBits, Cnt))
8967 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8970 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8971 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8972 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8975 // Don't do anything for most intrinsics.
8978 // Vector shifts: check for immediate versions and lower them.
8979 // Note: This is done during DAG combining instead of DAG legalizing because
8980 // the build_vectors for 64-bit vector element shift counts are generally
8981 // not legal, and it is hard to see their values after they get legalized to
8982 // loads from a constant pool.
8983 case Intrinsic::arm_neon_vshifts:
8984 case Intrinsic::arm_neon_vshiftu:
8985 case Intrinsic::arm_neon_vshiftls:
8986 case Intrinsic::arm_neon_vshiftlu:
8987 case Intrinsic::arm_neon_vshiftn:
8988 case Intrinsic::arm_neon_vrshifts:
8989 case Intrinsic::arm_neon_vrshiftu:
8990 case Intrinsic::arm_neon_vrshiftn:
8991 case Intrinsic::arm_neon_vqshifts:
8992 case Intrinsic::arm_neon_vqshiftu:
8993 case Intrinsic::arm_neon_vqshiftsu:
8994 case Intrinsic::arm_neon_vqshiftns:
8995 case Intrinsic::arm_neon_vqshiftnu:
8996 case Intrinsic::arm_neon_vqshiftnsu:
8997 case Intrinsic::arm_neon_vqrshiftns:
8998 case Intrinsic::arm_neon_vqrshiftnu:
8999 case Intrinsic::arm_neon_vqrshiftnsu: {
9000 EVT VT = N->getOperand(1).getValueType();
9002 unsigned VShiftOpc = 0;
9005 case Intrinsic::arm_neon_vshifts:
9006 case Intrinsic::arm_neon_vshiftu:
9007 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9008 VShiftOpc = ARMISD::VSHL;
9011 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9012 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9013 ARMISD::VSHRs : ARMISD::VSHRu);
9018 case Intrinsic::arm_neon_vshiftls:
9019 case Intrinsic::arm_neon_vshiftlu:
9020 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9022 llvm_unreachable("invalid shift count for vshll intrinsic");
9024 case Intrinsic::arm_neon_vrshifts:
9025 case Intrinsic::arm_neon_vrshiftu:
9026 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9030 case Intrinsic::arm_neon_vqshifts:
9031 case Intrinsic::arm_neon_vqshiftu:
9032 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9036 case Intrinsic::arm_neon_vqshiftsu:
9037 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9039 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9041 case Intrinsic::arm_neon_vshiftn:
9042 case Intrinsic::arm_neon_vrshiftn:
9043 case Intrinsic::arm_neon_vqshiftns:
9044 case Intrinsic::arm_neon_vqshiftnu:
9045 case Intrinsic::arm_neon_vqshiftnsu:
9046 case Intrinsic::arm_neon_vqrshiftns:
9047 case Intrinsic::arm_neon_vqrshiftnu:
9048 case Intrinsic::arm_neon_vqrshiftnsu:
9049 // Narrowing shifts require an immediate right shift.
9050 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9052 llvm_unreachable("invalid shift count for narrowing vector shift "
9056 llvm_unreachable("unhandled vector shift");
9060 case Intrinsic::arm_neon_vshifts:
9061 case Intrinsic::arm_neon_vshiftu:
9062 // Opcode already set above.
9064 case Intrinsic::arm_neon_vshiftls:
9065 case Intrinsic::arm_neon_vshiftlu:
9066 if (Cnt == VT.getVectorElementType().getSizeInBits())
9067 VShiftOpc = ARMISD::VSHLLi;
9069 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9070 ARMISD::VSHLLs : ARMISD::VSHLLu);
9072 case Intrinsic::arm_neon_vshiftn:
9073 VShiftOpc = ARMISD::VSHRN; break;
9074 case Intrinsic::arm_neon_vrshifts:
9075 VShiftOpc = ARMISD::VRSHRs; break;
9076 case Intrinsic::arm_neon_vrshiftu:
9077 VShiftOpc = ARMISD::VRSHRu; break;
9078 case Intrinsic::arm_neon_vrshiftn:
9079 VShiftOpc = ARMISD::VRSHRN; break;
9080 case Intrinsic::arm_neon_vqshifts:
9081 VShiftOpc = ARMISD::VQSHLs; break;
9082 case Intrinsic::arm_neon_vqshiftu:
9083 VShiftOpc = ARMISD::VQSHLu; break;
9084 case Intrinsic::arm_neon_vqshiftsu:
9085 VShiftOpc = ARMISD::VQSHLsu; break;
9086 case Intrinsic::arm_neon_vqshiftns:
9087 VShiftOpc = ARMISD::VQSHRNs; break;
9088 case Intrinsic::arm_neon_vqshiftnu:
9089 VShiftOpc = ARMISD::VQSHRNu; break;
9090 case Intrinsic::arm_neon_vqshiftnsu:
9091 VShiftOpc = ARMISD::VQSHRNsu; break;
9092 case Intrinsic::arm_neon_vqrshiftns:
9093 VShiftOpc = ARMISD::VQRSHRNs; break;
9094 case Intrinsic::arm_neon_vqrshiftnu:
9095 VShiftOpc = ARMISD::VQRSHRNu; break;
9096 case Intrinsic::arm_neon_vqrshiftnsu:
9097 VShiftOpc = ARMISD::VQRSHRNsu; break;
9100 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9101 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9104 case Intrinsic::arm_neon_vshiftins: {
9105 EVT VT = N->getOperand(1).getValueType();
9107 unsigned VShiftOpc = 0;
9109 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9110 VShiftOpc = ARMISD::VSLI;
9111 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9112 VShiftOpc = ARMISD::VSRI;
9114 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9117 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9118 N->getOperand(1), N->getOperand(2),
9119 DAG.getConstant(Cnt, MVT::i32));
9122 case Intrinsic::arm_neon_vqrshifts:
9123 case Intrinsic::arm_neon_vqrshiftu:
9124 // No immediate versions of these to check for.
9131 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9132 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9133 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9134 /// vector element shift counts are generally not legal, and it is hard to see
9135 /// their values after they get legalized to loads from a constant pool.
9136 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9137 const ARMSubtarget *ST) {
9138 EVT VT = N->getValueType(0);
9139 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9140 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9141 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9142 SDValue N1 = N->getOperand(1);
9143 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9144 SDValue N0 = N->getOperand(0);
9145 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9146 DAG.MaskedValueIsZero(N0.getOperand(0),
9147 APInt::getHighBitsSet(32, 16)))
9148 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9152 // Nothing to be done for scalar shifts.
9153 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9154 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9157 assert(ST->hasNEON() && "unexpected vector shift");
9160 switch (N->getOpcode()) {
9161 default: llvm_unreachable("unexpected shift opcode");
9164 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9165 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9166 DAG.getConstant(Cnt, MVT::i32));
9171 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9172 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9173 ARMISD::VSHRs : ARMISD::VSHRu);
9174 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9175 DAG.getConstant(Cnt, MVT::i32));
9181 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9182 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9183 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9184 const ARMSubtarget *ST) {
9185 SDValue N0 = N->getOperand(0);
9187 // Check for sign- and zero-extensions of vector extract operations of 8-
9188 // and 16-bit vector elements. NEON supports these directly. They are
9189 // handled during DAG combining because type legalization will promote them
9190 // to 32-bit types and it is messy to recognize the operations after that.
9191 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9192 SDValue Vec = N0.getOperand(0);
9193 SDValue Lane = N0.getOperand(1);
9194 EVT VT = N->getValueType(0);
9195 EVT EltVT = N0.getValueType();
9196 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9198 if (VT == MVT::i32 &&
9199 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9200 TLI.isTypeLegal(Vec.getValueType()) &&
9201 isa<ConstantSDNode>(Lane)) {
9204 switch (N->getOpcode()) {
9205 default: llvm_unreachable("unexpected opcode");
9206 case ISD::SIGN_EXTEND:
9207 Opc = ARMISD::VGETLANEs;
9209 case ISD::ZERO_EXTEND:
9210 case ISD::ANY_EXTEND:
9211 Opc = ARMISD::VGETLANEu;
9214 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9221 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9222 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9223 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9224 const ARMSubtarget *ST) {
9225 // If the target supports NEON, try to use vmax/vmin instructions for f32
9226 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9227 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9228 // a NaN; only do the transformation when it matches that behavior.
9230 // For now only do this when using NEON for FP operations; if using VFP, it
9231 // is not obvious that the benefit outweighs the cost of switching to the
9233 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9234 N->getValueType(0) != MVT::f32)
9237 SDValue CondLHS = N->getOperand(0);
9238 SDValue CondRHS = N->getOperand(1);
9239 SDValue LHS = N->getOperand(2);
9240 SDValue RHS = N->getOperand(3);
9241 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9243 unsigned Opcode = 0;
9245 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9246 IsReversed = false; // x CC y ? x : y
9247 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9248 IsReversed = true ; // x CC y ? y : x
9262 // If LHS is NaN, an ordered comparison will be false and the result will
9263 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9264 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9265 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9266 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9268 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9269 // will return -0, so vmin can only be used for unsafe math or if one of
9270 // the operands is known to be nonzero.
9271 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9272 !DAG.getTarget().Options.UnsafeFPMath &&
9273 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9275 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9284 // If LHS is NaN, an ordered comparison will be false and the result will
9285 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9286 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9287 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9288 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9290 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9291 // will return +0, so vmax can only be used for unsafe math or if one of
9292 // the operands is known to be nonzero.
9293 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9294 !DAG.getTarget().Options.UnsafeFPMath &&
9295 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9297 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9303 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9306 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9308 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9309 SDValue Cmp = N->getOperand(4);
9310 if (Cmp.getOpcode() != ARMISD::CMPZ)
9311 // Only looking at EQ and NE cases.
9314 EVT VT = N->getValueType(0);
9315 DebugLoc dl = N->getDebugLoc();
9316 SDValue LHS = Cmp.getOperand(0);
9317 SDValue RHS = Cmp.getOperand(1);
9318 SDValue FalseVal = N->getOperand(0);
9319 SDValue TrueVal = N->getOperand(1);
9320 SDValue ARMcc = N->getOperand(2);
9321 ARMCC::CondCodes CC =
9322 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9340 /// FIXME: Turn this into a target neutral optimization?
9342 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9343 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9344 N->getOperand(3), Cmp);
9345 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9347 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9348 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9349 N->getOperand(3), NewCmp);
9352 if (Res.getNode()) {
9353 APInt KnownZero, KnownOne;
9354 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9355 // Capture demanded bits information that would be otherwise lost.
9356 if (KnownZero == 0xfffffffe)
9357 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9358 DAG.getValueType(MVT::i1));
9359 else if (KnownZero == 0xffffff00)
9360 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9361 DAG.getValueType(MVT::i8));
9362 else if (KnownZero == 0xffff0000)
9363 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9364 DAG.getValueType(MVT::i16));
9370 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9371 DAGCombinerInfo &DCI) const {
9372 switch (N->getOpcode()) {
9374 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9375 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9376 case ISD::SUB: return PerformSUBCombine(N, DCI);
9377 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9378 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9379 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9380 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9381 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9382 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9383 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9384 case ISD::STORE: return PerformSTORECombine(N, DCI);
9385 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9386 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9387 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9388 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9389 case ISD::FP_TO_SINT:
9390 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9391 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9392 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9395 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9396 case ISD::SIGN_EXTEND:
9397 case ISD::ZERO_EXTEND:
9398 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9399 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9400 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9401 case ARMISD::VLD2DUP:
9402 case ARMISD::VLD3DUP:
9403 case ARMISD::VLD4DUP:
9404 return CombineBaseUpdate(N, DCI);
9405 case ISD::INTRINSIC_VOID:
9406 case ISD::INTRINSIC_W_CHAIN:
9407 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9408 case Intrinsic::arm_neon_vld1:
9409 case Intrinsic::arm_neon_vld2:
9410 case Intrinsic::arm_neon_vld3:
9411 case Intrinsic::arm_neon_vld4:
9412 case Intrinsic::arm_neon_vld2lane:
9413 case Intrinsic::arm_neon_vld3lane:
9414 case Intrinsic::arm_neon_vld4lane:
9415 case Intrinsic::arm_neon_vst1:
9416 case Intrinsic::arm_neon_vst2:
9417 case Intrinsic::arm_neon_vst3:
9418 case Intrinsic::arm_neon_vst4:
9419 case Intrinsic::arm_neon_vst2lane:
9420 case Intrinsic::arm_neon_vst3lane:
9421 case Intrinsic::arm_neon_vst4lane:
9422 return CombineBaseUpdate(N, DCI);
9430 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9432 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9435 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9436 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9437 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9439 switch (VT.getSimpleVT().SimpleTy) {
9445 // Unaligned access can use (for example) LRDB, LRDH, LDR
9446 if (AllowsUnaligned) {
9448 *Fast = Subtarget->hasV7Ops();
9455 // For any little-endian targets with neon, we can support unaligned ld/st
9456 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9457 // A big-endian target may also explictly support unaligned accesses
9458 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9468 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9469 unsigned AlignCheck) {
9470 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9471 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9474 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9475 unsigned DstAlign, unsigned SrcAlign,
9476 bool IsMemset, bool ZeroMemset,
9478 MachineFunction &MF) const {
9479 const Function *F = MF.getFunction();
9481 // See if we can use NEON instructions for this...
9482 if ((!IsMemset || ZeroMemset) &&
9483 Subtarget->hasNEON() &&
9484 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9485 Attribute::NoImplicitFloat)) {
9488 (memOpAlign(SrcAlign, DstAlign, 16) ||
9489 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9491 } else if (Size >= 8 &&
9492 (memOpAlign(SrcAlign, DstAlign, 8) ||
9493 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9498 // Lowering to i32/i16 if the size permits.
9504 // Let the target-independent logic figure it out.
9508 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9509 if (Val.getOpcode() != ISD::LOAD)
9512 EVT VT1 = Val.getValueType();
9513 if (!VT1.isSimple() || !VT1.isInteger() ||
9514 !VT2.isSimple() || !VT2.isInteger())
9517 switch (VT1.getSimpleVT().SimpleTy) {
9522 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9529 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9534 switch (VT.getSimpleVT().SimpleTy) {
9535 default: return false;
9550 if ((V & (Scale - 1)) != 0)
9553 return V == (V & ((1LL << 5) - 1));
9556 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9557 const ARMSubtarget *Subtarget) {
9564 switch (VT.getSimpleVT().SimpleTy) {
9565 default: return false;
9570 // + imm12 or - imm8
9572 return V == (V & ((1LL << 8) - 1));
9573 return V == (V & ((1LL << 12) - 1));
9576 // Same as ARM mode. FIXME: NEON?
9577 if (!Subtarget->hasVFP2())
9582 return V == (V & ((1LL << 8) - 1));
9586 /// isLegalAddressImmediate - Return true if the integer value can be used
9587 /// as the offset of the target addressing mode for load / store of the
9589 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9590 const ARMSubtarget *Subtarget) {
9597 if (Subtarget->isThumb1Only())
9598 return isLegalT1AddressImmediate(V, VT);
9599 else if (Subtarget->isThumb2())
9600 return isLegalT2AddressImmediate(V, VT, Subtarget);
9605 switch (VT.getSimpleVT().SimpleTy) {
9606 default: return false;
9611 return V == (V & ((1LL << 12) - 1));
9614 return V == (V & ((1LL << 8) - 1));
9617 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9622 return V == (V & ((1LL << 8) - 1));
9626 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9628 int Scale = AM.Scale;
9632 switch (VT.getSimpleVT().SimpleTy) {
9633 default: return false;
9642 return Scale == 2 || Scale == 4 || Scale == 8;
9645 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9649 // Note, we allow "void" uses (basically, uses that aren't loads or
9650 // stores), because arm allows folding a scale into many arithmetic
9651 // operations. This should be made more precise and revisited later.
9653 // Allow r << imm, but the imm has to be a multiple of two.
9654 if (Scale & 1) return false;
9655 return isPowerOf2_32(Scale);
9659 /// isLegalAddressingMode - Return true if the addressing mode represented
9660 /// by AM is legal for this target, for a load/store of the specified type.
9661 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9663 EVT VT = getValueType(Ty, true);
9664 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9667 // Can never fold addr of global into load/store.
9672 case 0: // no scale reg, must be "r+i" or "r", or "i".
9675 if (Subtarget->isThumb1Only())
9679 // ARM doesn't support any R+R*scale+imm addr modes.
9686 if (Subtarget->isThumb2())
9687 return isLegalT2ScaledAddressingMode(AM, VT);
9689 int Scale = AM.Scale;
9690 switch (VT.getSimpleVT().SimpleTy) {
9691 default: return false;
9695 if (Scale < 0) Scale = -Scale;
9699 return isPowerOf2_32(Scale & ~1);
9703 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9708 // Note, we allow "void" uses (basically, uses that aren't loads or
9709 // stores), because arm allows folding a scale into many arithmetic
9710 // operations. This should be made more precise and revisited later.
9712 // Allow r << imm, but the imm has to be a multiple of two.
9713 if (Scale & 1) return false;
9714 return isPowerOf2_32(Scale);
9720 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9721 /// icmp immediate, that is the target has icmp instructions which can compare
9722 /// a register against the immediate without having to materialize the
9723 /// immediate into a register.
9724 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9725 // Thumb2 and ARM modes can use cmn for negative immediates.
9726 if (!Subtarget->isThumb())
9727 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9728 if (Subtarget->isThumb2())
9729 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9730 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9731 return Imm >= 0 && Imm <= 255;
9734 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9735 /// *or sub* immediate, that is the target has add or sub instructions which can
9736 /// add a register with the immediate without having to materialize the
9737 /// immediate into a register.
9738 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9739 // Same encoding for add/sub, just flip the sign.
9740 int64_t AbsImm = llvm::abs64(Imm);
9741 if (!Subtarget->isThumb())
9742 return ARM_AM::getSOImmVal(AbsImm) != -1;
9743 if (Subtarget->isThumb2())
9744 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9745 // Thumb1 only has 8-bit unsigned immediate.
9746 return AbsImm >= 0 && AbsImm <= 255;
9749 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9750 bool isSEXTLoad, SDValue &Base,
9751 SDValue &Offset, bool &isInc,
9752 SelectionDAG &DAG) {
9753 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9756 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9758 Base = Ptr->getOperand(0);
9759 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9760 int RHSC = (int)RHS->getZExtValue();
9761 if (RHSC < 0 && RHSC > -256) {
9762 assert(Ptr->getOpcode() == ISD::ADD);
9764 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9768 isInc = (Ptr->getOpcode() == ISD::ADD);
9769 Offset = Ptr->getOperand(1);
9771 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9773 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9774 int RHSC = (int)RHS->getZExtValue();
9775 if (RHSC < 0 && RHSC > -0x1000) {
9776 assert(Ptr->getOpcode() == ISD::ADD);
9778 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9779 Base = Ptr->getOperand(0);
9784 if (Ptr->getOpcode() == ISD::ADD) {
9786 ARM_AM::ShiftOpc ShOpcVal=
9787 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9788 if (ShOpcVal != ARM_AM::no_shift) {
9789 Base = Ptr->getOperand(1);
9790 Offset = Ptr->getOperand(0);
9792 Base = Ptr->getOperand(0);
9793 Offset = Ptr->getOperand(1);
9798 isInc = (Ptr->getOpcode() == ISD::ADD);
9799 Base = Ptr->getOperand(0);
9800 Offset = Ptr->getOperand(1);
9804 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9808 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9809 bool isSEXTLoad, SDValue &Base,
9810 SDValue &Offset, bool &isInc,
9811 SelectionDAG &DAG) {
9812 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9815 Base = Ptr->getOperand(0);
9816 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9817 int RHSC = (int)RHS->getZExtValue();
9818 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9819 assert(Ptr->getOpcode() == ISD::ADD);
9821 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9823 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9824 isInc = Ptr->getOpcode() == ISD::ADD;
9825 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9833 /// getPreIndexedAddressParts - returns true by value, base pointer and
9834 /// offset pointer and addressing mode by reference if the node's address
9835 /// can be legally represented as pre-indexed load / store address.
9837 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9839 ISD::MemIndexedMode &AM,
9840 SelectionDAG &DAG) const {
9841 if (Subtarget->isThumb1Only())
9846 bool isSEXTLoad = false;
9847 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9848 Ptr = LD->getBasePtr();
9849 VT = LD->getMemoryVT();
9850 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9851 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9852 Ptr = ST->getBasePtr();
9853 VT = ST->getMemoryVT();
9858 bool isLegal = false;
9859 if (Subtarget->isThumb2())
9860 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9861 Offset, isInc, DAG);
9863 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9864 Offset, isInc, DAG);
9868 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9872 /// getPostIndexedAddressParts - returns true by value, base pointer and
9873 /// offset pointer and addressing mode by reference if this node can be
9874 /// combined with a load / store to form a post-indexed load / store.
9875 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9878 ISD::MemIndexedMode &AM,
9879 SelectionDAG &DAG) const {
9880 if (Subtarget->isThumb1Only())
9885 bool isSEXTLoad = false;
9886 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9887 VT = LD->getMemoryVT();
9888 Ptr = LD->getBasePtr();
9889 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9890 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9891 VT = ST->getMemoryVT();
9892 Ptr = ST->getBasePtr();
9897 bool isLegal = false;
9898 if (Subtarget->isThumb2())
9899 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9902 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9908 // Swap base ptr and offset to catch more post-index load / store when
9909 // it's legal. In Thumb2 mode, offset must be an immediate.
9910 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9911 !Subtarget->isThumb2())
9912 std::swap(Base, Offset);
9914 // Post-indexed load / store update the base pointer.
9919 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9923 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9926 const SelectionDAG &DAG,
9927 unsigned Depth) const {
9928 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9929 switch (Op.getOpcode()) {
9931 case ARMISD::CMOV: {
9932 // Bits are known zero/one if known on the LHS and RHS.
9933 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9934 if (KnownZero == 0 && KnownOne == 0) return;
9936 APInt KnownZeroRHS, KnownOneRHS;
9937 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9938 KnownZero &= KnownZeroRHS;
9939 KnownOne &= KnownOneRHS;
9945 //===----------------------------------------------------------------------===//
9946 // ARM Inline Assembly Support
9947 //===----------------------------------------------------------------------===//
9949 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9950 // Looking for "rev" which is V6+.
9951 if (!Subtarget->hasV6Ops())
9954 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9955 std::string AsmStr = IA->getAsmString();
9956 SmallVector<StringRef, 4> AsmPieces;
9957 SplitString(AsmStr, AsmPieces, ";\n");
9959 switch (AsmPieces.size()) {
9960 default: return false;
9962 AsmStr = AsmPieces[0];
9964 SplitString(AsmStr, AsmPieces, " \t,");
9967 if (AsmPieces.size() == 3 &&
9968 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9969 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9970 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9971 if (Ty && Ty->getBitWidth() == 32)
9972 return IntrinsicLowering::LowerToByteSwap(CI);
9980 /// getConstraintType - Given a constraint letter, return the type of
9981 /// constraint it is for this target.
9982 ARMTargetLowering::ConstraintType
9983 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9984 if (Constraint.size() == 1) {
9985 switch (Constraint[0]) {
9987 case 'l': return C_RegisterClass;
9988 case 'w': return C_RegisterClass;
9989 case 'h': return C_RegisterClass;
9990 case 'x': return C_RegisterClass;
9991 case 't': return C_RegisterClass;
9992 case 'j': return C_Other; // Constant for movw.
9993 // An address with a single base register. Due to the way we
9994 // currently handle addresses it is the same as an 'r' memory constraint.
9995 case 'Q': return C_Memory;
9997 } else if (Constraint.size() == 2) {
9998 switch (Constraint[0]) {
10000 // All 'U+' constraints are addresses.
10001 case 'U': return C_Memory;
10004 return TargetLowering::getConstraintType(Constraint);
10007 /// Examine constraint type and operand type and determine a weight value.
10008 /// This object must already have been set up with the operand type
10009 /// and the current alternative constraint selected.
10010 TargetLowering::ConstraintWeight
10011 ARMTargetLowering::getSingleConstraintMatchWeight(
10012 AsmOperandInfo &info, const char *constraint) const {
10013 ConstraintWeight weight = CW_Invalid;
10014 Value *CallOperandVal = info.CallOperandVal;
10015 // If we don't have a value, we can't do a match,
10016 // but allow it at the lowest weight.
10017 if (CallOperandVal == NULL)
10019 Type *type = CallOperandVal->getType();
10020 // Look at the constraint type.
10021 switch (*constraint) {
10023 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10026 if (type->isIntegerTy()) {
10027 if (Subtarget->isThumb())
10028 weight = CW_SpecificReg;
10030 weight = CW_Register;
10034 if (type->isFloatingPointTy())
10035 weight = CW_Register;
10041 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10043 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10045 if (Constraint.size() == 1) {
10046 // GCC ARM Constraint Letters
10047 switch (Constraint[0]) {
10048 case 'l': // Low regs or general regs.
10049 if (Subtarget->isThumb())
10050 return RCPair(0U, &ARM::tGPRRegClass);
10051 return RCPair(0U, &ARM::GPRRegClass);
10052 case 'h': // High regs or no regs.
10053 if (Subtarget->isThumb())
10054 return RCPair(0U, &ARM::hGPRRegClass);
10057 return RCPair(0U, &ARM::GPRRegClass);
10059 if (VT == MVT::f32)
10060 return RCPair(0U, &ARM::SPRRegClass);
10061 if (VT.getSizeInBits() == 64)
10062 return RCPair(0U, &ARM::DPRRegClass);
10063 if (VT.getSizeInBits() == 128)
10064 return RCPair(0U, &ARM::QPRRegClass);
10067 if (VT == MVT::f32)
10068 return RCPair(0U, &ARM::SPR_8RegClass);
10069 if (VT.getSizeInBits() == 64)
10070 return RCPair(0U, &ARM::DPR_8RegClass);
10071 if (VT.getSizeInBits() == 128)
10072 return RCPair(0U, &ARM::QPR_8RegClass);
10075 if (VT == MVT::f32)
10076 return RCPair(0U, &ARM::SPRRegClass);
10080 if (StringRef("{cc}").equals_lower(Constraint))
10081 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10083 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10086 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10087 /// vector. If it is invalid, don't add anything to Ops.
10088 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10089 std::string &Constraint,
10090 std::vector<SDValue>&Ops,
10091 SelectionDAG &DAG) const {
10092 SDValue Result(0, 0);
10094 // Currently only support length 1 constraints.
10095 if (Constraint.length() != 1) return;
10097 char ConstraintLetter = Constraint[0];
10098 switch (ConstraintLetter) {
10101 case 'I': case 'J': case 'K': case 'L':
10102 case 'M': case 'N': case 'O':
10103 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10107 int64_t CVal64 = C->getSExtValue();
10108 int CVal = (int) CVal64;
10109 // None of these constraints allow values larger than 32 bits. Check
10110 // that the value fits in an int.
10111 if (CVal != CVal64)
10114 switch (ConstraintLetter) {
10116 // Constant suitable for movw, must be between 0 and
10118 if (Subtarget->hasV6T2Ops())
10119 if (CVal >= 0 && CVal <= 65535)
10123 if (Subtarget->isThumb1Only()) {
10124 // This must be a constant between 0 and 255, for ADD
10126 if (CVal >= 0 && CVal <= 255)
10128 } else if (Subtarget->isThumb2()) {
10129 // A constant that can be used as an immediate value in a
10130 // data-processing instruction.
10131 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10134 // A constant that can be used as an immediate value in a
10135 // data-processing instruction.
10136 if (ARM_AM::getSOImmVal(CVal) != -1)
10142 if (Subtarget->isThumb()) { // FIXME thumb2
10143 // This must be a constant between -255 and -1, for negated ADD
10144 // immediates. This can be used in GCC with an "n" modifier that
10145 // prints the negated value, for use with SUB instructions. It is
10146 // not useful otherwise but is implemented for compatibility.
10147 if (CVal >= -255 && CVal <= -1)
10150 // This must be a constant between -4095 and 4095. It is not clear
10151 // what this constraint is intended for. Implemented for
10152 // compatibility with GCC.
10153 if (CVal >= -4095 && CVal <= 4095)
10159 if (Subtarget->isThumb1Only()) {
10160 // A 32-bit value where only one byte has a nonzero value. Exclude
10161 // zero to match GCC. This constraint is used by GCC internally for
10162 // constants that can be loaded with a move/shift combination.
10163 // It is not useful otherwise but is implemented for compatibility.
10164 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10166 } else if (Subtarget->isThumb2()) {
10167 // A constant whose bitwise inverse can be used as an immediate
10168 // value in a data-processing instruction. This can be used in GCC
10169 // with a "B" modifier that prints the inverted value, for use with
10170 // BIC and MVN instructions. It is not useful otherwise but is
10171 // implemented for compatibility.
10172 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10175 // A constant whose bitwise inverse can be used as an immediate
10176 // value in a data-processing instruction. This can be used in GCC
10177 // with a "B" modifier that prints the inverted value, for use with
10178 // BIC and MVN instructions. It is not useful otherwise but is
10179 // implemented for compatibility.
10180 if (ARM_AM::getSOImmVal(~CVal) != -1)
10186 if (Subtarget->isThumb1Only()) {
10187 // This must be a constant between -7 and 7,
10188 // for 3-operand ADD/SUB immediate instructions.
10189 if (CVal >= -7 && CVal < 7)
10191 } else if (Subtarget->isThumb2()) {
10192 // A constant whose negation can be used as an immediate value in a
10193 // data-processing instruction. This can be used in GCC with an "n"
10194 // modifier that prints the negated value, for use with SUB
10195 // instructions. It is not useful otherwise but is implemented for
10197 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10200 // A constant whose negation can be used as an immediate value in a
10201 // data-processing instruction. This can be used in GCC with an "n"
10202 // modifier that prints the negated value, for use with SUB
10203 // instructions. It is not useful otherwise but is implemented for
10205 if (ARM_AM::getSOImmVal(-CVal) != -1)
10211 if (Subtarget->isThumb()) { // FIXME thumb2
10212 // This must be a multiple of 4 between 0 and 1020, for
10213 // ADD sp + immediate.
10214 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10217 // A power of two or a constant between 0 and 32. This is used in
10218 // GCC for the shift amount on shifted register operands, but it is
10219 // useful in general for any shift amounts.
10220 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10226 if (Subtarget->isThumb()) { // FIXME thumb2
10227 // This must be a constant between 0 and 31, for shift amounts.
10228 if (CVal >= 0 && CVal <= 31)
10234 if (Subtarget->isThumb()) { // FIXME thumb2
10235 // This must be a multiple of 4 between -508 and 508, for
10236 // ADD/SUB sp = sp + immediate.
10237 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10242 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10246 if (Result.getNode()) {
10247 Ops.push_back(Result);
10250 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10254 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10255 // The ARM target isn't yet aware of offsets.
10259 bool ARM::isBitFieldInvertedMask(unsigned v) {
10260 if (v == 0xffffffff)
10262 // there can be 1's on either or both "outsides", all the "inside"
10263 // bits must be 0's
10264 unsigned int lsb = 0, msb = 31;
10265 while (v & (1 << msb)) --msb;
10266 while (v & (1 << lsb)) ++lsb;
10267 for (unsigned int i = lsb; i <= msb; ++i) {
10274 /// isFPImmLegal - Returns true if the target can instruction select the
10275 /// specified FP immediate natively. If false, the legalizer will
10276 /// materialize the FP immediate as a load from a constant pool.
10277 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10278 if (!Subtarget->hasVFP3())
10280 if (VT == MVT::f32)
10281 return ARM_AM::getFP32Imm(Imm) != -1;
10282 if (VT == MVT::f64)
10283 return ARM_AM::getFP64Imm(Imm) != -1;
10287 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10288 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10289 /// specified in the intrinsic calls.
10290 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10292 unsigned Intrinsic) const {
10293 switch (Intrinsic) {
10294 case Intrinsic::arm_neon_vld1:
10295 case Intrinsic::arm_neon_vld2:
10296 case Intrinsic::arm_neon_vld3:
10297 case Intrinsic::arm_neon_vld4:
10298 case Intrinsic::arm_neon_vld2lane:
10299 case Intrinsic::arm_neon_vld3lane:
10300 case Intrinsic::arm_neon_vld4lane: {
10301 Info.opc = ISD::INTRINSIC_W_CHAIN;
10302 // Conservatively set memVT to the entire set of vectors loaded.
10303 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10304 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10305 Info.ptrVal = I.getArgOperand(0);
10307 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10308 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10309 Info.vol = false; // volatile loads with NEON intrinsics not supported
10310 Info.readMem = true;
10311 Info.writeMem = false;
10314 case Intrinsic::arm_neon_vst1:
10315 case Intrinsic::arm_neon_vst2:
10316 case Intrinsic::arm_neon_vst3:
10317 case Intrinsic::arm_neon_vst4:
10318 case Intrinsic::arm_neon_vst2lane:
10319 case Intrinsic::arm_neon_vst3lane:
10320 case Intrinsic::arm_neon_vst4lane: {
10321 Info.opc = ISD::INTRINSIC_VOID;
10322 // Conservatively set memVT to the entire set of vectors stored.
10323 unsigned NumElts = 0;
10324 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10325 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10326 if (!ArgTy->isVectorTy())
10328 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10330 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10331 Info.ptrVal = I.getArgOperand(0);
10333 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10334 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10335 Info.vol = false; // volatile stores with NEON intrinsics not supported
10336 Info.readMem = false;
10337 Info.writeMem = true;
10340 case Intrinsic::arm_strexd: {
10341 Info.opc = ISD::INTRINSIC_W_CHAIN;
10342 Info.memVT = MVT::i64;
10343 Info.ptrVal = I.getArgOperand(2);
10347 Info.readMem = false;
10348 Info.writeMem = true;
10351 case Intrinsic::arm_ldrexd: {
10352 Info.opc = ISD::INTRINSIC_W_CHAIN;
10353 Info.memVT = MVT::i64;
10354 Info.ptrVal = I.getArgOperand(0);
10358 Info.readMem = true;
10359 Info.writeMem = false;