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/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.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::SIGN_EXTEND_INREG, VT, Expand);
126 if (VT.isInteger()) {
127 setOperationAction(ISD::SHL, VT, Custom);
128 setOperationAction(ISD::SRA, VT, Custom);
129 setOperationAction(ISD::SRL, VT, Custom);
132 // Promote all bit-wise operations.
133 if (VT.isInteger() && VT != PromotedBitwiseVT) {
134 setOperationAction(ISD::AND, VT, Promote);
135 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
136 setOperationAction(ISD::OR, VT, Promote);
137 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
138 setOperationAction(ISD::XOR, VT, Promote);
139 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
142 // Neon does not support vector divide/remainder operations.
143 setOperationAction(ISD::SDIV, VT, Expand);
144 setOperationAction(ISD::UDIV, VT, Expand);
145 setOperationAction(ISD::FDIV, VT, Expand);
146 setOperationAction(ISD::SREM, VT, Expand);
147 setOperationAction(ISD::UREM, VT, Expand);
148 setOperationAction(ISD::FREM, VT, Expand);
151 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
152 addRegisterClass(VT, &ARM::DPRRegClass);
153 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
156 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
157 addRegisterClass(VT, &ARM::QPRRegClass);
158 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
161 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
162 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
163 return new TargetLoweringObjectFileMachO();
165 return new ARMElfTargetObjectFile();
168 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
169 : TargetLowering(TM, createTLOF(TM)) {
170 Subtarget = &TM.getSubtarget<ARMSubtarget>();
171 RegInfo = TM.getRegisterInfo();
172 Itins = TM.getInstrItineraryData();
174 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176 if (Subtarget->isTargetDarwin()) {
177 // Uses VFP for Thumb libfuncs if available.
178 if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
179 // Single-precision floating-point arithmetic.
180 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
181 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
182 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
183 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185 // Double-precision floating-point arithmetic.
186 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
187 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
188 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
189 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191 // Single-precision comparisons.
192 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
193 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
194 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
195 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
196 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
197 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
198 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
199 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
201 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
210 // Double-precision comparisons.
211 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
212 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
213 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
214 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
215 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
216 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
217 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
218 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
220 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
229 // Floating-point to integer conversions.
230 // i64 conversions are done via library routines even when generating VFP
231 // instructions, so use the same ones.
232 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
233 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
234 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
235 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237 // Conversions between floating types.
238 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
239 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
241 // Integer to floating-point conversions.
242 // i64 conversions are done via library routines even when generating VFP
243 // instructions, so use the same ones.
244 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
245 // e.g., __floatunsidf vs. __floatunssidfvfp.
246 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
247 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
248 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
249 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
253 // These libcalls are not available in 32-bit.
254 setLibcallName(RTLIB::SHL_I128, 0);
255 setLibcallName(RTLIB::SRL_I128, 0);
256 setLibcallName(RTLIB::SRA_I128, 0);
258 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
259 // Double-precision floating-point arithmetic helper functions
260 // RTABI chapter 4.1.2, Table 2
261 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
262 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
263 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
264 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
265 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
266 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
267 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
268 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270 // Double-precision floating-point comparison helper functions
271 // RTABI chapter 4.1.2, Table 3
272 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
273 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
274 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
275 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
276 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
277 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
278 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
279 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
280 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
281 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
282 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
283 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
284 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
285 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
286 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
287 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
288 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
289 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
290 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297 // Single-precision floating-point arithmetic helper functions
298 // RTABI chapter 4.1.2, Table 4
299 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
300 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
301 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
302 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
303 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
304 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
305 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
306 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308 // Single-precision floating-point comparison helper functions
309 // RTABI chapter 4.1.2, Table 5
310 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
311 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
312 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
313 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
314 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
315 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
316 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
317 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
318 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
319 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
320 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
321 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
322 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
323 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
324 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
325 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
326 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
327 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
328 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335 // Floating-point to integer conversions.
336 // RTABI chapter 4.1.2, Table 6
337 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
338 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
339 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
340 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
341 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
342 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
343 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
344 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
345 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
346 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
347 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354 // Conversions between floating types.
355 // RTABI chapter 4.1.2, Table 7
356 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
357 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
358 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
359 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361 // Integer to floating-point conversions.
362 // RTABI chapter 4.1.2, Table 8
363 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
364 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
365 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
366 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
367 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
368 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
369 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
370 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
371 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
372 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380 // Long long helper functions
381 // RTABI chapter 4.2, Table 9
382 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
383 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
384 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
385 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
386 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
387 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
388 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393 // Integer division functions
394 // RTABI chapter 4.3.1
395 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
396 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
397 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
398 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
399 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
400 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
401 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
402 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
403 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
404 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
405 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
413 // RTABI chapter 4.3.4
414 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
415 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
416 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
417 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
418 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
419 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
422 // Use divmod compiler-rt calls for iOS 5.0 and later.
423 if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
424 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
425 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
426 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
429 if (Subtarget->isThumb1Only())
430 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
433 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
434 !Subtarget->isThumb1Only()) {
435 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
436 if (!Subtarget->isFPOnlySP())
437 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
442 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
444 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
445 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
446 setTruncStoreAction((MVT::SimpleValueType)VT,
447 (MVT::SimpleValueType)InnerVT, Expand);
448 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
449 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
453 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455 if (Subtarget->hasNEON()) {
456 addDRTypeForNEON(MVT::v2f32);
457 addDRTypeForNEON(MVT::v8i8);
458 addDRTypeForNEON(MVT::v4i16);
459 addDRTypeForNEON(MVT::v2i32);
460 addDRTypeForNEON(MVT::v1i64);
462 addQRTypeForNEON(MVT::v4f32);
463 addQRTypeForNEON(MVT::v2f64);
464 addQRTypeForNEON(MVT::v16i8);
465 addQRTypeForNEON(MVT::v8i16);
466 addQRTypeForNEON(MVT::v4i32);
467 addQRTypeForNEON(MVT::v2i64);
469 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
470 // neither Neon nor VFP support any arithmetic operations on it.
471 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
472 // supported for v4f32.
473 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
474 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
475 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
476 // FIXME: Code duplication: FDIV and FREM are expanded always, see
477 // ARMTargetLowering::addTypeForNEON method for details.
478 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
479 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
480 // FIXME: Create unittest.
481 // In another words, find a way when "copysign" appears in DAG with vector
483 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
484 // FIXME: Code duplication: SETCC has custom operation action, see
485 // ARMTargetLowering::addTypeForNEON method for details.
486 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
487 // FIXME: Create unittest for FNEG and for FABS.
488 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
489 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
490 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
491 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
492 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
493 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
494 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
495 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
496 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
497 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
498 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
499 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
500 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
501 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
502 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
503 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
504 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
505 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
508 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
509 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
510 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
511 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
512 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
513 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
514 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
515 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
516 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
518 // Neon does not support some operations on v1i64 and v2i64 types.
519 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
520 // Custom handling for some quad-vector types to detect VMULL.
521 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
522 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
523 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
524 // Custom handling for some vector types to avoid expensive expansions
525 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
526 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
527 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
528 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
529 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
530 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
531 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
532 // a destination type that is wider than the source, and nor does
533 // it have a FP_TO_[SU]INT instruction with a narrower destination than
535 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
536 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
537 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
538 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
540 setTargetDAGCombine(ISD::INTRINSIC_VOID);
541 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
542 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
543 setTargetDAGCombine(ISD::SHL);
544 setTargetDAGCombine(ISD::SRL);
545 setTargetDAGCombine(ISD::SRA);
546 setTargetDAGCombine(ISD::SIGN_EXTEND);
547 setTargetDAGCombine(ISD::ZERO_EXTEND);
548 setTargetDAGCombine(ISD::ANY_EXTEND);
549 setTargetDAGCombine(ISD::SELECT_CC);
550 setTargetDAGCombine(ISD::BUILD_VECTOR);
551 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
552 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
553 setTargetDAGCombine(ISD::STORE);
554 setTargetDAGCombine(ISD::FP_TO_SINT);
555 setTargetDAGCombine(ISD::FP_TO_UINT);
556 setTargetDAGCombine(ISD::FDIV);
558 // It is legal to extload from v4i8 to v4i16 or v4i32.
559 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
560 MVT::v4i16, MVT::v2i16,
562 for (unsigned i = 0; i < 6; ++i) {
563 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
564 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
565 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
569 // ARM and Thumb2 support UMLAL/SMLAL.
570 if (!Subtarget->isThumb1Only())
571 setTargetDAGCombine(ISD::ADDC);
574 computeRegisterProperties();
576 // ARM does not have f32 extending load.
577 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
579 // ARM does not have i1 sign extending load.
580 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
582 // ARM supports all 4 flavors of integer indexed load / store.
583 if (!Subtarget->isThumb1Only()) {
584 for (unsigned im = (unsigned)ISD::PRE_INC;
585 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
586 setIndexedLoadAction(im, MVT::i1, Legal);
587 setIndexedLoadAction(im, MVT::i8, Legal);
588 setIndexedLoadAction(im, MVT::i16, Legal);
589 setIndexedLoadAction(im, MVT::i32, Legal);
590 setIndexedStoreAction(im, MVT::i1, Legal);
591 setIndexedStoreAction(im, MVT::i8, Legal);
592 setIndexedStoreAction(im, MVT::i16, Legal);
593 setIndexedStoreAction(im, MVT::i32, Legal);
597 // i64 operation support.
598 setOperationAction(ISD::MUL, MVT::i64, Expand);
599 setOperationAction(ISD::MULHU, MVT::i32, Expand);
600 if (Subtarget->isThumb1Only()) {
601 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
602 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
604 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
605 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
606 setOperationAction(ISD::MULHS, MVT::i32, Expand);
608 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
609 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
610 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
611 setOperationAction(ISD::SRL, MVT::i64, Custom);
612 setOperationAction(ISD::SRA, MVT::i64, Custom);
614 if (!Subtarget->isThumb1Only()) {
615 // FIXME: We should do this for Thumb1 as well.
616 setOperationAction(ISD::ADDC, MVT::i32, Custom);
617 setOperationAction(ISD::ADDE, MVT::i32, Custom);
618 setOperationAction(ISD::SUBC, MVT::i32, Custom);
619 setOperationAction(ISD::SUBE, MVT::i32, Custom);
622 // ARM does not have ROTL.
623 setOperationAction(ISD::ROTL, MVT::i32, Expand);
624 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
625 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
626 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
627 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
629 // These just redirect to CTTZ and CTLZ on ARM.
630 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
631 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
633 // Only ARMv6 has BSWAP.
634 if (!Subtarget->hasV6Ops())
635 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
637 // These are expanded into libcalls.
638 if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
639 // v7M has a hardware divider
640 setOperationAction(ISD::SDIV, MVT::i32, Expand);
641 setOperationAction(ISD::UDIV, MVT::i32, Expand);
643 setOperationAction(ISD::SREM, MVT::i32, Expand);
644 setOperationAction(ISD::UREM, MVT::i32, Expand);
645 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
646 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
648 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
649 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
650 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
651 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
652 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
654 setOperationAction(ISD::TRAP, MVT::Other, Legal);
656 // Use the default implementation.
657 setOperationAction(ISD::VASTART, MVT::Other, Custom);
658 setOperationAction(ISD::VAARG, MVT::Other, Expand);
659 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
660 setOperationAction(ISD::VAEND, MVT::Other, Expand);
661 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
662 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
664 if (!Subtarget->isTargetDarwin()) {
665 // Non-Darwin platforms may return values in these registers via the
666 // personality function.
667 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
668 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
669 setExceptionPointerRegister(ARM::R0);
670 setExceptionSelectorRegister(ARM::R1);
673 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
674 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
675 // the default expansion.
676 // FIXME: This should be checking for v6k, not just v6.
677 if (Subtarget->hasDataBarrier() ||
678 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
679 // membarrier needs custom lowering; the rest are legal and handled
681 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
682 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
683 // Custom lowering for 64-bit ops
684 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
685 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
686 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
687 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
688 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
689 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
690 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
691 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
692 setInsertFencesForAtomic(true);
694 // Set them all for expansion, which will force libcalls.
695 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
696 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
697 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
698 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
699 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
700 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
701 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
702 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
703 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
704 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
705 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
706 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
707 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
708 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
709 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
710 // Unordered/Monotonic case.
711 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
712 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
713 // Since the libcalls include locking, fold in the fences
714 setShouldFoldAtomicFences(true);
717 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
719 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
720 if (!Subtarget->hasV6Ops()) {
721 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
722 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
724 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
726 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
727 !Subtarget->isThumb1Only()) {
728 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
729 // iff target supports vfp2.
730 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
731 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
734 // We want to custom lower some of our intrinsics.
735 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
736 if (Subtarget->isTargetDarwin()) {
737 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
738 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
739 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
742 setOperationAction(ISD::SETCC, MVT::i32, Expand);
743 setOperationAction(ISD::SETCC, MVT::f32, Expand);
744 setOperationAction(ISD::SETCC, MVT::f64, Expand);
745 setOperationAction(ISD::SELECT, MVT::i32, Custom);
746 setOperationAction(ISD::SELECT, MVT::f32, Custom);
747 setOperationAction(ISD::SELECT, MVT::f64, Custom);
748 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
749 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
750 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
752 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
753 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
754 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
755 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
756 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
758 // We don't support sin/cos/fmod/copysign/pow
759 setOperationAction(ISD::FSIN, MVT::f64, Expand);
760 setOperationAction(ISD::FSIN, MVT::f32, Expand);
761 setOperationAction(ISD::FCOS, MVT::f32, Expand);
762 setOperationAction(ISD::FCOS, MVT::f64, Expand);
763 setOperationAction(ISD::FREM, MVT::f64, Expand);
764 setOperationAction(ISD::FREM, MVT::f32, Expand);
765 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
766 !Subtarget->isThumb1Only()) {
767 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
768 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
770 setOperationAction(ISD::FPOW, MVT::f64, Expand);
771 setOperationAction(ISD::FPOW, MVT::f32, Expand);
773 if (!Subtarget->hasVFP4()) {
774 setOperationAction(ISD::FMA, MVT::f64, Expand);
775 setOperationAction(ISD::FMA, MVT::f32, Expand);
778 // Various VFP goodness
779 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
780 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
781 if (Subtarget->hasVFP2()) {
782 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
783 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
784 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
785 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
787 // Special handling for half-precision FP.
788 if (!Subtarget->hasFP16()) {
789 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
790 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
794 // We have target-specific dag combine patterns for the following nodes:
795 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
796 setTargetDAGCombine(ISD::ADD);
797 setTargetDAGCombine(ISD::SUB);
798 setTargetDAGCombine(ISD::MUL);
800 if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
801 setTargetDAGCombine(ISD::AND);
802 setTargetDAGCombine(ISD::OR);
803 setTargetDAGCombine(ISD::XOR);
806 if (Subtarget->hasV6Ops())
807 setTargetDAGCombine(ISD::SRL);
809 setStackPointerRegisterToSaveRestore(ARM::SP);
811 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
812 !Subtarget->hasVFP2())
813 setSchedulingPreference(Sched::RegPressure);
815 setSchedulingPreference(Sched::Hybrid);
817 //// temporary - rewrite interface to use type
818 maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
819 maxStoresPerMemset = 16;
820 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
822 // On ARM arguments smaller than 4 bytes are extended, so all arguments
823 // are at least 4 bytes aligned.
824 setMinStackArgumentAlignment(4);
826 benefitFromCodePlacementOpt = true;
828 // Prefer likely predicted branches to selects on out-of-order cores.
829 predictableSelectIsExpensive = Subtarget->isCortexA9();
831 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
834 // FIXME: It might make sense to define the representative register class as the
835 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
836 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
837 // SPR's representative would be DPR_VFP2. This should work well if register
838 // pressure tracking were modified such that a register use would increment the
839 // pressure of the register class's representative and all of it's super
840 // classes' representatives transitively. We have not implemented this because
841 // of the difficulty prior to coalescing of modeling operand register classes
842 // due to the common occurrence of cross class copies and subregister insertions
844 std::pair<const TargetRegisterClass*, uint8_t>
845 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
846 const TargetRegisterClass *RRC = 0;
848 switch (VT.getSimpleVT().SimpleTy) {
850 return TargetLowering::findRepresentativeClass(VT);
851 // Use DPR as representative register class for all floating point
852 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
853 // the cost is 1 for both f32 and f64.
854 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
855 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
856 RRC = &ARM::DPRRegClass;
857 // When NEON is used for SP, only half of the register file is available
858 // because operations that define both SP and DP results will be constrained
859 // to the VFP2 class (D0-D15). We currently model this constraint prior to
860 // coalescing by double-counting the SP regs. See the FIXME above.
861 if (Subtarget->useNEONForSinglePrecisionFP())
864 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
865 case MVT::v4f32: case MVT::v2f64:
866 RRC = &ARM::DPRRegClass;
870 RRC = &ARM::DPRRegClass;
874 RRC = &ARM::DPRRegClass;
878 return std::make_pair(RRC, Cost);
881 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
884 case ARMISD::Wrapper: return "ARMISD::Wrapper";
885 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
886 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
887 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
888 case ARMISD::CALL: return "ARMISD::CALL";
889 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
890 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
891 case ARMISD::tCALL: return "ARMISD::tCALL";
892 case ARMISD::BRCOND: return "ARMISD::BRCOND";
893 case ARMISD::BR_JT: return "ARMISD::BR_JT";
894 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
895 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
896 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
897 case ARMISD::CMP: return "ARMISD::CMP";
898 case ARMISD::CMN: return "ARMISD::CMN";
899 case ARMISD::CMPZ: return "ARMISD::CMPZ";
900 case ARMISD::CMPFP: return "ARMISD::CMPFP";
901 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
902 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
903 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
905 case ARMISD::CMOV: return "ARMISD::CMOV";
907 case ARMISD::RBIT: return "ARMISD::RBIT";
909 case ARMISD::FTOSI: return "ARMISD::FTOSI";
910 case ARMISD::FTOUI: return "ARMISD::FTOUI";
911 case ARMISD::SITOF: return "ARMISD::SITOF";
912 case ARMISD::UITOF: return "ARMISD::UITOF";
914 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
915 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
916 case ARMISD::RRX: return "ARMISD::RRX";
918 case ARMISD::ADDC: return "ARMISD::ADDC";
919 case ARMISD::ADDE: return "ARMISD::ADDE";
920 case ARMISD::SUBC: return "ARMISD::SUBC";
921 case ARMISD::SUBE: return "ARMISD::SUBE";
923 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
924 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
926 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
927 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
929 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
931 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
933 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
935 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
936 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
938 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
940 case ARMISD::VCEQ: return "ARMISD::VCEQ";
941 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
942 case ARMISD::VCGE: return "ARMISD::VCGE";
943 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
944 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
945 case ARMISD::VCGEU: return "ARMISD::VCGEU";
946 case ARMISD::VCGT: return "ARMISD::VCGT";
947 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
948 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
949 case ARMISD::VCGTU: return "ARMISD::VCGTU";
950 case ARMISD::VTST: return "ARMISD::VTST";
952 case ARMISD::VSHL: return "ARMISD::VSHL";
953 case ARMISD::VSHRs: return "ARMISD::VSHRs";
954 case ARMISD::VSHRu: return "ARMISD::VSHRu";
955 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
956 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
957 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
958 case ARMISD::VSHRN: return "ARMISD::VSHRN";
959 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
960 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
961 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
962 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
963 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
964 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
965 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
966 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
967 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
968 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
969 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
970 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
971 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
972 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
973 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
974 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
975 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
976 case ARMISD::VDUP: return "ARMISD::VDUP";
977 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
978 case ARMISD::VEXT: return "ARMISD::VEXT";
979 case ARMISD::VREV64: return "ARMISD::VREV64";
980 case ARMISD::VREV32: return "ARMISD::VREV32";
981 case ARMISD::VREV16: return "ARMISD::VREV16";
982 case ARMISD::VZIP: return "ARMISD::VZIP";
983 case ARMISD::VUZP: return "ARMISD::VUZP";
984 case ARMISD::VTRN: return "ARMISD::VTRN";
985 case ARMISD::VTBL1: return "ARMISD::VTBL1";
986 case ARMISD::VTBL2: return "ARMISD::VTBL2";
987 case ARMISD::VMULLs: return "ARMISD::VMULLs";
988 case ARMISD::VMULLu: return "ARMISD::VMULLu";
989 case ARMISD::UMLAL: return "ARMISD::UMLAL";
990 case ARMISD::SMLAL: return "ARMISD::SMLAL";
991 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
992 case ARMISD::FMAX: return "ARMISD::FMAX";
993 case ARMISD::FMIN: return "ARMISD::FMIN";
994 case ARMISD::BFI: return "ARMISD::BFI";
995 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
996 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
997 case ARMISD::VBSL: return "ARMISD::VBSL";
998 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
999 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1000 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1001 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1002 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1003 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1004 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1005 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1006 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1007 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1008 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1009 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1010 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1011 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1012 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1013 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1014 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1015 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1016 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1017 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1021 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1022 if (!VT.isVector()) return getPointerTy();
1023 return VT.changeVectorElementTypeToInteger();
1026 /// getRegClassFor - Return the register class that should be used for the
1027 /// specified value type.
1028 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1029 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1030 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1031 // load / store 4 to 8 consecutive D registers.
1032 if (Subtarget->hasNEON()) {
1033 if (VT == MVT::v4i64)
1034 return &ARM::QQPRRegClass;
1035 if (VT == MVT::v8i64)
1036 return &ARM::QQQQPRRegClass;
1038 return TargetLowering::getRegClassFor(VT);
1041 // Create a fast isel object.
1043 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1044 const TargetLibraryInfo *libInfo) const {
1045 return ARM::createFastISel(funcInfo, libInfo);
1048 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1049 /// be used for loads / stores from the global.
1050 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1051 return (Subtarget->isThumb1Only() ? 127 : 4095);
1054 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1055 unsigned NumVals = N->getNumValues();
1057 return Sched::RegPressure;
1059 for (unsigned i = 0; i != NumVals; ++i) {
1060 EVT VT = N->getValueType(i);
1061 if (VT == MVT::Glue || VT == MVT::Other)
1063 if (VT.isFloatingPoint() || VT.isVector())
1067 if (!N->isMachineOpcode())
1068 return Sched::RegPressure;
1070 // Load are scheduled for latency even if there instruction itinerary
1071 // is not available.
1072 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1073 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1075 if (MCID.getNumDefs() == 0)
1076 return Sched::RegPressure;
1077 if (!Itins->isEmpty() &&
1078 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1081 return Sched::RegPressure;
1084 //===----------------------------------------------------------------------===//
1086 //===----------------------------------------------------------------------===//
1088 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1089 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1091 default: llvm_unreachable("Unknown condition code!");
1092 case ISD::SETNE: return ARMCC::NE;
1093 case ISD::SETEQ: return ARMCC::EQ;
1094 case ISD::SETGT: return ARMCC::GT;
1095 case ISD::SETGE: return ARMCC::GE;
1096 case ISD::SETLT: return ARMCC::LT;
1097 case ISD::SETLE: return ARMCC::LE;
1098 case ISD::SETUGT: return ARMCC::HI;
1099 case ISD::SETUGE: return ARMCC::HS;
1100 case ISD::SETULT: return ARMCC::LO;
1101 case ISD::SETULE: return ARMCC::LS;
1105 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1106 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1107 ARMCC::CondCodes &CondCode2) {
1108 CondCode2 = ARMCC::AL;
1110 default: llvm_unreachable("Unknown FP condition!");
1112 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1114 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1116 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1117 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1118 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1119 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1120 case ISD::SETO: CondCode = ARMCC::VC; break;
1121 case ISD::SETUO: CondCode = ARMCC::VS; break;
1122 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1123 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1124 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1126 case ISD::SETULT: CondCode = ARMCC::LT; break;
1128 case ISD::SETULE: CondCode = ARMCC::LE; break;
1130 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1134 //===----------------------------------------------------------------------===//
1135 // Calling Convention Implementation
1136 //===----------------------------------------------------------------------===//
1138 #include "ARMGenCallingConv.inc"
1140 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1141 /// given CallingConvention value.
1142 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1144 bool isVarArg) const {
1147 llvm_unreachable("Unsupported calling convention");
1148 case CallingConv::Fast:
1149 if (Subtarget->hasVFP2() && !isVarArg) {
1150 if (!Subtarget->isAAPCS_ABI())
1151 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1152 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1153 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1156 case CallingConv::C: {
1157 // Use target triple & subtarget features to do actual dispatch.
1158 if (!Subtarget->isAAPCS_ABI())
1159 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1160 else if (Subtarget->hasVFP2() &&
1161 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1163 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1164 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1166 case CallingConv::ARM_AAPCS_VFP:
1168 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1170 case CallingConv::ARM_AAPCS:
1171 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1172 case CallingConv::ARM_APCS:
1173 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1174 case CallingConv::GHC:
1175 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1179 /// LowerCallResult - Lower the result values of a call into the
1180 /// appropriate copies out of appropriate physical registers.
1182 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1183 CallingConv::ID CallConv, bool isVarArg,
1184 const SmallVectorImpl<ISD::InputArg> &Ins,
1185 DebugLoc dl, SelectionDAG &DAG,
1186 SmallVectorImpl<SDValue> &InVals) const {
1188 // Assign locations to each value returned by this call.
1189 SmallVector<CCValAssign, 16> RVLocs;
1190 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1191 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1192 CCInfo.AnalyzeCallResult(Ins,
1193 CCAssignFnForNode(CallConv, /* Return*/ true,
1196 // Copy all of the result registers out of their specified physreg.
1197 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1198 CCValAssign VA = RVLocs[i];
1201 if (VA.needsCustom()) {
1202 // Handle f64 or half of a v2f64.
1203 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1205 Chain = Lo.getValue(1);
1206 InFlag = Lo.getValue(2);
1207 VA = RVLocs[++i]; // skip ahead to next loc
1208 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1210 Chain = Hi.getValue(1);
1211 InFlag = Hi.getValue(2);
1212 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1214 if (VA.getLocVT() == MVT::v2f64) {
1215 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1216 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1217 DAG.getConstant(0, MVT::i32));
1219 VA = RVLocs[++i]; // skip ahead to next loc
1220 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1221 Chain = Lo.getValue(1);
1222 InFlag = Lo.getValue(2);
1223 VA = RVLocs[++i]; // skip ahead to next loc
1224 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1225 Chain = Hi.getValue(1);
1226 InFlag = Hi.getValue(2);
1227 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1228 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1229 DAG.getConstant(1, MVT::i32));
1232 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1234 Chain = Val.getValue(1);
1235 InFlag = Val.getValue(2);
1238 switch (VA.getLocInfo()) {
1239 default: llvm_unreachable("Unknown loc info!");
1240 case CCValAssign::Full: break;
1241 case CCValAssign::BCvt:
1242 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1246 InVals.push_back(Val);
1252 /// LowerMemOpCallTo - Store the argument to the stack.
1254 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1255 SDValue StackPtr, SDValue Arg,
1256 DebugLoc dl, SelectionDAG &DAG,
1257 const CCValAssign &VA,
1258 ISD::ArgFlagsTy Flags) const {
1259 unsigned LocMemOffset = VA.getLocMemOffset();
1260 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1261 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1262 return DAG.getStore(Chain, dl, Arg, PtrOff,
1263 MachinePointerInfo::getStack(LocMemOffset),
1267 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1268 SDValue Chain, SDValue &Arg,
1269 RegsToPassVector &RegsToPass,
1270 CCValAssign &VA, CCValAssign &NextVA,
1272 SmallVector<SDValue, 8> &MemOpChains,
1273 ISD::ArgFlagsTy Flags) const {
1275 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1276 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1277 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1279 if (NextVA.isRegLoc())
1280 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1282 assert(NextVA.isMemLoc());
1283 if (StackPtr.getNode() == 0)
1284 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1286 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1292 /// LowerCall - Lowering a call into a callseq_start <-
1293 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1296 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1297 SmallVectorImpl<SDValue> &InVals) const {
1298 SelectionDAG &DAG = CLI.DAG;
1299 DebugLoc &dl = CLI.DL;
1300 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1301 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1302 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1303 SDValue Chain = CLI.Chain;
1304 SDValue Callee = CLI.Callee;
1305 bool &isTailCall = CLI.IsTailCall;
1306 CallingConv::ID CallConv = CLI.CallConv;
1307 bool doesNotRet = CLI.DoesNotReturn;
1308 bool isVarArg = CLI.IsVarArg;
1310 MachineFunction &MF = DAG.getMachineFunction();
1311 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1312 bool IsSibCall = false;
1313 // Disable tail calls if they're not supported.
1314 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1317 // Check if it's really possible to do a tail call.
1318 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1319 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1320 Outs, OutVals, Ins, DAG);
1321 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1322 // detected sibcalls.
1329 // Analyze operands of the call, assigning locations to each operand.
1330 SmallVector<CCValAssign, 16> ArgLocs;
1331 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1332 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1333 CCInfo.AnalyzeCallOperands(Outs,
1334 CCAssignFnForNode(CallConv, /* Return*/ false,
1337 // Get a count of how many bytes are to be pushed on the stack.
1338 unsigned NumBytes = CCInfo.getNextStackOffset();
1340 // For tail calls, memory operands are available in our caller's stack.
1344 // Adjust the stack pointer for the new arguments...
1345 // These operations are automatically eliminated by the prolog/epilog pass
1347 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1349 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1351 RegsToPassVector RegsToPass;
1352 SmallVector<SDValue, 8> MemOpChains;
1354 // Walk the register/memloc assignments, inserting copies/loads. In the case
1355 // of tail call optimization, arguments are handled later.
1356 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1358 ++i, ++realArgIdx) {
1359 CCValAssign &VA = ArgLocs[i];
1360 SDValue Arg = OutVals[realArgIdx];
1361 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1362 bool isByVal = Flags.isByVal();
1364 // Promote the value if needed.
1365 switch (VA.getLocInfo()) {
1366 default: llvm_unreachable("Unknown loc info!");
1367 case CCValAssign::Full: break;
1368 case CCValAssign::SExt:
1369 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1371 case CCValAssign::ZExt:
1372 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1374 case CCValAssign::AExt:
1375 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1377 case CCValAssign::BCvt:
1378 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1382 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1383 if (VA.needsCustom()) {
1384 if (VA.getLocVT() == MVT::v2f64) {
1385 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1386 DAG.getConstant(0, MVT::i32));
1387 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1388 DAG.getConstant(1, MVT::i32));
1390 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1391 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1393 VA = ArgLocs[++i]; // skip ahead to next loc
1394 if (VA.isRegLoc()) {
1395 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1396 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1398 assert(VA.isMemLoc());
1400 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1401 dl, DAG, VA, Flags));
1404 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1405 StackPtr, MemOpChains, Flags);
1407 } else if (VA.isRegLoc()) {
1408 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1409 } else if (isByVal) {
1410 assert(VA.isMemLoc());
1411 unsigned offset = 0;
1413 // True if this byval aggregate will be split between registers
1415 if (CCInfo.isFirstByValRegValid()) {
1416 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1418 for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1419 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1420 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1421 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1422 MachinePointerInfo(),
1423 false, false, false, 0);
1424 MemOpChains.push_back(Load.getValue(1));
1425 RegsToPass.push_back(std::make_pair(j, Load));
1427 offset = ARM::R4 - CCInfo.getFirstByValReg();
1428 CCInfo.clearFirstByValReg();
1431 if (Flags.getByValSize() - 4*offset > 0) {
1432 unsigned LocMemOffset = VA.getLocMemOffset();
1433 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1434 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1436 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1437 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1438 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1440 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1442 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1443 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1444 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1445 Ops, array_lengthof(Ops)));
1447 } else if (!IsSibCall) {
1448 assert(VA.isMemLoc());
1450 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1451 dl, DAG, VA, Flags));
1455 if (!MemOpChains.empty())
1456 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1457 &MemOpChains[0], MemOpChains.size());
1459 // Build a sequence of copy-to-reg nodes chained together with token chain
1460 // and flag operands which copy the outgoing args into the appropriate regs.
1462 // Tail call byval lowering might overwrite argument registers so in case of
1463 // tail call optimization the copies to registers are lowered later.
1465 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1466 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1467 RegsToPass[i].second, InFlag);
1468 InFlag = Chain.getValue(1);
1471 // For tail calls lower the arguments to the 'real' stack slot.
1473 // Force all the incoming stack arguments to be loaded from the stack
1474 // before any new outgoing arguments are stored to the stack, because the
1475 // outgoing stack slots may alias the incoming argument stack slots, and
1476 // the alias isn't otherwise explicit. This is slightly more conservative
1477 // than necessary, because it means that each store effectively depends
1478 // on every argument instead of just those arguments it would clobber.
1480 // Do not flag preceding copytoreg stuff together with the following stuff.
1482 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1483 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1484 RegsToPass[i].second, InFlag);
1485 InFlag = Chain.getValue(1);
1490 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1491 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1492 // node so that legalize doesn't hack it.
1493 bool isDirect = false;
1494 bool isARMFunc = false;
1495 bool isLocalARMFunc = false;
1496 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1498 if (EnableARMLongCalls) {
1499 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1500 && "long-calls with non-static relocation model!");
1501 // Handle a global address or an external symbol. If it's not one of
1502 // those, the target's already in a register, so we don't need to do
1504 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1505 const GlobalValue *GV = G->getGlobal();
1506 // Create a constant pool entry for the callee address
1507 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1508 ARMConstantPoolValue *CPV =
1509 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1511 // Get the address of the callee into a register
1512 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1513 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1514 Callee = DAG.getLoad(getPointerTy(), dl,
1515 DAG.getEntryNode(), CPAddr,
1516 MachinePointerInfo::getConstantPool(),
1517 false, false, false, 0);
1518 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1519 const char *Sym = S->getSymbol();
1521 // Create a constant pool entry for the callee address
1522 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1523 ARMConstantPoolValue *CPV =
1524 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1525 ARMPCLabelIndex, 0);
1526 // Get the address of the callee into a register
1527 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1528 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1529 Callee = DAG.getLoad(getPointerTy(), dl,
1530 DAG.getEntryNode(), CPAddr,
1531 MachinePointerInfo::getConstantPool(),
1532 false, false, false, 0);
1534 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1535 const GlobalValue *GV = G->getGlobal();
1537 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1538 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1539 getTargetMachine().getRelocationModel() != Reloc::Static;
1540 isARMFunc = !Subtarget->isThumb() || isStub;
1541 // ARM call to a local ARM function is predicable.
1542 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1543 // tBX takes a register source operand.
1544 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1545 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1546 ARMConstantPoolValue *CPV =
1547 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1548 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1549 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1550 Callee = DAG.getLoad(getPointerTy(), dl,
1551 DAG.getEntryNode(), CPAddr,
1552 MachinePointerInfo::getConstantPool(),
1553 false, false, false, 0);
1554 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1555 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1556 getPointerTy(), Callee, PICLabel);
1558 // On ELF targets for PIC code, direct calls should go through the PLT
1559 unsigned OpFlags = 0;
1560 if (Subtarget->isTargetELF() &&
1561 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1562 OpFlags = ARMII::MO_PLT;
1563 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1565 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1567 bool isStub = Subtarget->isTargetDarwin() &&
1568 getTargetMachine().getRelocationModel() != Reloc::Static;
1569 isARMFunc = !Subtarget->isThumb() || isStub;
1570 // tBX takes a register source operand.
1571 const char *Sym = S->getSymbol();
1572 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1573 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1574 ARMConstantPoolValue *CPV =
1575 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1576 ARMPCLabelIndex, 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 unsigned OpFlags = 0;
1588 // On ELF targets for PIC code, direct calls should go through the PLT
1589 if (Subtarget->isTargetELF() &&
1590 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1591 OpFlags = ARMII::MO_PLT;
1592 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1596 // FIXME: handle tail calls differently.
1598 if (Subtarget->isThumb()) {
1599 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1600 CallOpc = ARMISD::CALL_NOLINK;
1601 else if (doesNotRet && isDirect && !isARMFunc &&
1602 Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1603 // "mov lr, pc; b _foo" to avoid confusing the RSP
1604 CallOpc = ARMISD::CALL_NOLINK;
1606 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1608 if (!isDirect && !Subtarget->hasV5TOps()) {
1609 CallOpc = ARMISD::CALL_NOLINK;
1610 } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1611 // "mov lr, pc; b _foo" to avoid confusing the RSP
1612 CallOpc = ARMISD::CALL_NOLINK;
1614 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1617 std::vector<SDValue> Ops;
1618 Ops.push_back(Chain);
1619 Ops.push_back(Callee);
1621 // Add argument registers to the end of the list so that they are known live
1623 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1624 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1625 RegsToPass[i].second.getValueType()));
1627 // Add a register mask operand representing the call-preserved registers.
1628 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1629 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1630 assert(Mask && "Missing call preserved mask for calling convention");
1631 Ops.push_back(DAG.getRegisterMask(Mask));
1633 if (InFlag.getNode())
1634 Ops.push_back(InFlag);
1636 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1638 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1640 // Returns a chain and a flag for retval copy to use.
1641 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1642 InFlag = Chain.getValue(1);
1644 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1645 DAG.getIntPtrConstant(0, true), InFlag);
1647 InFlag = Chain.getValue(1);
1649 // Handle result values, copying them out of physregs into vregs that we
1651 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1655 /// HandleByVal - Every parameter *after* a byval parameter is passed
1656 /// on the stack. Remember the next parameter register to allocate,
1657 /// and then confiscate the rest of the parameter registers to insure
1660 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1661 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1662 assert((State->getCallOrPrologue() == Prologue ||
1663 State->getCallOrPrologue() == Call) &&
1664 "unhandled ParmContext");
1665 if ((!State->isFirstByValRegValid()) &&
1666 (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1667 State->setFirstByValReg(reg);
1668 // At a call site, a byval parameter that is split between
1669 // registers and memory needs its size truncated here. In a
1670 // function prologue, such byval parameters are reassembled in
1671 // memory, and are not truncated.
1672 if (State->getCallOrPrologue() == Call) {
1673 unsigned excess = 4 * (ARM::R4 - reg);
1674 assert(size >= excess && "expected larger existing stack allocation");
1678 // Confiscate any remaining parameter registers to preclude their
1679 // assignment to subsequent parameters.
1680 while (State->AllocateReg(GPRArgRegs, 4))
1684 /// MatchingStackOffset - Return true if the given stack call argument is
1685 /// already available in the same position (relatively) of the caller's
1686 /// incoming argument stack.
1688 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1689 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1690 const TargetInstrInfo *TII) {
1691 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1693 if (Arg.getOpcode() == ISD::CopyFromReg) {
1694 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1695 if (!TargetRegisterInfo::isVirtualRegister(VR))
1697 MachineInstr *Def = MRI->getVRegDef(VR);
1700 if (!Flags.isByVal()) {
1701 if (!TII->isLoadFromStackSlot(Def, FI))
1706 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1707 if (Flags.isByVal())
1708 // ByVal argument is passed in as a pointer but it's now being
1709 // dereferenced. e.g.
1710 // define @foo(%struct.X* %A) {
1711 // tail call @bar(%struct.X* byval %A)
1714 SDValue Ptr = Ld->getBasePtr();
1715 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1718 FI = FINode->getIndex();
1722 assert(FI != INT_MAX);
1723 if (!MFI->isFixedObjectIndex(FI))
1725 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1728 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1729 /// for tail call optimization. Targets which want to do tail call
1730 /// optimization should implement this function.
1732 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1733 CallingConv::ID CalleeCC,
1735 bool isCalleeStructRet,
1736 bool isCallerStructRet,
1737 const SmallVectorImpl<ISD::OutputArg> &Outs,
1738 const SmallVectorImpl<SDValue> &OutVals,
1739 const SmallVectorImpl<ISD::InputArg> &Ins,
1740 SelectionDAG& DAG) const {
1741 const Function *CallerF = DAG.getMachineFunction().getFunction();
1742 CallingConv::ID CallerCC = CallerF->getCallingConv();
1743 bool CCMatch = CallerCC == CalleeCC;
1745 // Look for obvious safe cases to perform tail call optimization that do not
1746 // require ABI changes. This is what gcc calls sibcall.
1748 // Do not sibcall optimize vararg calls unless the call site is not passing
1750 if (isVarArg && !Outs.empty())
1753 // Also avoid sibcall optimization if either caller or callee uses struct
1754 // return semantics.
1755 if (isCalleeStructRet || isCallerStructRet)
1758 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1759 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1760 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1761 // support in the assembler and linker to be used. This would need to be
1762 // fixed to fully support tail calls in Thumb1.
1764 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1765 // LR. This means if we need to reload LR, it takes an extra instructions,
1766 // which outweighs the value of the tail call; but here we don't know yet
1767 // whether LR is going to be used. Probably the right approach is to
1768 // generate the tail call here and turn it back into CALL/RET in
1769 // emitEpilogue if LR is used.
1771 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1772 // but we need to make sure there are enough registers; the only valid
1773 // registers are the 4 used for parameters. We don't currently do this
1775 if (Subtarget->isThumb1Only())
1778 // If the calling conventions do not match, then we'd better make sure the
1779 // results are returned in the same way as what the caller expects.
1781 SmallVector<CCValAssign, 16> RVLocs1;
1782 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1783 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1784 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1786 SmallVector<CCValAssign, 16> RVLocs2;
1787 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1788 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1789 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1791 if (RVLocs1.size() != RVLocs2.size())
1793 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1794 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1796 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1798 if (RVLocs1[i].isRegLoc()) {
1799 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1802 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1808 // If the callee takes no arguments then go on to check the results of the
1810 if (!Outs.empty()) {
1811 // Check if stack adjustment is needed. For now, do not do this if any
1812 // argument is passed on the stack.
1813 SmallVector<CCValAssign, 16> ArgLocs;
1814 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1815 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1816 CCInfo.AnalyzeCallOperands(Outs,
1817 CCAssignFnForNode(CalleeCC, false, isVarArg));
1818 if (CCInfo.getNextStackOffset()) {
1819 MachineFunction &MF = DAG.getMachineFunction();
1821 // Check if the arguments are already laid out in the right way as
1822 // the caller's fixed stack objects.
1823 MachineFrameInfo *MFI = MF.getFrameInfo();
1824 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1825 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1826 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1828 ++i, ++realArgIdx) {
1829 CCValAssign &VA = ArgLocs[i];
1830 EVT RegVT = VA.getLocVT();
1831 SDValue Arg = OutVals[realArgIdx];
1832 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1833 if (VA.getLocInfo() == CCValAssign::Indirect)
1835 if (VA.needsCustom()) {
1836 // f64 and vector types are split into multiple registers or
1837 // register/stack-slot combinations. The types will not match
1838 // the registers; give up on memory f64 refs until we figure
1839 // out what to do about this.
1842 if (!ArgLocs[++i].isRegLoc())
1844 if (RegVT == MVT::v2f64) {
1845 if (!ArgLocs[++i].isRegLoc())
1847 if (!ArgLocs[++i].isRegLoc())
1850 } else if (!VA.isRegLoc()) {
1851 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1863 ARMTargetLowering::LowerReturn(SDValue Chain,
1864 CallingConv::ID CallConv, bool isVarArg,
1865 const SmallVectorImpl<ISD::OutputArg> &Outs,
1866 const SmallVectorImpl<SDValue> &OutVals,
1867 DebugLoc dl, SelectionDAG &DAG) const {
1869 // CCValAssign - represent the assignment of the return value to a location.
1870 SmallVector<CCValAssign, 16> RVLocs;
1872 // CCState - Info about the registers and stack slots.
1873 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1874 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1876 // Analyze outgoing return values.
1877 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1880 // If this is the first return lowered for this function, add
1881 // the regs to the liveout set for the function.
1882 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1883 for (unsigned i = 0; i != RVLocs.size(); ++i)
1884 if (RVLocs[i].isRegLoc())
1885 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1890 // Copy the result values into the output registers.
1891 for (unsigned i = 0, realRVLocIdx = 0;
1893 ++i, ++realRVLocIdx) {
1894 CCValAssign &VA = RVLocs[i];
1895 assert(VA.isRegLoc() && "Can only return in registers!");
1897 SDValue Arg = OutVals[realRVLocIdx];
1899 switch (VA.getLocInfo()) {
1900 default: llvm_unreachable("Unknown loc info!");
1901 case CCValAssign::Full: break;
1902 case CCValAssign::BCvt:
1903 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1907 if (VA.needsCustom()) {
1908 if (VA.getLocVT() == MVT::v2f64) {
1909 // Extract the first half and return it in two registers.
1910 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1911 DAG.getConstant(0, MVT::i32));
1912 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1913 DAG.getVTList(MVT::i32, MVT::i32), Half);
1915 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1916 Flag = Chain.getValue(1);
1917 VA = RVLocs[++i]; // skip ahead to next loc
1918 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1919 HalfGPRs.getValue(1), Flag);
1920 Flag = Chain.getValue(1);
1921 VA = RVLocs[++i]; // skip ahead to next loc
1923 // Extract the 2nd half and fall through to handle it as an f64 value.
1924 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1925 DAG.getConstant(1, MVT::i32));
1927 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1929 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1930 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1931 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1932 Flag = Chain.getValue(1);
1933 VA = RVLocs[++i]; // skip ahead to next loc
1934 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1937 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1939 // Guarantee that all emitted copies are
1940 // stuck together, avoiding something bad.
1941 Flag = Chain.getValue(1);
1946 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1948 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1953 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1954 if (N->getNumValues() != 1)
1956 if (!N->hasNUsesOfValue(1, 0))
1959 SDValue TCChain = Chain;
1960 SDNode *Copy = *N->use_begin();
1961 if (Copy->getOpcode() == ISD::CopyToReg) {
1962 // If the copy has a glue operand, we conservatively assume it isn't safe to
1963 // perform a tail call.
1964 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1966 TCChain = Copy->getOperand(0);
1967 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1968 SDNode *VMov = Copy;
1969 // f64 returned in a pair of GPRs.
1970 SmallPtrSet<SDNode*, 2> Copies;
1971 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1973 if (UI->getOpcode() != ISD::CopyToReg)
1977 if (Copies.size() > 2)
1980 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1982 SDValue UseChain = UI->getOperand(0);
1983 if (Copies.count(UseChain.getNode()))
1990 } else if (Copy->getOpcode() == ISD::BITCAST) {
1991 // f32 returned in a single GPR.
1992 if (!Copy->hasOneUse())
1994 Copy = *Copy->use_begin();
1995 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1997 Chain = Copy->getOperand(0);
2002 bool HasRet = false;
2003 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2005 if (UI->getOpcode() != ARMISD::RET_FLAG)
2017 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2018 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2021 if (!CI->isTailCall())
2024 return !Subtarget->isThumb1Only();
2027 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2028 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2029 // one of the above mentioned nodes. It has to be wrapped because otherwise
2030 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2031 // be used to form addressing mode. These wrapped nodes will be selected
2033 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2034 EVT PtrVT = Op.getValueType();
2035 // FIXME there is no actual debug info here
2036 DebugLoc dl = Op.getDebugLoc();
2037 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2039 if (CP->isMachineConstantPoolEntry())
2040 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2041 CP->getAlignment());
2043 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2044 CP->getAlignment());
2045 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2048 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2049 return MachineJumpTableInfo::EK_Inline;
2052 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2053 SelectionDAG &DAG) const {
2054 MachineFunction &MF = DAG.getMachineFunction();
2055 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2056 unsigned ARMPCLabelIndex = 0;
2057 DebugLoc DL = Op.getDebugLoc();
2058 EVT PtrVT = getPointerTy();
2059 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2060 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2062 if (RelocM == Reloc::Static) {
2063 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2065 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2066 ARMPCLabelIndex = AFI->createPICLabelUId();
2067 ARMConstantPoolValue *CPV =
2068 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2069 ARMCP::CPBlockAddress, PCAdj);
2070 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2072 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2073 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2074 MachinePointerInfo::getConstantPool(),
2075 false, false, false, 0);
2076 if (RelocM == Reloc::Static)
2078 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2079 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2082 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2084 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2085 SelectionDAG &DAG) const {
2086 DebugLoc dl = GA->getDebugLoc();
2087 EVT PtrVT = getPointerTy();
2088 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2089 MachineFunction &MF = DAG.getMachineFunction();
2090 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2091 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2092 ARMConstantPoolValue *CPV =
2093 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2094 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2095 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2096 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2097 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2098 MachinePointerInfo::getConstantPool(),
2099 false, false, false, 0);
2100 SDValue Chain = Argument.getValue(1);
2102 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2103 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2105 // call __tls_get_addr.
2108 Entry.Node = Argument;
2109 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2110 Args.push_back(Entry);
2111 // FIXME: is there useful debug info available here?
2112 TargetLowering::CallLoweringInfo CLI(Chain,
2113 (Type *) Type::getInt32Ty(*DAG.getContext()),
2114 false, false, false, false,
2115 0, CallingConv::C, /*isTailCall=*/false,
2116 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2117 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2118 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2119 return CallResult.first;
2122 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2123 // "local exec" model.
2125 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2127 TLSModel::Model model) const {
2128 const GlobalValue *GV = GA->getGlobal();
2129 DebugLoc dl = GA->getDebugLoc();
2131 SDValue Chain = DAG.getEntryNode();
2132 EVT PtrVT = getPointerTy();
2133 // Get the Thread Pointer
2134 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2136 if (model == TLSModel::InitialExec) {
2137 MachineFunction &MF = DAG.getMachineFunction();
2138 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2139 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2140 // Initial exec model.
2141 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2142 ARMConstantPoolValue *CPV =
2143 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2144 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2146 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2147 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2148 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2149 MachinePointerInfo::getConstantPool(),
2150 false, false, false, 0);
2151 Chain = Offset.getValue(1);
2153 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2154 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2156 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2157 MachinePointerInfo::getConstantPool(),
2158 false, false, false, 0);
2161 assert(model == TLSModel::LocalExec);
2162 ARMConstantPoolValue *CPV =
2163 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2164 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2165 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2166 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2167 MachinePointerInfo::getConstantPool(),
2168 false, false, false, 0);
2171 // The address of the thread local variable is the add of the thread
2172 // pointer with the offset of the variable.
2173 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2177 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2178 // TODO: implement the "local dynamic" model
2179 assert(Subtarget->isTargetELF() &&
2180 "TLS not implemented for non-ELF targets");
2181 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2183 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2186 case TLSModel::GeneralDynamic:
2187 case TLSModel::LocalDynamic:
2188 return LowerToTLSGeneralDynamicModel(GA, DAG);
2189 case TLSModel::InitialExec:
2190 case TLSModel::LocalExec:
2191 return LowerToTLSExecModels(GA, DAG, model);
2193 llvm_unreachable("bogus TLS model");
2196 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2197 SelectionDAG &DAG) const {
2198 EVT PtrVT = getPointerTy();
2199 DebugLoc dl = Op.getDebugLoc();
2200 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2201 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2202 if (RelocM == Reloc::PIC_) {
2203 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2204 ARMConstantPoolValue *CPV =
2205 ARMConstantPoolConstant::Create(GV,
2206 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2207 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2208 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2209 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2211 MachinePointerInfo::getConstantPool(),
2212 false, false, false, 0);
2213 SDValue Chain = Result.getValue(1);
2214 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2215 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2217 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2218 MachinePointerInfo::getGOT(),
2219 false, false, false, 0);
2223 // If we have T2 ops, we can materialize the address directly via movt/movw
2224 // pair. This is always cheaper.
2225 if (Subtarget->useMovt()) {
2227 // FIXME: Once remat is capable of dealing with instructions with register
2228 // operands, expand this into two nodes.
2229 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2230 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2232 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2233 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2234 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2235 MachinePointerInfo::getConstantPool(),
2236 false, false, false, 0);
2240 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2241 SelectionDAG &DAG) const {
2242 EVT PtrVT = getPointerTy();
2243 DebugLoc dl = Op.getDebugLoc();
2244 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2245 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2246 MachineFunction &MF = DAG.getMachineFunction();
2247 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2249 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2250 // update ARMFastISel::ARMMaterializeGV.
2251 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2253 // FIXME: Once remat is capable of dealing with instructions with register
2254 // operands, expand this into two nodes.
2255 if (RelocM == Reloc::Static)
2256 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2257 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2259 unsigned Wrapper = (RelocM == Reloc::PIC_)
2260 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2261 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2262 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2263 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2264 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2265 MachinePointerInfo::getGOT(),
2266 false, false, false, 0);
2270 unsigned ARMPCLabelIndex = 0;
2272 if (RelocM == Reloc::Static) {
2273 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2275 ARMPCLabelIndex = AFI->createPICLabelUId();
2276 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2277 ARMConstantPoolValue *CPV =
2278 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2280 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2282 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2284 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2285 MachinePointerInfo::getConstantPool(),
2286 false, false, false, 0);
2287 SDValue Chain = Result.getValue(1);
2289 if (RelocM == Reloc::PIC_) {
2290 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2291 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2294 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2295 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2296 false, false, false, 0);
2301 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2302 SelectionDAG &DAG) const {
2303 assert(Subtarget->isTargetELF() &&
2304 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2305 MachineFunction &MF = DAG.getMachineFunction();
2306 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2307 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2308 EVT PtrVT = getPointerTy();
2309 DebugLoc dl = Op.getDebugLoc();
2310 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2311 ARMConstantPoolValue *CPV =
2312 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2313 ARMPCLabelIndex, PCAdj);
2314 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2315 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2316 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2317 MachinePointerInfo::getConstantPool(),
2318 false, false, false, 0);
2319 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2320 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2324 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2325 DebugLoc dl = Op.getDebugLoc();
2326 SDValue Val = DAG.getConstant(0, MVT::i32);
2327 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2328 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2329 Op.getOperand(1), Val);
2333 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2334 DebugLoc dl = Op.getDebugLoc();
2335 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2336 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2340 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2341 const ARMSubtarget *Subtarget) const {
2342 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2343 DebugLoc dl = Op.getDebugLoc();
2345 default: return SDValue(); // Don't custom lower most intrinsics.
2346 case Intrinsic::arm_thread_pointer: {
2347 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2348 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2350 case Intrinsic::eh_sjlj_lsda: {
2351 MachineFunction &MF = DAG.getMachineFunction();
2352 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2353 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2354 EVT PtrVT = getPointerTy();
2355 DebugLoc dl = Op.getDebugLoc();
2356 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2358 unsigned PCAdj = (RelocM != Reloc::PIC_)
2359 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2360 ARMConstantPoolValue *CPV =
2361 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2362 ARMCP::CPLSDA, PCAdj);
2363 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2364 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2366 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2367 MachinePointerInfo::getConstantPool(),
2368 false, false, false, 0);
2370 if (RelocM == Reloc::PIC_) {
2371 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2372 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2376 case Intrinsic::arm_neon_vmulls:
2377 case Intrinsic::arm_neon_vmullu: {
2378 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2379 ? ARMISD::VMULLs : ARMISD::VMULLu;
2380 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2381 Op.getOperand(1), Op.getOperand(2));
2386 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2387 const ARMSubtarget *Subtarget) {
2388 DebugLoc dl = Op.getDebugLoc();
2389 if (!Subtarget->hasDataBarrier()) {
2390 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2391 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2393 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2394 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2395 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2396 DAG.getConstant(0, MVT::i32));
2399 SDValue Op5 = Op.getOperand(5);
2400 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2401 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2402 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2403 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2405 ARM_MB::MemBOpt DMBOpt;
2406 if (isDeviceBarrier)
2407 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2409 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2410 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2411 DAG.getConstant(DMBOpt, MVT::i32));
2415 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2416 const ARMSubtarget *Subtarget) {
2417 // FIXME: handle "fence singlethread" more efficiently.
2418 DebugLoc dl = Op.getDebugLoc();
2419 if (!Subtarget->hasDataBarrier()) {
2420 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2421 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2423 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2424 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2425 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2426 DAG.getConstant(0, MVT::i32));
2429 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2430 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2433 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2434 const ARMSubtarget *Subtarget) {
2435 // ARM pre v5TE and Thumb1 does not have preload instructions.
2436 if (!(Subtarget->isThumb2() ||
2437 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2438 // Just preserve the chain.
2439 return Op.getOperand(0);
2441 DebugLoc dl = Op.getDebugLoc();
2442 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2444 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2445 // ARMv7 with MP extension has PLDW.
2446 return Op.getOperand(0);
2448 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2449 if (Subtarget->isThumb()) {
2451 isRead = ~isRead & 1;
2452 isData = ~isData & 1;
2455 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2456 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2457 DAG.getConstant(isData, MVT::i32));
2460 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2461 MachineFunction &MF = DAG.getMachineFunction();
2462 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2464 // vastart just stores the address of the VarArgsFrameIndex slot into the
2465 // memory location argument.
2466 DebugLoc dl = Op.getDebugLoc();
2467 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2468 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2469 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2470 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2471 MachinePointerInfo(SV), false, false, 0);
2475 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2476 SDValue &Root, SelectionDAG &DAG,
2477 DebugLoc dl) const {
2478 MachineFunction &MF = DAG.getMachineFunction();
2479 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2481 const TargetRegisterClass *RC;
2482 if (AFI->isThumb1OnlyFunction())
2483 RC = &ARM::tGPRRegClass;
2485 RC = &ARM::GPRRegClass;
2487 // Transform the arguments stored in physical registers into virtual ones.
2488 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2489 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2492 if (NextVA.isMemLoc()) {
2493 MachineFrameInfo *MFI = MF.getFrameInfo();
2494 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2496 // Create load node to retrieve arguments from the stack.
2497 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2498 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2499 MachinePointerInfo::getFixedStack(FI),
2500 false, false, false, 0);
2502 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2503 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2506 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2510 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2511 unsigned &VARegSize, unsigned &VARegSaveSize)
2514 if (CCInfo.isFirstByValRegValid())
2515 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2517 unsigned int firstUnalloced;
2518 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2519 sizeof(GPRArgRegs) /
2520 sizeof(GPRArgRegs[0]));
2521 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2524 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2525 VARegSize = NumGPRs * 4;
2526 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2529 // The remaining GPRs hold either the beginning of variable-argument
2530 // data, or the beginning of an aggregate passed by value (usuall
2531 // byval). Either way, we allocate stack slots adjacent to the data
2532 // provided by our caller, and store the unallocated registers there.
2533 // If this is a variadic function, the va_list pointer will begin with
2534 // these values; otherwise, this reassembles a (byval) structure that
2535 // was split between registers and memory.
2537 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2538 DebugLoc dl, SDValue &Chain,
2539 unsigned ArgOffset) const {
2540 MachineFunction &MF = DAG.getMachineFunction();
2541 MachineFrameInfo *MFI = MF.getFrameInfo();
2542 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2543 unsigned firstRegToSaveIndex;
2544 if (CCInfo.isFirstByValRegValid())
2545 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2547 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2548 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2551 unsigned VARegSize, VARegSaveSize;
2552 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2553 if (VARegSaveSize) {
2554 // If this function is vararg, store any remaining integer argument regs
2555 // to their spots on the stack so that they may be loaded by deferencing
2556 // the result of va_next.
2557 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2558 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2559 ArgOffset + VARegSaveSize
2562 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2565 SmallVector<SDValue, 4> MemOps;
2566 for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2567 const TargetRegisterClass *RC;
2568 if (AFI->isThumb1OnlyFunction())
2569 RC = &ARM::tGPRRegClass;
2571 RC = &ARM::GPRRegClass;
2573 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2574 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2576 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2577 MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2579 MemOps.push_back(Store);
2580 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2581 DAG.getConstant(4, getPointerTy()));
2583 if (!MemOps.empty())
2584 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2585 &MemOps[0], MemOps.size());
2587 // This will point to the next argument passed via stack.
2588 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2592 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2593 CallingConv::ID CallConv, bool isVarArg,
2594 const SmallVectorImpl<ISD::InputArg>
2596 DebugLoc dl, SelectionDAG &DAG,
2597 SmallVectorImpl<SDValue> &InVals)
2599 MachineFunction &MF = DAG.getMachineFunction();
2600 MachineFrameInfo *MFI = MF.getFrameInfo();
2602 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2604 // Assign locations to all of the incoming arguments.
2605 SmallVector<CCValAssign, 16> ArgLocs;
2606 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2607 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2608 CCInfo.AnalyzeFormalArguments(Ins,
2609 CCAssignFnForNode(CallConv, /* Return*/ false,
2612 SmallVector<SDValue, 16> ArgValues;
2613 int lastInsIndex = -1;
2616 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2617 CCValAssign &VA = ArgLocs[i];
2619 // Arguments stored in registers.
2620 if (VA.isRegLoc()) {
2621 EVT RegVT = VA.getLocVT();
2623 if (VA.needsCustom()) {
2624 // f64 and vector types are split up into multiple registers or
2625 // combinations of registers and stack slots.
2626 if (VA.getLocVT() == MVT::v2f64) {
2627 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2629 VA = ArgLocs[++i]; // skip ahead to next loc
2631 if (VA.isMemLoc()) {
2632 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2633 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2634 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2635 MachinePointerInfo::getFixedStack(FI),
2636 false, false, false, 0);
2638 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2641 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2642 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2643 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2644 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2645 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2647 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2650 const TargetRegisterClass *RC;
2652 if (RegVT == MVT::f32)
2653 RC = &ARM::SPRRegClass;
2654 else if (RegVT == MVT::f64)
2655 RC = &ARM::DPRRegClass;
2656 else if (RegVT == MVT::v2f64)
2657 RC = &ARM::QPRRegClass;
2658 else if (RegVT == MVT::i32)
2659 RC = AFI->isThumb1OnlyFunction() ?
2660 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2661 (const TargetRegisterClass*)&ARM::GPRRegClass;
2663 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2665 // Transform the arguments in physical registers into virtual ones.
2666 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2667 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2670 // If this is an 8 or 16-bit value, it is really passed promoted
2671 // to 32 bits. Insert an assert[sz]ext to capture this, then
2672 // truncate to the right size.
2673 switch (VA.getLocInfo()) {
2674 default: llvm_unreachable("Unknown loc info!");
2675 case CCValAssign::Full: break;
2676 case CCValAssign::BCvt:
2677 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2679 case CCValAssign::SExt:
2680 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2681 DAG.getValueType(VA.getValVT()));
2682 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2684 case CCValAssign::ZExt:
2685 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2686 DAG.getValueType(VA.getValVT()));
2687 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2691 InVals.push_back(ArgValue);
2693 } else { // VA.isRegLoc()
2696 assert(VA.isMemLoc());
2697 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2699 int index = ArgLocs[i].getValNo();
2701 // Some Ins[] entries become multiple ArgLoc[] entries.
2702 // Process them only once.
2703 if (index != lastInsIndex)
2705 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2706 // FIXME: For now, all byval parameter objects are marked mutable.
2707 // This can be changed with more analysis.
2708 // In case of tail call optimization mark all arguments mutable.
2709 // Since they could be overwritten by lowering of arguments in case of
2711 if (Flags.isByVal()) {
2712 unsigned VARegSize, VARegSaveSize;
2713 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2714 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2715 unsigned Bytes = Flags.getByValSize() - VARegSize;
2716 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2717 int FI = MFI->CreateFixedObject(Bytes,
2718 VA.getLocMemOffset(), false);
2719 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2721 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2722 VA.getLocMemOffset(), true);
2724 // Create load nodes to retrieve arguments from the stack.
2725 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2726 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2727 MachinePointerInfo::getFixedStack(FI),
2728 false, false, false, 0));
2730 lastInsIndex = index;
2737 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2742 /// isFloatingPointZero - Return true if this is +0.0.
2743 static bool isFloatingPointZero(SDValue Op) {
2744 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2745 return CFP->getValueAPF().isPosZero();
2746 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2747 // Maybe this has already been legalized into the constant pool?
2748 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2749 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2750 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2751 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2752 return CFP->getValueAPF().isPosZero();
2758 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2759 /// the given operands.
2761 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2762 SDValue &ARMcc, SelectionDAG &DAG,
2763 DebugLoc dl) const {
2764 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2765 unsigned C = RHSC->getZExtValue();
2766 if (!isLegalICmpImmediate(C)) {
2767 // Constant does not fit, try adjusting it by one?
2772 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2773 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2774 RHS = DAG.getConstant(C-1, MVT::i32);
2779 if (C != 0 && isLegalICmpImmediate(C-1)) {
2780 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2781 RHS = DAG.getConstant(C-1, MVT::i32);
2786 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2787 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2788 RHS = DAG.getConstant(C+1, MVT::i32);
2793 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2794 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2795 RHS = DAG.getConstant(C+1, MVT::i32);
2802 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2803 ARMISD::NodeType CompareType;
2806 CompareType = ARMISD::CMP;
2811 CompareType = ARMISD::CMPZ;
2814 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2815 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2818 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2820 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2821 DebugLoc dl) const {
2823 if (!isFloatingPointZero(RHS))
2824 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2826 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2827 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2830 /// duplicateCmp - Glue values can have only one use, so this function
2831 /// duplicates a comparison node.
2833 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2834 unsigned Opc = Cmp.getOpcode();
2835 DebugLoc DL = Cmp.getDebugLoc();
2836 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2837 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2839 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2840 Cmp = Cmp.getOperand(0);
2841 Opc = Cmp.getOpcode();
2842 if (Opc == ARMISD::CMPFP)
2843 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2845 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2846 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2848 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2851 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2852 SDValue Cond = Op.getOperand(0);
2853 SDValue SelectTrue = Op.getOperand(1);
2854 SDValue SelectFalse = Op.getOperand(2);
2855 DebugLoc dl = Op.getDebugLoc();
2859 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2860 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2862 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2863 const ConstantSDNode *CMOVTrue =
2864 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2865 const ConstantSDNode *CMOVFalse =
2866 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2868 if (CMOVTrue && CMOVFalse) {
2869 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2870 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2874 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2876 False = SelectFalse;
2877 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2882 if (True.getNode() && False.getNode()) {
2883 EVT VT = Op.getValueType();
2884 SDValue ARMcc = Cond.getOperand(2);
2885 SDValue CCR = Cond.getOperand(3);
2886 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2887 assert(True.getValueType() == VT);
2888 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2893 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2894 // undefined bits before doing a full-word comparison with zero.
2895 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2896 DAG.getConstant(1, Cond.getValueType()));
2898 return DAG.getSelectCC(dl, Cond,
2899 DAG.getConstant(0, Cond.getValueType()),
2900 SelectTrue, SelectFalse, ISD::SETNE);
2903 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2904 EVT VT = Op.getValueType();
2905 SDValue LHS = Op.getOperand(0);
2906 SDValue RHS = Op.getOperand(1);
2907 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2908 SDValue TrueVal = Op.getOperand(2);
2909 SDValue FalseVal = Op.getOperand(3);
2910 DebugLoc dl = Op.getDebugLoc();
2912 if (LHS.getValueType() == MVT::i32) {
2914 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2915 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2916 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2919 ARMCC::CondCodes CondCode, CondCode2;
2920 FPCCToARMCC(CC, CondCode, CondCode2);
2922 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2923 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2924 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2925 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2927 if (CondCode2 != ARMCC::AL) {
2928 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2929 // FIXME: Needs another CMP because flag can have but one use.
2930 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2931 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2932 Result, TrueVal, ARMcc2, CCR, Cmp2);
2937 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2938 /// to morph to an integer compare sequence.
2939 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2940 const ARMSubtarget *Subtarget) {
2941 SDNode *N = Op.getNode();
2942 if (!N->hasOneUse())
2943 // Otherwise it requires moving the value from fp to integer registers.
2945 if (!N->getNumValues())
2947 EVT VT = Op.getValueType();
2948 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2949 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2950 // vmrs are very slow, e.g. cortex-a8.
2953 if (isFloatingPointZero(Op)) {
2957 return ISD::isNormalLoad(N);
2960 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2961 if (isFloatingPointZero(Op))
2962 return DAG.getConstant(0, MVT::i32);
2964 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2965 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2966 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2967 Ld->isVolatile(), Ld->isNonTemporal(),
2968 Ld->isInvariant(), Ld->getAlignment());
2970 llvm_unreachable("Unknown VFP cmp argument!");
2973 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2974 SDValue &RetVal1, SDValue &RetVal2) {
2975 if (isFloatingPointZero(Op)) {
2976 RetVal1 = DAG.getConstant(0, MVT::i32);
2977 RetVal2 = DAG.getConstant(0, MVT::i32);
2981 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2982 SDValue Ptr = Ld->getBasePtr();
2983 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2984 Ld->getChain(), Ptr,
2985 Ld->getPointerInfo(),
2986 Ld->isVolatile(), Ld->isNonTemporal(),
2987 Ld->isInvariant(), Ld->getAlignment());
2989 EVT PtrType = Ptr.getValueType();
2990 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2991 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2992 PtrType, Ptr, DAG.getConstant(4, PtrType));
2993 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2994 Ld->getChain(), NewPtr,
2995 Ld->getPointerInfo().getWithOffset(4),
2996 Ld->isVolatile(), Ld->isNonTemporal(),
2997 Ld->isInvariant(), NewAlign);
3001 llvm_unreachable("Unknown VFP cmp argument!");
3004 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3005 /// f32 and even f64 comparisons to integer ones.
3007 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3008 SDValue Chain = Op.getOperand(0);
3009 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3010 SDValue LHS = Op.getOperand(2);
3011 SDValue RHS = Op.getOperand(3);
3012 SDValue Dest = Op.getOperand(4);
3013 DebugLoc dl = Op.getDebugLoc();
3015 bool LHSSeenZero = false;
3016 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3017 bool RHSSeenZero = false;
3018 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3019 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3020 // If unsafe fp math optimization is enabled and there are no other uses of
3021 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3022 // to an integer comparison.
3023 if (CC == ISD::SETOEQ)
3025 else if (CC == ISD::SETUNE)
3028 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3030 if (LHS.getValueType() == MVT::f32) {
3031 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3032 bitcastf32Toi32(LHS, DAG), Mask);
3033 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3034 bitcastf32Toi32(RHS, DAG), Mask);
3035 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3036 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3037 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3038 Chain, Dest, ARMcc, CCR, Cmp);
3043 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3044 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3045 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3046 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3047 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3048 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3049 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3050 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3051 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3057 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3058 SDValue Chain = Op.getOperand(0);
3059 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3060 SDValue LHS = Op.getOperand(2);
3061 SDValue RHS = Op.getOperand(3);
3062 SDValue Dest = Op.getOperand(4);
3063 DebugLoc dl = Op.getDebugLoc();
3065 if (LHS.getValueType() == MVT::i32) {
3067 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3068 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3069 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3070 Chain, Dest, ARMcc, CCR, Cmp);
3073 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3075 if (getTargetMachine().Options.UnsafeFPMath &&
3076 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3077 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3078 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3079 if (Result.getNode())
3083 ARMCC::CondCodes CondCode, CondCode2;
3084 FPCCToARMCC(CC, CondCode, CondCode2);
3086 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3087 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3088 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3089 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3090 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3091 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3092 if (CondCode2 != ARMCC::AL) {
3093 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3094 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3095 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3100 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3101 SDValue Chain = Op.getOperand(0);
3102 SDValue Table = Op.getOperand(1);
3103 SDValue Index = Op.getOperand(2);
3104 DebugLoc dl = Op.getDebugLoc();
3106 EVT PTy = getPointerTy();
3107 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3108 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3109 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3110 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3111 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3112 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3113 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3114 if (Subtarget->isThumb2()) {
3115 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3116 // which does another jump to the destination. This also makes it easier
3117 // to translate it to TBB / TBH later.
3118 // FIXME: This might not work if the function is extremely large.
3119 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3120 Addr, Op.getOperand(2), JTI, UId);
3122 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3123 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3124 MachinePointerInfo::getJumpTable(),
3125 false, false, false, 0);
3126 Chain = Addr.getValue(1);
3127 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3128 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3130 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3131 MachinePointerInfo::getJumpTable(),
3132 false, false, false, 0);
3133 Chain = Addr.getValue(1);
3134 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3138 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3139 EVT VT = Op.getValueType();
3140 DebugLoc dl = Op.getDebugLoc();
3142 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3143 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3145 return DAG.UnrollVectorOp(Op.getNode());
3148 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3149 "Invalid type for custom lowering!");
3150 if (VT != MVT::v4i16)
3151 return DAG.UnrollVectorOp(Op.getNode());
3153 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3154 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3157 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3158 EVT VT = Op.getValueType();
3160 return LowerVectorFP_TO_INT(Op, DAG);
3162 DebugLoc dl = Op.getDebugLoc();
3165 switch (Op.getOpcode()) {
3166 default: llvm_unreachable("Invalid opcode!");
3167 case ISD::FP_TO_SINT:
3168 Opc = ARMISD::FTOSI;
3170 case ISD::FP_TO_UINT:
3171 Opc = ARMISD::FTOUI;
3174 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3175 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3178 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3179 EVT VT = Op.getValueType();
3180 DebugLoc dl = Op.getDebugLoc();
3182 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3183 if (VT.getVectorElementType() == MVT::f32)
3185 return DAG.UnrollVectorOp(Op.getNode());
3188 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3189 "Invalid type for custom lowering!");
3190 if (VT != MVT::v4f32)
3191 return DAG.UnrollVectorOp(Op.getNode());
3195 switch (Op.getOpcode()) {
3196 default: llvm_unreachable("Invalid opcode!");
3197 case ISD::SINT_TO_FP:
3198 CastOpc = ISD::SIGN_EXTEND;
3199 Opc = ISD::SINT_TO_FP;
3201 case ISD::UINT_TO_FP:
3202 CastOpc = ISD::ZERO_EXTEND;
3203 Opc = ISD::UINT_TO_FP;
3207 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3208 return DAG.getNode(Opc, dl, VT, Op);
3211 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3212 EVT VT = Op.getValueType();
3214 return LowerVectorINT_TO_FP(Op, DAG);
3216 DebugLoc dl = Op.getDebugLoc();
3219 switch (Op.getOpcode()) {
3220 default: llvm_unreachable("Invalid opcode!");
3221 case ISD::SINT_TO_FP:
3222 Opc = ARMISD::SITOF;
3224 case ISD::UINT_TO_FP:
3225 Opc = ARMISD::UITOF;
3229 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3230 return DAG.getNode(Opc, dl, VT, Op);
3233 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3234 // Implement fcopysign with a fabs and a conditional fneg.
3235 SDValue Tmp0 = Op.getOperand(0);
3236 SDValue Tmp1 = Op.getOperand(1);
3237 DebugLoc dl = Op.getDebugLoc();
3238 EVT VT = Op.getValueType();
3239 EVT SrcVT = Tmp1.getValueType();
3240 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3241 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3242 bool UseNEON = !InGPR && Subtarget->hasNEON();
3245 // Use VBSL to copy the sign bit.
3246 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3247 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3248 DAG.getTargetConstant(EncodedVal, MVT::i32));
3249 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3251 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3252 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3253 DAG.getConstant(32, MVT::i32));
3254 else /*if (VT == MVT::f32)*/
3255 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3256 if (SrcVT == MVT::f32) {
3257 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3259 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3260 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3261 DAG.getConstant(32, MVT::i32));
3262 } else if (VT == MVT::f32)
3263 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3264 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3265 DAG.getConstant(32, MVT::i32));
3266 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3267 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3269 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3271 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3272 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3273 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3275 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3276 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3277 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3278 if (VT == MVT::f32) {
3279 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3280 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3281 DAG.getConstant(0, MVT::i32));
3283 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3289 // Bitcast operand 1 to i32.
3290 if (SrcVT == MVT::f64)
3291 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3292 &Tmp1, 1).getValue(1);
3293 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3295 // Or in the signbit with integer operations.
3296 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3297 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3298 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3299 if (VT == MVT::f32) {
3300 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3301 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3302 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3303 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3306 // f64: Or the high part with signbit and then combine two parts.
3307 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3309 SDValue Lo = Tmp0.getValue(0);
3310 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3311 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3312 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3315 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3316 MachineFunction &MF = DAG.getMachineFunction();
3317 MachineFrameInfo *MFI = MF.getFrameInfo();
3318 MFI->setReturnAddressIsTaken(true);
3320 EVT VT = Op.getValueType();
3321 DebugLoc dl = Op.getDebugLoc();
3322 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3324 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3325 SDValue Offset = DAG.getConstant(4, MVT::i32);
3326 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3327 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3328 MachinePointerInfo(), false, false, false, 0);
3331 // Return LR, which contains the return address. Mark it an implicit live-in.
3332 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3333 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3336 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3337 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3338 MFI->setFrameAddressIsTaken(true);
3340 EVT VT = Op.getValueType();
3341 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3342 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3343 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3344 ? ARM::R7 : ARM::R11;
3345 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3347 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3348 MachinePointerInfo(),
3349 false, false, false, 0);
3353 /// ExpandBITCAST - If the target supports VFP, this function is called to
3354 /// expand a bit convert where either the source or destination type is i64 to
3355 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3356 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3357 /// vectors), since the legalizer won't know what to do with that.
3358 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3359 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3360 DebugLoc dl = N->getDebugLoc();
3361 SDValue Op = N->getOperand(0);
3363 // This function is only supposed to be called for i64 types, either as the
3364 // source or destination of the bit convert.
3365 EVT SrcVT = Op.getValueType();
3366 EVT DstVT = N->getValueType(0);
3367 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3368 "ExpandBITCAST called for non-i64 type");
3370 // Turn i64->f64 into VMOVDRR.
3371 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3372 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3373 DAG.getConstant(0, MVT::i32));
3374 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3375 DAG.getConstant(1, MVT::i32));
3376 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3377 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3380 // Turn f64->i64 into VMOVRRD.
3381 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3382 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3383 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3384 // Merge the pieces into a single i64 value.
3385 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3391 /// getZeroVector - Returns a vector of specified type with all zero elements.
3392 /// Zero vectors are used to represent vector negation and in those cases
3393 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3394 /// not support i64 elements, so sometimes the zero vectors will need to be
3395 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3397 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3398 assert(VT.isVector() && "Expected a vector type");
3399 // The canonical modified immediate encoding of a zero vector is....0!
3400 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3401 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3402 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3403 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3406 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3407 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3408 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3409 SelectionDAG &DAG) const {
3410 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3411 EVT VT = Op.getValueType();
3412 unsigned VTBits = VT.getSizeInBits();
3413 DebugLoc dl = Op.getDebugLoc();
3414 SDValue ShOpLo = Op.getOperand(0);
3415 SDValue ShOpHi = Op.getOperand(1);
3416 SDValue ShAmt = Op.getOperand(2);
3418 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3420 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3422 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3423 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3424 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3425 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3426 DAG.getConstant(VTBits, MVT::i32));
3427 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3428 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3429 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3431 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3432 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3434 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3435 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3438 SDValue Ops[2] = { Lo, Hi };
3439 return DAG.getMergeValues(Ops, 2, dl);
3442 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3443 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3444 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3445 SelectionDAG &DAG) const {
3446 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3447 EVT VT = Op.getValueType();
3448 unsigned VTBits = VT.getSizeInBits();
3449 DebugLoc dl = Op.getDebugLoc();
3450 SDValue ShOpLo = Op.getOperand(0);
3451 SDValue ShOpHi = Op.getOperand(1);
3452 SDValue ShAmt = Op.getOperand(2);
3455 assert(Op.getOpcode() == ISD::SHL_PARTS);
3456 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3457 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3458 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3459 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3460 DAG.getConstant(VTBits, MVT::i32));
3461 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3462 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3464 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3465 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3466 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3468 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3469 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3472 SDValue Ops[2] = { Lo, Hi };
3473 return DAG.getMergeValues(Ops, 2, dl);
3476 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3477 SelectionDAG &DAG) const {
3478 // The rounding mode is in bits 23:22 of the FPSCR.
3479 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3480 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3481 // so that the shift + and get folded into a bitfield extract.
3482 DebugLoc dl = Op.getDebugLoc();
3483 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3484 DAG.getConstant(Intrinsic::arm_get_fpscr,
3486 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3487 DAG.getConstant(1U << 22, MVT::i32));
3488 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3489 DAG.getConstant(22, MVT::i32));
3490 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3491 DAG.getConstant(3, MVT::i32));
3494 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3495 const ARMSubtarget *ST) {
3496 EVT VT = N->getValueType(0);
3497 DebugLoc dl = N->getDebugLoc();
3499 if (!ST->hasV6T2Ops())
3502 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3503 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3506 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3507 const ARMSubtarget *ST) {
3508 EVT VT = N->getValueType(0);
3509 DebugLoc dl = N->getDebugLoc();
3514 // Lower vector shifts on NEON to use VSHL.
3515 assert(ST->hasNEON() && "unexpected vector shift");
3517 // Left shifts translate directly to the vshiftu intrinsic.
3518 if (N->getOpcode() == ISD::SHL)
3519 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3520 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3521 N->getOperand(0), N->getOperand(1));
3523 assert((N->getOpcode() == ISD::SRA ||
3524 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3526 // NEON uses the same intrinsics for both left and right shifts. For
3527 // right shifts, the shift amounts are negative, so negate the vector of
3529 EVT ShiftVT = N->getOperand(1).getValueType();
3530 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3531 getZeroVector(ShiftVT, DAG, dl),
3533 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3534 Intrinsic::arm_neon_vshifts :
3535 Intrinsic::arm_neon_vshiftu);
3536 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3537 DAG.getConstant(vshiftInt, MVT::i32),
3538 N->getOperand(0), NegatedCount);
3541 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3542 const ARMSubtarget *ST) {
3543 EVT VT = N->getValueType(0);
3544 DebugLoc dl = N->getDebugLoc();
3546 // We can get here for a node like i32 = ISD::SHL i32, i64
3550 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3551 "Unknown shift to lower!");
3553 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3554 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3555 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3558 // If we are in thumb mode, we don't have RRX.
3559 if (ST->isThumb1Only()) return SDValue();
3561 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3562 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3563 DAG.getConstant(0, MVT::i32));
3564 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3565 DAG.getConstant(1, MVT::i32));
3567 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3568 // captures the result into a carry flag.
3569 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3570 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3572 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3573 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3575 // Merge the pieces into a single i64 value.
3576 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3579 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3580 SDValue TmpOp0, TmpOp1;
3581 bool Invert = false;
3585 SDValue Op0 = Op.getOperand(0);
3586 SDValue Op1 = Op.getOperand(1);
3587 SDValue CC = Op.getOperand(2);
3588 EVT VT = Op.getValueType();
3589 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3590 DebugLoc dl = Op.getDebugLoc();
3592 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3593 switch (SetCCOpcode) {
3594 default: llvm_unreachable("Illegal FP comparison");
3596 case ISD::SETNE: Invert = true; // Fallthrough
3598 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3600 case ISD::SETLT: Swap = true; // Fallthrough
3602 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3604 case ISD::SETLE: Swap = true; // Fallthrough
3606 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3607 case ISD::SETUGE: Swap = true; // Fallthrough
3608 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3609 case ISD::SETUGT: Swap = true; // Fallthrough
3610 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3611 case ISD::SETUEQ: Invert = true; // Fallthrough
3613 // Expand this to (OLT | OGT).
3617 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3618 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3620 case ISD::SETUO: Invert = true; // Fallthrough
3622 // Expand this to (OLT | OGE).
3626 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3627 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3631 // Integer comparisons.
3632 switch (SetCCOpcode) {
3633 default: llvm_unreachable("Illegal integer comparison");
3634 case ISD::SETNE: Invert = true;
3635 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3636 case ISD::SETLT: Swap = true;
3637 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3638 case ISD::SETLE: Swap = true;
3639 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3640 case ISD::SETULT: Swap = true;
3641 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3642 case ISD::SETULE: Swap = true;
3643 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3646 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3647 if (Opc == ARMISD::VCEQ) {
3650 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3652 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3655 // Ignore bitconvert.
3656 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3657 AndOp = AndOp.getOperand(0);
3659 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3661 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3662 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3669 std::swap(Op0, Op1);
3671 // If one of the operands is a constant vector zero, attempt to fold the
3672 // comparison to a specialized compare-against-zero form.
3674 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3676 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3677 if (Opc == ARMISD::VCGE)
3678 Opc = ARMISD::VCLEZ;
3679 else if (Opc == ARMISD::VCGT)
3680 Opc = ARMISD::VCLTZ;
3685 if (SingleOp.getNode()) {
3688 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3690 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3692 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3694 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3696 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3698 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3701 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3705 Result = DAG.getNOT(dl, Result, VT);
3710 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3711 /// valid vector constant for a NEON instruction with a "modified immediate"
3712 /// operand (e.g., VMOV). If so, return the encoded value.
3713 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3714 unsigned SplatBitSize, SelectionDAG &DAG,
3715 EVT &VT, bool is128Bits, NEONModImmType type) {
3716 unsigned OpCmode, Imm;
3718 // SplatBitSize is set to the smallest size that splats the vector, so a
3719 // zero vector will always have SplatBitSize == 8. However, NEON modified
3720 // immediate instructions others than VMOV do not support the 8-bit encoding
3721 // of a zero vector, and the default encoding of zero is supposed to be the
3726 switch (SplatBitSize) {
3728 if (type != VMOVModImm)
3730 // Any 1-byte value is OK. Op=0, Cmode=1110.
3731 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3734 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3738 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3739 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3740 if ((SplatBits & ~0xff) == 0) {
3741 // Value = 0x00nn: Op=x, Cmode=100x.
3746 if ((SplatBits & ~0xff00) == 0) {
3747 // Value = 0xnn00: Op=x, Cmode=101x.
3749 Imm = SplatBits >> 8;
3755 // NEON's 32-bit VMOV supports splat values where:
3756 // * only one byte is nonzero, or
3757 // * the least significant byte is 0xff and the second byte is nonzero, or
3758 // * the least significant 2 bytes are 0xff and the third is nonzero.
3759 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3760 if ((SplatBits & ~0xff) == 0) {
3761 // Value = 0x000000nn: Op=x, Cmode=000x.
3766 if ((SplatBits & ~0xff00) == 0) {
3767 // Value = 0x0000nn00: Op=x, Cmode=001x.
3769 Imm = SplatBits >> 8;
3772 if ((SplatBits & ~0xff0000) == 0) {
3773 // Value = 0x00nn0000: Op=x, Cmode=010x.
3775 Imm = SplatBits >> 16;
3778 if ((SplatBits & ~0xff000000) == 0) {
3779 // Value = 0xnn000000: Op=x, Cmode=011x.
3781 Imm = SplatBits >> 24;
3785 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3786 if (type == OtherModImm) return SDValue();
3788 if ((SplatBits & ~0xffff) == 0 &&
3789 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3790 // Value = 0x0000nnff: Op=x, Cmode=1100.
3792 Imm = SplatBits >> 8;
3797 if ((SplatBits & ~0xffffff) == 0 &&
3798 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3799 // Value = 0x00nnffff: Op=x, Cmode=1101.
3801 Imm = SplatBits >> 16;
3802 SplatBits |= 0xffff;
3806 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3807 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3808 // VMOV.I32. A (very) minor optimization would be to replicate the value
3809 // and fall through here to test for a valid 64-bit splat. But, then the
3810 // caller would also need to check and handle the change in size.
3814 if (type != VMOVModImm)
3816 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3817 uint64_t BitMask = 0xff;
3819 unsigned ImmMask = 1;
3821 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3822 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3825 } else if ((SplatBits & BitMask) != 0) {
3831 // Op=1, Cmode=1110.
3834 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3839 llvm_unreachable("unexpected size for isNEONModifiedImm");
3842 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3843 return DAG.getTargetConstant(EncodedVal, MVT::i32);
3846 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3847 const ARMSubtarget *ST) const {
3848 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3851 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3852 assert(Op.getValueType() == MVT::f32 &&
3853 "ConstantFP custom lowering should only occur for f32.");
3855 // Try splatting with a VMOV.f32...
3856 APFloat FPVal = CFP->getValueAPF();
3857 int ImmVal = ARM_AM::getFP32Imm(FPVal);
3859 DebugLoc DL = Op.getDebugLoc();
3860 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3861 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3863 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3864 DAG.getConstant(0, MVT::i32));
3867 // If that fails, try a VMOV.i32
3869 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3870 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3872 if (NewVal != SDValue()) {
3873 DebugLoc DL = Op.getDebugLoc();
3874 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3876 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3878 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3879 DAG.getConstant(0, MVT::i32));
3882 // Finally, try a VMVN.i32
3883 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3885 if (NewVal != SDValue()) {
3886 DebugLoc DL = Op.getDebugLoc();
3887 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3888 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3890 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3891 DAG.getConstant(0, MVT::i32));
3898 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3899 bool &ReverseVEXT, unsigned &Imm) {
3900 unsigned NumElts = VT.getVectorNumElements();
3901 ReverseVEXT = false;
3903 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3909 // If this is a VEXT shuffle, the immediate value is the index of the first
3910 // element. The other shuffle indices must be the successive elements after
3912 unsigned ExpectedElt = Imm;
3913 for (unsigned i = 1; i < NumElts; ++i) {
3914 // Increment the expected index. If it wraps around, it may still be
3915 // a VEXT but the source vectors must be swapped.
3917 if (ExpectedElt == NumElts * 2) {
3922 if (M[i] < 0) continue; // ignore UNDEF indices
3923 if (ExpectedElt != static_cast<unsigned>(M[i]))
3927 // Adjust the index value if the source operands will be swapped.
3934 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3935 /// instruction with the specified blocksize. (The order of the elements
3936 /// within each block of the vector is reversed.)
3937 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3938 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3939 "Only possible block sizes for VREV are: 16, 32, 64");
3941 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3945 unsigned NumElts = VT.getVectorNumElements();
3946 unsigned BlockElts = M[0] + 1;
3947 // If the first shuffle index is UNDEF, be optimistic.
3949 BlockElts = BlockSize / EltSz;
3951 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3954 for (unsigned i = 0; i < NumElts; ++i) {
3955 if (M[i] < 0) continue; // ignore UNDEF indices
3956 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3963 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3964 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3965 // range, then 0 is placed into the resulting vector. So pretty much any mask
3966 // of 8 elements can work here.
3967 return VT == MVT::v8i8 && M.size() == 8;
3970 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3971 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3975 unsigned NumElts = VT.getVectorNumElements();
3976 WhichResult = (M[0] == 0 ? 0 : 1);
3977 for (unsigned i = 0; i < NumElts; i += 2) {
3978 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3979 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3985 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3986 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3987 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3988 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3989 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3993 unsigned NumElts = VT.getVectorNumElements();
3994 WhichResult = (M[0] == 0 ? 0 : 1);
3995 for (unsigned i = 0; i < NumElts; i += 2) {
3996 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3997 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4003 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4004 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4008 unsigned NumElts = VT.getVectorNumElements();
4009 WhichResult = (M[0] == 0 ? 0 : 1);
4010 for (unsigned i = 0; i != NumElts; ++i) {
4011 if (M[i] < 0) continue; // ignore UNDEF indices
4012 if ((unsigned) M[i] != 2 * i + WhichResult)
4016 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4017 if (VT.is64BitVector() && EltSz == 32)
4023 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4024 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4025 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4026 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4027 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4031 unsigned Half = VT.getVectorNumElements() / 2;
4032 WhichResult = (M[0] == 0 ? 0 : 1);
4033 for (unsigned j = 0; j != 2; ++j) {
4034 unsigned Idx = WhichResult;
4035 for (unsigned i = 0; i != Half; ++i) {
4036 int MIdx = M[i + j * Half];
4037 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4043 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4044 if (VT.is64BitVector() && EltSz == 32)
4050 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4051 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4055 unsigned NumElts = VT.getVectorNumElements();
4056 WhichResult = (M[0] == 0 ? 0 : 1);
4057 unsigned Idx = WhichResult * NumElts / 2;
4058 for (unsigned i = 0; i != NumElts; i += 2) {
4059 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4060 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4065 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4066 if (VT.is64BitVector() && EltSz == 32)
4072 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4073 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4074 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4075 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4076 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4080 unsigned NumElts = VT.getVectorNumElements();
4081 WhichResult = (M[0] == 0 ? 0 : 1);
4082 unsigned Idx = WhichResult * NumElts / 2;
4083 for (unsigned i = 0; i != NumElts; i += 2) {
4084 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4085 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4090 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4091 if (VT.is64BitVector() && EltSz == 32)
4097 // If N is an integer constant that can be moved into a register in one
4098 // instruction, return an SDValue of such a constant (will become a MOV
4099 // instruction). Otherwise return null.
4100 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4101 const ARMSubtarget *ST, DebugLoc dl) {
4103 if (!isa<ConstantSDNode>(N))
4105 Val = cast<ConstantSDNode>(N)->getZExtValue();
4107 if (ST->isThumb1Only()) {
4108 if (Val <= 255 || ~Val <= 255)
4109 return DAG.getConstant(Val, MVT::i32);
4111 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4112 return DAG.getConstant(Val, MVT::i32);
4117 // If this is a case we can't handle, return null and let the default
4118 // expansion code take care of it.
4119 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4120 const ARMSubtarget *ST) const {
4121 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4122 DebugLoc dl = Op.getDebugLoc();
4123 EVT VT = Op.getValueType();
4125 APInt SplatBits, SplatUndef;
4126 unsigned SplatBitSize;
4128 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4129 if (SplatBitSize <= 64) {
4130 // Check if an immediate VMOV works.
4132 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4133 SplatUndef.getZExtValue(), SplatBitSize,
4134 DAG, VmovVT, VT.is128BitVector(),
4136 if (Val.getNode()) {
4137 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4138 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4141 // Try an immediate VMVN.
4142 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4143 Val = isNEONModifiedImm(NegatedImm,
4144 SplatUndef.getZExtValue(), SplatBitSize,
4145 DAG, VmovVT, VT.is128BitVector(),
4147 if (Val.getNode()) {
4148 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4149 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4152 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4153 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4154 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4156 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4157 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4163 // Scan through the operands to see if only one value is used.
4164 unsigned NumElts = VT.getVectorNumElements();
4165 bool isOnlyLowElement = true;
4166 bool usesOnlyOneValue = true;
4167 bool isConstant = true;
4169 for (unsigned i = 0; i < NumElts; ++i) {
4170 SDValue V = Op.getOperand(i);
4171 if (V.getOpcode() == ISD::UNDEF)
4174 isOnlyLowElement = false;
4175 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4178 if (!Value.getNode())
4180 else if (V != Value)
4181 usesOnlyOneValue = false;
4184 if (!Value.getNode())
4185 return DAG.getUNDEF(VT);
4187 if (isOnlyLowElement)
4188 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4190 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4192 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4193 // i32 and try again.
4194 if (usesOnlyOneValue && EltSize <= 32) {
4196 return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4197 if (VT.getVectorElementType().isFloatingPoint()) {
4198 SmallVector<SDValue, 8> Ops;
4199 for (unsigned i = 0; i < NumElts; ++i)
4200 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4202 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4203 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4204 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4206 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4208 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4210 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4213 // If all elements are constants and the case above didn't get hit, fall back
4214 // to the default expansion, which will generate a load from the constant
4219 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4221 SDValue shuffle = ReconstructShuffle(Op, DAG);
4222 if (shuffle != SDValue())
4226 // Vectors with 32- or 64-bit elements can be built by directly assigning
4227 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4228 // will be legalized.
4229 if (EltSize >= 32) {
4230 // Do the expansion with floating-point types, since that is what the VFP
4231 // registers are defined to use, and since i64 is not legal.
4232 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4233 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4234 SmallVector<SDValue, 8> Ops;
4235 for (unsigned i = 0; i < NumElts; ++i)
4236 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4237 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4238 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4244 // Gather data to see if the operation can be modelled as a
4245 // shuffle in combination with VEXTs.
4246 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4247 SelectionDAG &DAG) const {
4248 DebugLoc dl = Op.getDebugLoc();
4249 EVT VT = Op.getValueType();
4250 unsigned NumElts = VT.getVectorNumElements();
4252 SmallVector<SDValue, 2> SourceVecs;
4253 SmallVector<unsigned, 2> MinElts;
4254 SmallVector<unsigned, 2> MaxElts;
4256 for (unsigned i = 0; i < NumElts; ++i) {
4257 SDValue V = Op.getOperand(i);
4258 if (V.getOpcode() == ISD::UNDEF)
4260 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4261 // A shuffle can only come from building a vector from various
4262 // elements of other vectors.
4264 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4265 VT.getVectorElementType()) {
4266 // This code doesn't know how to handle shuffles where the vector
4267 // element types do not match (this happens because type legalization
4268 // promotes the return type of EXTRACT_VECTOR_ELT).
4269 // FIXME: It might be appropriate to extend this code to handle
4270 // mismatched types.
4274 // Record this extraction against the appropriate vector if possible...
4275 SDValue SourceVec = V.getOperand(0);
4276 // If the element number isn't a constant, we can't effectively
4277 // analyze what's going on.
4278 if (!isa<ConstantSDNode>(V.getOperand(1)))
4280 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4281 bool FoundSource = false;
4282 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4283 if (SourceVecs[j] == SourceVec) {
4284 if (MinElts[j] > EltNo)
4286 if (MaxElts[j] < EltNo)
4293 // Or record a new source if not...
4295 SourceVecs.push_back(SourceVec);
4296 MinElts.push_back(EltNo);
4297 MaxElts.push_back(EltNo);
4301 // Currently only do something sane when at most two source vectors
4303 if (SourceVecs.size() > 2)
4306 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4307 int VEXTOffsets[2] = {0, 0};
4309 // This loop extracts the usage patterns of the source vectors
4310 // and prepares appropriate SDValues for a shuffle if possible.
4311 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4312 if (SourceVecs[i].getValueType() == VT) {
4313 // No VEXT necessary
4314 ShuffleSrcs[i] = SourceVecs[i];
4317 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4318 // It probably isn't worth padding out a smaller vector just to
4319 // break it down again in a shuffle.
4323 // Since only 64-bit and 128-bit vectors are legal on ARM and
4324 // we've eliminated the other cases...
4325 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4326 "unexpected vector sizes in ReconstructShuffle");
4328 if (MaxElts[i] - MinElts[i] >= NumElts) {
4329 // Span too large for a VEXT to cope
4333 if (MinElts[i] >= NumElts) {
4334 // The extraction can just take the second half
4335 VEXTOffsets[i] = NumElts;
4336 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4338 DAG.getIntPtrConstant(NumElts));
4339 } else if (MaxElts[i] < NumElts) {
4340 // The extraction can just take the first half
4342 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4344 DAG.getIntPtrConstant(0));
4346 // An actual VEXT is needed
4347 VEXTOffsets[i] = MinElts[i];
4348 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4350 DAG.getIntPtrConstant(0));
4351 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4353 DAG.getIntPtrConstant(NumElts));
4354 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4355 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4359 SmallVector<int, 8> Mask;
4361 for (unsigned i = 0; i < NumElts; ++i) {
4362 SDValue Entry = Op.getOperand(i);
4363 if (Entry.getOpcode() == ISD::UNDEF) {
4368 SDValue ExtractVec = Entry.getOperand(0);
4369 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4370 .getOperand(1))->getSExtValue();
4371 if (ExtractVec == SourceVecs[0]) {
4372 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4374 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4378 // Final check before we try to produce nonsense...
4379 if (isShuffleMaskLegal(Mask, VT))
4380 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4386 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4387 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4388 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4389 /// are assumed to be legal.
4391 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4393 if (VT.getVectorNumElements() == 4 &&
4394 (VT.is128BitVector() || VT.is64BitVector())) {
4395 unsigned PFIndexes[4];
4396 for (unsigned i = 0; i != 4; ++i) {
4400 PFIndexes[i] = M[i];
4403 // Compute the index in the perfect shuffle table.
4404 unsigned PFTableIndex =
4405 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4406 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4407 unsigned Cost = (PFEntry >> 30);
4414 unsigned Imm, WhichResult;
4416 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4417 return (EltSize >= 32 ||
4418 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4419 isVREVMask(M, VT, 64) ||
4420 isVREVMask(M, VT, 32) ||
4421 isVREVMask(M, VT, 16) ||
4422 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4423 isVTBLMask(M, VT) ||
4424 isVTRNMask(M, VT, WhichResult) ||
4425 isVUZPMask(M, VT, WhichResult) ||
4426 isVZIPMask(M, VT, WhichResult) ||
4427 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4428 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4429 isVZIP_v_undef_Mask(M, VT, WhichResult));
4432 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4433 /// the specified operations to build the shuffle.
4434 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4435 SDValue RHS, SelectionDAG &DAG,
4437 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4438 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4439 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4442 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4451 OP_VUZPL, // VUZP, left result
4452 OP_VUZPR, // VUZP, right result
4453 OP_VZIPL, // VZIP, left result
4454 OP_VZIPR, // VZIP, right result
4455 OP_VTRNL, // VTRN, left result
4456 OP_VTRNR // VTRN, right result
4459 if (OpNum == OP_COPY) {
4460 if (LHSID == (1*9+2)*9+3) return LHS;
4461 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4465 SDValue OpLHS, OpRHS;
4466 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4467 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4468 EVT VT = OpLHS.getValueType();
4471 default: llvm_unreachable("Unknown shuffle opcode!");
4473 // VREV divides the vector in half and swaps within the half.
4474 if (VT.getVectorElementType() == MVT::i32 ||
4475 VT.getVectorElementType() == MVT::f32)
4476 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4477 // vrev <4 x i16> -> VREV32
4478 if (VT.getVectorElementType() == MVT::i16)
4479 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4480 // vrev <4 x i8> -> VREV16
4481 assert(VT.getVectorElementType() == MVT::i8);
4482 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4487 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4488 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4492 return DAG.getNode(ARMISD::VEXT, dl, VT,
4494 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4497 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4498 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4501 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4502 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4505 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4506 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4510 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4511 ArrayRef<int> ShuffleMask,
4512 SelectionDAG &DAG) {
4513 // Check to see if we can use the VTBL instruction.
4514 SDValue V1 = Op.getOperand(0);
4515 SDValue V2 = Op.getOperand(1);
4516 DebugLoc DL = Op.getDebugLoc();
4518 SmallVector<SDValue, 8> VTBLMask;
4519 for (ArrayRef<int>::iterator
4520 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4521 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4523 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4524 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4525 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4528 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4529 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4533 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4534 SDValue V1 = Op.getOperand(0);
4535 SDValue V2 = Op.getOperand(1);
4536 DebugLoc dl = Op.getDebugLoc();
4537 EVT VT = Op.getValueType();
4538 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4540 // Convert shuffles that are directly supported on NEON to target-specific
4541 // DAG nodes, instead of keeping them as shuffles and matching them again
4542 // during code selection. This is more efficient and avoids the possibility
4543 // of inconsistencies between legalization and selection.
4544 // FIXME: floating-point vectors should be canonicalized to integer vectors
4545 // of the same time so that they get CSEd properly.
4546 ArrayRef<int> ShuffleMask = SVN->getMask();
4548 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4549 if (EltSize <= 32) {
4550 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4551 int Lane = SVN->getSplatIndex();
4552 // If this is undef splat, generate it via "just" vdup, if possible.
4553 if (Lane == -1) Lane = 0;
4555 // Test if V1 is a SCALAR_TO_VECTOR.
4556 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4557 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4559 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4560 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4562 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4563 !isa<ConstantSDNode>(V1.getOperand(0))) {
4564 bool IsScalarToVector = true;
4565 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4566 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4567 IsScalarToVector = false;
4570 if (IsScalarToVector)
4571 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4573 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4574 DAG.getConstant(Lane, MVT::i32));
4579 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4582 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4583 DAG.getConstant(Imm, MVT::i32));
4586 if (isVREVMask(ShuffleMask, VT, 64))
4587 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4588 if (isVREVMask(ShuffleMask, VT, 32))
4589 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4590 if (isVREVMask(ShuffleMask, VT, 16))
4591 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4593 // Check for Neon shuffles that modify both input vectors in place.
4594 // If both results are used, i.e., if there are two shuffles with the same
4595 // source operands and with masks corresponding to both results of one of
4596 // these operations, DAG memoization will ensure that a single node is
4597 // used for both shuffles.
4598 unsigned WhichResult;
4599 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4600 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4601 V1, V2).getValue(WhichResult);
4602 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4603 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4604 V1, V2).getValue(WhichResult);
4605 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4606 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4607 V1, V2).getValue(WhichResult);
4609 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4610 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4611 V1, V1).getValue(WhichResult);
4612 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4613 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4614 V1, V1).getValue(WhichResult);
4615 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4616 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4617 V1, V1).getValue(WhichResult);
4620 // If the shuffle is not directly supported and it has 4 elements, use
4621 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4622 unsigned NumElts = VT.getVectorNumElements();
4624 unsigned PFIndexes[4];
4625 for (unsigned i = 0; i != 4; ++i) {
4626 if (ShuffleMask[i] < 0)
4629 PFIndexes[i] = ShuffleMask[i];
4632 // Compute the index in the perfect shuffle table.
4633 unsigned PFTableIndex =
4634 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4635 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4636 unsigned Cost = (PFEntry >> 30);
4639 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4642 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4643 if (EltSize >= 32) {
4644 // Do the expansion with floating-point types, since that is what the VFP
4645 // registers are defined to use, and since i64 is not legal.
4646 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4647 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4648 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4649 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4650 SmallVector<SDValue, 8> Ops;
4651 for (unsigned i = 0; i < NumElts; ++i) {
4652 if (ShuffleMask[i] < 0)
4653 Ops.push_back(DAG.getUNDEF(EltVT));
4655 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4656 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4657 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4660 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4661 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4664 if (VT == MVT::v8i8) {
4665 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4666 if (NewOp.getNode())
4673 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4674 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4675 SDValue Lane = Op.getOperand(2);
4676 if (!isa<ConstantSDNode>(Lane))
4682 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4683 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4684 SDValue Lane = Op.getOperand(1);
4685 if (!isa<ConstantSDNode>(Lane))
4688 SDValue Vec = Op.getOperand(0);
4689 if (Op.getValueType() == MVT::i32 &&
4690 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4691 DebugLoc dl = Op.getDebugLoc();
4692 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4698 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4699 // The only time a CONCAT_VECTORS operation can have legal types is when
4700 // two 64-bit vectors are concatenated to a 128-bit vector.
4701 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4702 "unexpected CONCAT_VECTORS");
4703 DebugLoc dl = Op.getDebugLoc();
4704 SDValue Val = DAG.getUNDEF(MVT::v2f64);
4705 SDValue Op0 = Op.getOperand(0);
4706 SDValue Op1 = Op.getOperand(1);
4707 if (Op0.getOpcode() != ISD::UNDEF)
4708 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4709 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4710 DAG.getIntPtrConstant(0));
4711 if (Op1.getOpcode() != ISD::UNDEF)
4712 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4713 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4714 DAG.getIntPtrConstant(1));
4715 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4718 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4719 /// element has been zero/sign-extended, depending on the isSigned parameter,
4720 /// from an integer type half its size.
4721 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4723 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4724 EVT VT = N->getValueType(0);
4725 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4726 SDNode *BVN = N->getOperand(0).getNode();
4727 if (BVN->getValueType(0) != MVT::v4i32 ||
4728 BVN->getOpcode() != ISD::BUILD_VECTOR)
4730 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4731 unsigned HiElt = 1 - LoElt;
4732 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4733 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4734 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4735 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4736 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4739 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4740 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4743 if (Hi0->isNullValue() && Hi1->isNullValue())
4749 if (N->getOpcode() != ISD::BUILD_VECTOR)
4752 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4753 SDNode *Elt = N->getOperand(i).getNode();
4754 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4755 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4756 unsigned HalfSize = EltSize / 2;
4758 if (!isIntN(HalfSize, C->getSExtValue()))
4761 if (!isUIntN(HalfSize, C->getZExtValue()))
4772 /// isSignExtended - Check if a node is a vector value that is sign-extended
4773 /// or a constant BUILD_VECTOR with sign-extended elements.
4774 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4775 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4777 if (isExtendedBUILD_VECTOR(N, DAG, true))
4782 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4783 /// or a constant BUILD_VECTOR with zero-extended elements.
4784 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4785 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4787 if (isExtendedBUILD_VECTOR(N, DAG, false))
4792 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4793 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4794 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4795 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4796 return N->getOperand(0);
4797 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4798 return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4799 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4800 LD->isNonTemporal(), LD->isInvariant(),
4801 LD->getAlignment());
4802 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
4803 // have been legalized as a BITCAST from v4i32.
4804 if (N->getOpcode() == ISD::BITCAST) {
4805 SDNode *BVN = N->getOperand(0).getNode();
4806 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4807 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4808 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4809 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4810 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4812 // Construct a new BUILD_VECTOR with elements truncated to half the size.
4813 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4814 EVT VT = N->getValueType(0);
4815 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4816 unsigned NumElts = VT.getVectorNumElements();
4817 MVT TruncVT = MVT::getIntegerVT(EltSize);
4818 SmallVector<SDValue, 8> Ops;
4819 for (unsigned i = 0; i != NumElts; ++i) {
4820 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4821 const APInt &CInt = C->getAPIntValue();
4822 // Element types smaller than 32 bits are not legal, so use i32 elements.
4823 // The values are implicitly truncated so sext vs. zext doesn't matter.
4824 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4826 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4827 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4830 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4831 unsigned Opcode = N->getOpcode();
4832 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4833 SDNode *N0 = N->getOperand(0).getNode();
4834 SDNode *N1 = N->getOperand(1).getNode();
4835 return N0->hasOneUse() && N1->hasOneUse() &&
4836 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4841 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4842 unsigned Opcode = N->getOpcode();
4843 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4844 SDNode *N0 = N->getOperand(0).getNode();
4845 SDNode *N1 = N->getOperand(1).getNode();
4846 return N0->hasOneUse() && N1->hasOneUse() &&
4847 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4852 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4853 // Multiplications are only custom-lowered for 128-bit vectors so that
4854 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
4855 EVT VT = Op.getValueType();
4856 assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4857 SDNode *N0 = Op.getOperand(0).getNode();
4858 SDNode *N1 = Op.getOperand(1).getNode();
4859 unsigned NewOpc = 0;
4861 bool isN0SExt = isSignExtended(N0, DAG);
4862 bool isN1SExt = isSignExtended(N1, DAG);
4863 if (isN0SExt && isN1SExt)
4864 NewOpc = ARMISD::VMULLs;
4866 bool isN0ZExt = isZeroExtended(N0, DAG);
4867 bool isN1ZExt = isZeroExtended(N1, DAG);
4868 if (isN0ZExt && isN1ZExt)
4869 NewOpc = ARMISD::VMULLu;
4870 else if (isN1SExt || isN1ZExt) {
4871 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4872 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4873 if (isN1SExt && isAddSubSExt(N0, DAG)) {
4874 NewOpc = ARMISD::VMULLs;
4876 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4877 NewOpc = ARMISD::VMULLu;
4879 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4881 NewOpc = ARMISD::VMULLu;
4887 if (VT == MVT::v2i64)
4888 // Fall through to expand this. It is not legal.
4891 // Other vector multiplications are legal.
4896 // Legalize to a VMULL instruction.
4897 DebugLoc DL = Op.getDebugLoc();
4899 SDValue Op1 = SkipExtension(N1, DAG);
4901 Op0 = SkipExtension(N0, DAG);
4902 assert(Op0.getValueType().is64BitVector() &&
4903 Op1.getValueType().is64BitVector() &&
4904 "unexpected types for extended operands to VMULL");
4905 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4908 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4909 // isel lowering to take advantage of no-stall back to back vmul + vmla.
4916 SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4917 SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4918 EVT Op1VT = Op1.getValueType();
4919 return DAG.getNode(N0->getOpcode(), DL, VT,
4920 DAG.getNode(NewOpc, DL, VT,
4921 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4922 DAG.getNode(NewOpc, DL, VT,
4923 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4927 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4929 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4930 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4931 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4932 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4933 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4934 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4935 // Get reciprocal estimate.
4936 // float4 recip = vrecpeq_f32(yf);
4937 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4938 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4939 // Because char has a smaller range than uchar, we can actually get away
4940 // without any newton steps. This requires that we use a weird bias
4941 // of 0xb000, however (again, this has been exhaustively tested).
4942 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4943 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4944 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4945 Y = DAG.getConstant(0xb000, MVT::i32);
4946 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4947 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4948 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4949 // Convert back to short.
4950 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4951 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4956 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4958 // Convert to float.
4959 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4960 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4961 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4962 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4963 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4964 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4966 // Use reciprocal estimate and one refinement step.
4967 // float4 recip = vrecpeq_f32(yf);
4968 // recip *= vrecpsq_f32(yf, recip);
4969 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4970 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4971 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4972 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4974 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4975 // Because short has a smaller range than ushort, we can actually get away
4976 // with only a single newton step. This requires that we use a weird bias
4977 // of 89, however (again, this has been exhaustively tested).
4978 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4979 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4980 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4981 N1 = DAG.getConstant(0x89, MVT::i32);
4982 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4983 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4984 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4985 // Convert back to integer and return.
4986 // return vmovn_s32(vcvt_s32_f32(result));
4987 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4988 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4992 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4993 EVT VT = Op.getValueType();
4994 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4995 "unexpected type for custom-lowering ISD::SDIV");
4997 DebugLoc dl = Op.getDebugLoc();
4998 SDValue N0 = Op.getOperand(0);
4999 SDValue N1 = Op.getOperand(1);
5002 if (VT == MVT::v8i8) {
5003 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5004 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5006 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5007 DAG.getIntPtrConstant(4));
5008 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5009 DAG.getIntPtrConstant(4));
5010 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5011 DAG.getIntPtrConstant(0));
5012 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5013 DAG.getIntPtrConstant(0));
5015 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5016 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5018 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5019 N0 = LowerCONCAT_VECTORS(N0, DAG);
5021 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5024 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5027 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5028 EVT VT = Op.getValueType();
5029 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5030 "unexpected type for custom-lowering ISD::UDIV");
5032 DebugLoc dl = Op.getDebugLoc();
5033 SDValue N0 = Op.getOperand(0);
5034 SDValue N1 = Op.getOperand(1);
5037 if (VT == MVT::v8i8) {
5038 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5039 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5041 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5042 DAG.getIntPtrConstant(4));
5043 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5044 DAG.getIntPtrConstant(4));
5045 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5046 DAG.getIntPtrConstant(0));
5047 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5048 DAG.getIntPtrConstant(0));
5050 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5051 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5053 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5054 N0 = LowerCONCAT_VECTORS(N0, DAG);
5056 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5057 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5062 // v4i16 sdiv ... Convert to float.
5063 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5064 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5065 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5066 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5067 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5068 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5070 // Use reciprocal estimate and two refinement steps.
5071 // float4 recip = vrecpeq_f32(yf);
5072 // recip *= vrecpsq_f32(yf, recip);
5073 // recip *= vrecpsq_f32(yf, recip);
5074 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5075 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5076 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5077 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5079 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5080 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5081 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5083 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5084 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5085 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5086 // and that it will never cause us to return an answer too large).
5087 // float4 result = as_float4(as_int4(xf*recip) + 2);
5088 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5089 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5090 N1 = DAG.getConstant(2, MVT::i32);
5091 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5092 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5093 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5094 // Convert back to integer and return.
5095 // return vmovn_u32(vcvt_s32_f32(result));
5096 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5097 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5101 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5102 EVT VT = Op.getNode()->getValueType(0);
5103 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5106 bool ExtraOp = false;
5107 switch (Op.getOpcode()) {
5108 default: llvm_unreachable("Invalid code");
5109 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5110 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5111 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5112 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5116 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5118 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5119 Op.getOperand(1), Op.getOperand(2));
5122 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5123 // Monotonic load/store is legal for all targets
5124 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5127 // Aquire/Release load/store is not legal for targets without a
5128 // dmb or equivalent available.
5134 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5135 SelectionDAG &DAG, unsigned NewOp) {
5136 DebugLoc dl = Node->getDebugLoc();
5137 assert (Node->getValueType(0) == MVT::i64 &&
5138 "Only know how to expand i64 atomics");
5140 SmallVector<SDValue, 6> Ops;
5141 Ops.push_back(Node->getOperand(0)); // Chain
5142 Ops.push_back(Node->getOperand(1)); // Ptr
5144 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5145 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5146 // High part of Val1
5147 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5148 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5149 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5150 // High part of Val1
5151 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5152 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5153 // High part of Val2
5154 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5155 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5157 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5159 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5160 cast<MemSDNode>(Node)->getMemOperand());
5161 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5162 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5163 Results.push_back(Result.getValue(2));
5166 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5167 switch (Op.getOpcode()) {
5168 default: llvm_unreachable("Don't know how to custom lower this!");
5169 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5170 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5171 case ISD::GlobalAddress:
5172 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5173 LowerGlobalAddressELF(Op, DAG);
5174 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5175 case ISD::SELECT: return LowerSELECT(Op, DAG);
5176 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5177 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5178 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5179 case ISD::VASTART: return LowerVASTART(Op, DAG);
5180 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5181 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5182 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5183 case ISD::SINT_TO_FP:
5184 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5185 case ISD::FP_TO_SINT:
5186 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5187 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5188 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5189 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5190 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5191 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5192 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5193 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5195 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5198 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5199 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5200 case ISD::SRL_PARTS:
5201 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5202 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5203 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5204 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5205 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5206 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5207 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5208 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5209 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5210 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5211 case ISD::MUL: return LowerMUL(Op, DAG);
5212 case ISD::SDIV: return LowerSDIV(Op, DAG);
5213 case ISD::UDIV: return LowerUDIV(Op, DAG);
5217 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5218 case ISD::ATOMIC_LOAD:
5219 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5223 /// ReplaceNodeResults - Replace the results of node with an illegal result
5224 /// type with new values built out of custom code.
5225 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5226 SmallVectorImpl<SDValue>&Results,
5227 SelectionDAG &DAG) const {
5229 switch (N->getOpcode()) {
5231 llvm_unreachable("Don't know how to custom expand this!");
5233 Res = ExpandBITCAST(N, DAG);
5237 Res = Expand64BitShift(N, DAG, Subtarget);
5239 case ISD::ATOMIC_LOAD_ADD:
5240 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5242 case ISD::ATOMIC_LOAD_AND:
5243 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5245 case ISD::ATOMIC_LOAD_NAND:
5246 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5248 case ISD::ATOMIC_LOAD_OR:
5249 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5251 case ISD::ATOMIC_LOAD_SUB:
5252 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5254 case ISD::ATOMIC_LOAD_XOR:
5255 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5257 case ISD::ATOMIC_SWAP:
5258 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5260 case ISD::ATOMIC_CMP_SWAP:
5261 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5265 Results.push_back(Res);
5268 //===----------------------------------------------------------------------===//
5269 // ARM Scheduler Hooks
5270 //===----------------------------------------------------------------------===//
5273 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5274 MachineBasicBlock *BB,
5275 unsigned Size) const {
5276 unsigned dest = MI->getOperand(0).getReg();
5277 unsigned ptr = MI->getOperand(1).getReg();
5278 unsigned oldval = MI->getOperand(2).getReg();
5279 unsigned newval = MI->getOperand(3).getReg();
5280 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5281 DebugLoc dl = MI->getDebugLoc();
5282 bool isThumb2 = Subtarget->isThumb2();
5284 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5285 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5286 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5287 (const TargetRegisterClass*)&ARM::GPRRegClass);
5290 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5291 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5292 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5295 unsigned ldrOpc, strOpc;
5297 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5299 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5300 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5303 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5304 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5307 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5308 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5312 MachineFunction *MF = BB->getParent();
5313 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5314 MachineFunction::iterator It = BB;
5315 ++It; // insert the new blocks after the current block
5317 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5318 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5319 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5320 MF->insert(It, loop1MBB);
5321 MF->insert(It, loop2MBB);
5322 MF->insert(It, exitMBB);
5324 // Transfer the remainder of BB and its successor edges to exitMBB.
5325 exitMBB->splice(exitMBB->begin(), BB,
5326 llvm::next(MachineBasicBlock::iterator(MI)),
5328 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5332 // fallthrough --> loop1MBB
5333 BB->addSuccessor(loop1MBB);
5336 // ldrex dest, [ptr]
5340 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5341 if (ldrOpc == ARM::t2LDREX)
5343 AddDefaultPred(MIB);
5344 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5345 .addReg(dest).addReg(oldval));
5346 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5347 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5348 BB->addSuccessor(loop2MBB);
5349 BB->addSuccessor(exitMBB);
5352 // strex scratch, newval, [ptr]
5356 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5357 if (strOpc == ARM::t2STREX)
5359 AddDefaultPred(MIB);
5360 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5361 .addReg(scratch).addImm(0));
5362 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5363 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5364 BB->addSuccessor(loop1MBB);
5365 BB->addSuccessor(exitMBB);
5371 MI->eraseFromParent(); // The instruction is gone now.
5377 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5378 unsigned Size, unsigned BinOpcode) const {
5379 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5380 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5382 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5383 MachineFunction *MF = BB->getParent();
5384 MachineFunction::iterator It = BB;
5387 unsigned dest = MI->getOperand(0).getReg();
5388 unsigned ptr = MI->getOperand(1).getReg();
5389 unsigned incr = MI->getOperand(2).getReg();
5390 DebugLoc dl = MI->getDebugLoc();
5391 bool isThumb2 = Subtarget->isThumb2();
5393 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5395 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5396 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5399 unsigned ldrOpc, strOpc;
5401 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5403 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5404 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5407 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5408 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5411 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5412 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5416 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5417 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5418 MF->insert(It, loopMBB);
5419 MF->insert(It, exitMBB);
5421 // Transfer the remainder of BB and its successor edges to exitMBB.
5422 exitMBB->splice(exitMBB->begin(), BB,
5423 llvm::next(MachineBasicBlock::iterator(MI)),
5425 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5427 const TargetRegisterClass *TRC = isThumb2 ?
5428 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5429 (const TargetRegisterClass*)&ARM::GPRRegClass;
5430 unsigned scratch = MRI.createVirtualRegister(TRC);
5431 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5435 // fallthrough --> loopMBB
5436 BB->addSuccessor(loopMBB);
5440 // <binop> scratch2, dest, incr
5441 // strex scratch, scratch2, ptr
5444 // fallthrough --> exitMBB
5446 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5447 if (ldrOpc == ARM::t2LDREX)
5449 AddDefaultPred(MIB);
5451 // operand order needs to go the other way for NAND
5452 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5453 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5454 addReg(incr).addReg(dest)).addReg(0);
5456 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5457 addReg(dest).addReg(incr)).addReg(0);
5460 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5461 if (strOpc == ARM::t2STREX)
5463 AddDefaultPred(MIB);
5464 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5465 .addReg(scratch).addImm(0));
5466 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5467 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5469 BB->addSuccessor(loopMBB);
5470 BB->addSuccessor(exitMBB);
5476 MI->eraseFromParent(); // The instruction is gone now.
5482 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5483 MachineBasicBlock *BB,
5486 ARMCC::CondCodes Cond) const {
5487 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5489 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5490 MachineFunction *MF = BB->getParent();
5491 MachineFunction::iterator It = BB;
5494 unsigned dest = MI->getOperand(0).getReg();
5495 unsigned ptr = MI->getOperand(1).getReg();
5496 unsigned incr = MI->getOperand(2).getReg();
5497 unsigned oldval = dest;
5498 DebugLoc dl = MI->getDebugLoc();
5499 bool isThumb2 = Subtarget->isThumb2();
5501 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5503 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5504 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5507 unsigned ldrOpc, strOpc, extendOpc;
5509 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5511 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5512 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5513 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5516 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5517 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5518 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5521 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5522 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5527 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5528 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5529 MF->insert(It, loopMBB);
5530 MF->insert(It, exitMBB);
5532 // Transfer the remainder of BB and its successor edges to exitMBB.
5533 exitMBB->splice(exitMBB->begin(), BB,
5534 llvm::next(MachineBasicBlock::iterator(MI)),
5536 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5538 const TargetRegisterClass *TRC = isThumb2 ?
5539 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5540 (const TargetRegisterClass*)&ARM::GPRRegClass;
5541 unsigned scratch = MRI.createVirtualRegister(TRC);
5542 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5546 // fallthrough --> loopMBB
5547 BB->addSuccessor(loopMBB);
5551 // (sign extend dest, if required)
5553 // cmov.cond scratch2, dest, incr
5554 // strex scratch, scratch2, ptr
5557 // fallthrough --> exitMBB
5559 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5560 if (ldrOpc == ARM::t2LDREX)
5562 AddDefaultPred(MIB);
5564 // Sign extend the value, if necessary.
5565 if (signExtend && extendOpc) {
5566 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5567 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5572 // Build compare and cmov instructions.
5573 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5574 .addReg(oldval).addReg(incr));
5575 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5576 .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5578 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5579 if (strOpc == ARM::t2STREX)
5581 AddDefaultPred(MIB);
5582 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5583 .addReg(scratch).addImm(0));
5584 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5585 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5587 BB->addSuccessor(loopMBB);
5588 BB->addSuccessor(exitMBB);
5594 MI->eraseFromParent(); // The instruction is gone now.
5600 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5601 unsigned Op1, unsigned Op2,
5602 bool NeedsCarry, bool IsCmpxchg) const {
5603 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5604 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5606 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5607 MachineFunction *MF = BB->getParent();
5608 MachineFunction::iterator It = BB;
5611 unsigned destlo = MI->getOperand(0).getReg();
5612 unsigned desthi = MI->getOperand(1).getReg();
5613 unsigned ptr = MI->getOperand(2).getReg();
5614 unsigned vallo = MI->getOperand(3).getReg();
5615 unsigned valhi = MI->getOperand(4).getReg();
5616 DebugLoc dl = MI->getDebugLoc();
5617 bool isThumb2 = Subtarget->isThumb2();
5619 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5621 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5622 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5623 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5626 unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5627 unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5629 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5630 MachineBasicBlock *contBB = 0, *cont2BB = 0;
5632 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5633 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5635 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5636 MF->insert(It, loopMBB);
5638 MF->insert(It, contBB);
5639 MF->insert(It, cont2BB);
5641 MF->insert(It, exitMBB);
5643 // Transfer the remainder of BB and its successor edges to exitMBB.
5644 exitMBB->splice(exitMBB->begin(), BB,
5645 llvm::next(MachineBasicBlock::iterator(MI)),
5647 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5649 const TargetRegisterClass *TRC = isThumb2 ?
5650 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5651 (const TargetRegisterClass*)&ARM::GPRRegClass;
5652 unsigned storesuccess = MRI.createVirtualRegister(TRC);
5656 // fallthrough --> loopMBB
5657 BB->addSuccessor(loopMBB);
5660 // ldrexd r2, r3, ptr
5661 // <binopa> r0, r2, incr
5662 // <binopb> r1, r3, incr
5663 // strexd storesuccess, r0, r1, ptr
5664 // cmp storesuccess, #0
5666 // fallthrough --> exitMBB
5668 // Note that the registers are explicitly specified because there is not any
5669 // way to force the register allocator to allocate a register pair.
5671 // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5672 // need to properly enforce the restriction that the two output registers
5673 // for ldrexd must be different.
5676 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5677 .addReg(ARM::R2, RegState::Define)
5678 .addReg(ARM::R3, RegState::Define).addReg(ptr));
5679 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
5680 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5681 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5685 for (unsigned i = 0; i < 2; i++) {
5686 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5688 .addReg(i == 0 ? destlo : desthi)
5689 .addReg(i == 0 ? vallo : valhi));
5690 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5691 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5692 BB->addSuccessor(exitMBB);
5693 BB->addSuccessor(i == 0 ? contBB : cont2BB);
5694 BB = (i == 0 ? contBB : cont2BB);
5697 // Copy to physregs for strexd
5698 unsigned setlo = MI->getOperand(5).getReg();
5699 unsigned sethi = MI->getOperand(6).getReg();
5700 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5701 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5703 // Perform binary operation
5704 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5705 .addReg(destlo).addReg(vallo))
5706 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5707 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5708 .addReg(desthi).addReg(valhi)).addReg(0);
5710 // Copy to physregs for strexd
5711 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5712 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5716 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5717 .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5719 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5720 .addReg(storesuccess).addImm(0));
5721 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5722 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5724 BB->addSuccessor(loopMBB);
5725 BB->addSuccessor(exitMBB);
5731 MI->eraseFromParent(); // The instruction is gone now.
5736 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5737 /// registers the function context.
5738 void ARMTargetLowering::
5739 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5740 MachineBasicBlock *DispatchBB, int FI) const {
5741 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5742 DebugLoc dl = MI->getDebugLoc();
5743 MachineFunction *MF = MBB->getParent();
5744 MachineRegisterInfo *MRI = &MF->getRegInfo();
5745 MachineConstantPool *MCP = MF->getConstantPool();
5746 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5747 const Function *F = MF->getFunction();
5749 bool isThumb = Subtarget->isThumb();
5750 bool isThumb2 = Subtarget->isThumb2();
5752 unsigned PCLabelId = AFI->createPICLabelUId();
5753 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5754 ARMConstantPoolValue *CPV =
5755 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5756 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5758 const TargetRegisterClass *TRC = isThumb ?
5759 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5760 (const TargetRegisterClass*)&ARM::GPRRegClass;
5762 // Grab constant pool and fixed stack memory operands.
5763 MachineMemOperand *CPMMO =
5764 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5765 MachineMemOperand::MOLoad, 4, 4);
5767 MachineMemOperand *FIMMOSt =
5768 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5769 MachineMemOperand::MOStore, 4, 4);
5771 // Load the address of the dispatch MBB into the jump buffer.
5773 // Incoming value: jbuf
5774 // ldr.n r5, LCPI1_1
5777 // str r5, [$jbuf, #+4] ; &jbuf[1]
5778 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5779 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5780 .addConstantPoolIndex(CPI)
5781 .addMemOperand(CPMMO));
5782 // Set the low bit because of thumb mode.
5783 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5785 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5786 .addReg(NewVReg1, RegState::Kill)
5788 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5789 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5790 .addReg(NewVReg2, RegState::Kill)
5792 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5793 .addReg(NewVReg3, RegState::Kill)
5795 .addImm(36) // &jbuf[1] :: pc
5796 .addMemOperand(FIMMOSt));
5797 } else if (isThumb) {
5798 // Incoming value: jbuf
5799 // ldr.n r1, LCPI1_4
5803 // add r2, $jbuf, #+4 ; &jbuf[1]
5805 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5806 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5807 .addConstantPoolIndex(CPI)
5808 .addMemOperand(CPMMO));
5809 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5810 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5811 .addReg(NewVReg1, RegState::Kill)
5813 // Set the low bit because of thumb mode.
5814 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5815 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5816 .addReg(ARM::CPSR, RegState::Define)
5818 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5819 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5820 .addReg(ARM::CPSR, RegState::Define)
5821 .addReg(NewVReg2, RegState::Kill)
5822 .addReg(NewVReg3, RegState::Kill));
5823 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5824 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5826 .addImm(36)); // &jbuf[1] :: pc
5827 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5828 .addReg(NewVReg4, RegState::Kill)
5829 .addReg(NewVReg5, RegState::Kill)
5831 .addMemOperand(FIMMOSt));
5833 // Incoming value: jbuf
5836 // str r1, [$jbuf, #+4] ; &jbuf[1]
5837 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5838 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
5839 .addConstantPoolIndex(CPI)
5841 .addMemOperand(CPMMO));
5842 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5843 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5844 .addReg(NewVReg1, RegState::Kill)
5845 .addImm(PCLabelId));
5846 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5847 .addReg(NewVReg2, RegState::Kill)
5849 .addImm(36) // &jbuf[1] :: pc
5850 .addMemOperand(FIMMOSt));
5854 MachineBasicBlock *ARMTargetLowering::
5855 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5856 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5857 DebugLoc dl = MI->getDebugLoc();
5858 MachineFunction *MF = MBB->getParent();
5859 MachineRegisterInfo *MRI = &MF->getRegInfo();
5860 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5861 MachineFrameInfo *MFI = MF->getFrameInfo();
5862 int FI = MFI->getFunctionContextIndex();
5864 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5865 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5866 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5868 // Get a mapping of the call site numbers to all of the landing pads they're
5870 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5871 unsigned MaxCSNum = 0;
5872 MachineModuleInfo &MMI = MF->getMMI();
5873 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5875 if (!BB->isLandingPad()) continue;
5877 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5879 for (MachineBasicBlock::iterator
5880 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5881 if (!II->isEHLabel()) continue;
5883 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5884 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5886 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5887 for (SmallVectorImpl<unsigned>::iterator
5888 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5889 CSI != CSE; ++CSI) {
5890 CallSiteNumToLPad[*CSI].push_back(BB);
5891 MaxCSNum = std::max(MaxCSNum, *CSI);
5897 // Get an ordered list of the machine basic blocks for the jump table.
5898 std::vector<MachineBasicBlock*> LPadList;
5899 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5900 LPadList.reserve(CallSiteNumToLPad.size());
5901 for (unsigned I = 1; I <= MaxCSNum; ++I) {
5902 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5903 for (SmallVectorImpl<MachineBasicBlock*>::iterator
5904 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5905 LPadList.push_back(*II);
5906 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5910 assert(!LPadList.empty() &&
5911 "No landing pad destinations for the dispatch jump table!");
5913 // Create the jump table and associated information.
5914 MachineJumpTableInfo *JTI =
5915 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5916 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5917 unsigned UId = AFI->createJumpTableUId();
5919 // Create the MBBs for the dispatch code.
5921 // Shove the dispatch's address into the return slot in the function context.
5922 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5923 DispatchBB->setIsLandingPad();
5925 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5926 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5927 DispatchBB->addSuccessor(TrapBB);
5929 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5930 DispatchBB->addSuccessor(DispContBB);
5933 MF->insert(MF->end(), DispatchBB);
5934 MF->insert(MF->end(), DispContBB);
5935 MF->insert(MF->end(), TrapBB);
5937 // Insert code into the entry block that creates and registers the function
5939 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5941 MachineMemOperand *FIMMOLd =
5942 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5943 MachineMemOperand::MOLoad |
5944 MachineMemOperand::MOVolatile, 4, 4);
5946 if (AFI->isThumb1OnlyFunction())
5947 BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5948 else if (!Subtarget->hasVFP2())
5949 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5951 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5953 unsigned NumLPads = LPadList.size();
5954 if (Subtarget->isThumb2()) {
5955 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5956 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5959 .addMemOperand(FIMMOLd));
5961 if (NumLPads < 256) {
5962 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5964 .addImm(LPadList.size()));
5966 unsigned VReg1 = MRI->createVirtualRegister(TRC);
5967 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5968 .addImm(NumLPads & 0xFFFF));
5970 unsigned VReg2 = VReg1;
5971 if ((NumLPads & 0xFFFF0000) != 0) {
5972 VReg2 = MRI->createVirtualRegister(TRC);
5973 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5975 .addImm(NumLPads >> 16));
5978 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5983 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5988 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5989 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5990 .addJumpTableIndex(MJTI)
5993 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5996 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5997 .addReg(NewVReg3, RegState::Kill)
5999 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6001 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6002 .addReg(NewVReg4, RegState::Kill)
6004 .addJumpTableIndex(MJTI)
6006 } else if (Subtarget->isThumb()) {
6007 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6008 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6011 .addMemOperand(FIMMOLd));
6013 if (NumLPads < 256) {
6014 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6018 MachineConstantPool *ConstantPool = MF->getConstantPool();
6019 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6020 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6022 // MachineConstantPool wants an explicit alignment.
6023 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6025 Align = getTargetData()->getTypeAllocSize(C->getType());
6026 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6028 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6029 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6030 .addReg(VReg1, RegState::Define)
6031 .addConstantPoolIndex(Idx));
6032 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6037 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6042 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6043 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6044 .addReg(ARM::CPSR, RegState::Define)
6048 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6049 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6050 .addJumpTableIndex(MJTI)
6053 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6054 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6055 .addReg(ARM::CPSR, RegState::Define)
6056 .addReg(NewVReg2, RegState::Kill)
6059 MachineMemOperand *JTMMOLd =
6060 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6061 MachineMemOperand::MOLoad, 4, 4);
6063 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6064 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6065 .addReg(NewVReg4, RegState::Kill)
6067 .addMemOperand(JTMMOLd));
6069 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6070 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6071 .addReg(ARM::CPSR, RegState::Define)
6072 .addReg(NewVReg5, RegState::Kill)
6075 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6076 .addReg(NewVReg6, RegState::Kill)
6077 .addJumpTableIndex(MJTI)
6080 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6081 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6084 .addMemOperand(FIMMOLd));
6086 if (NumLPads < 256) {
6087 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6090 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6091 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6092 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6093 .addImm(NumLPads & 0xFFFF));
6095 unsigned VReg2 = VReg1;
6096 if ((NumLPads & 0xFFFF0000) != 0) {
6097 VReg2 = MRI->createVirtualRegister(TRC);
6098 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6100 .addImm(NumLPads >> 16));
6103 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6107 MachineConstantPool *ConstantPool = MF->getConstantPool();
6108 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6109 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6111 // MachineConstantPool wants an explicit alignment.
6112 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6114 Align = getTargetData()->getTypeAllocSize(C->getType());
6115 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6117 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6118 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6119 .addReg(VReg1, RegState::Define)
6120 .addConstantPoolIndex(Idx)
6122 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6124 .addReg(VReg1, RegState::Kill));
6127 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6132 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6134 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6136 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6137 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6138 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6139 .addJumpTableIndex(MJTI)
6142 MachineMemOperand *JTMMOLd =
6143 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6144 MachineMemOperand::MOLoad, 4, 4);
6145 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6147 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6148 .addReg(NewVReg3, RegState::Kill)
6151 .addMemOperand(JTMMOLd));
6153 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6154 .addReg(NewVReg5, RegState::Kill)
6156 .addJumpTableIndex(MJTI)
6160 // Add the jump table entries as successors to the MBB.
6161 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6162 for (std::vector<MachineBasicBlock*>::iterator
6163 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6164 MachineBasicBlock *CurMBB = *I;
6165 if (SeenMBBs.insert(CurMBB))
6166 DispContBB->addSuccessor(CurMBB);
6169 // N.B. the order the invoke BBs are processed in doesn't matter here.
6170 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6171 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6172 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6173 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6174 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6175 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6176 MachineBasicBlock *BB = *I;
6178 // Remove the landing pad successor from the invoke block and replace it
6179 // with the new dispatch block.
6180 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6182 while (!Successors.empty()) {
6183 MachineBasicBlock *SMBB = Successors.pop_back_val();
6184 if (SMBB->isLandingPad()) {
6185 BB->removeSuccessor(SMBB);
6186 MBBLPads.push_back(SMBB);
6190 BB->addSuccessor(DispatchBB);
6192 // Find the invoke call and mark all of the callee-saved registers as
6193 // 'implicit defined' so that they're spilled. This prevents code from
6194 // moving instructions to before the EH block, where they will never be
6196 for (MachineBasicBlock::reverse_iterator
6197 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6198 if (!II->isCall()) continue;
6200 DenseMap<unsigned, bool> DefRegs;
6201 for (MachineInstr::mop_iterator
6202 OI = II->operands_begin(), OE = II->operands_end();
6204 if (!OI->isReg()) continue;
6205 DefRegs[OI->getReg()] = true;
6208 MachineInstrBuilder MIB(&*II);
6210 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6211 unsigned Reg = SavedRegs[i];
6212 if (Subtarget->isThumb2() &&
6213 !ARM::tGPRRegClass.contains(Reg) &&
6214 !ARM::hGPRRegClass.contains(Reg))
6216 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6218 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6221 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6228 // Mark all former landing pads as non-landing pads. The dispatch is the only
6230 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6231 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6232 (*I)->setIsLandingPad(false);
6234 // The instruction is gone now.
6235 MI->eraseFromParent();
6241 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6242 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6243 E = MBB->succ_end(); I != E; ++I)
6246 llvm_unreachable("Expecting a BB with two successors!");
6249 MachineBasicBlock *ARMTargetLowering::
6250 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6251 // This pseudo instruction has 3 operands: dst, src, size
6252 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6253 // Otherwise, we will generate unrolled scalar copies.
6254 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6255 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6256 MachineFunction::iterator It = BB;
6259 unsigned dest = MI->getOperand(0).getReg();
6260 unsigned src = MI->getOperand(1).getReg();
6261 unsigned SizeVal = MI->getOperand(2).getImm();
6262 unsigned Align = MI->getOperand(3).getImm();
6263 DebugLoc dl = MI->getDebugLoc();
6265 bool isThumb2 = Subtarget->isThumb2();
6266 MachineFunction *MF = BB->getParent();
6267 MachineRegisterInfo &MRI = MF->getRegInfo();
6268 unsigned ldrOpc, strOpc, UnitSize = 0;
6270 const TargetRegisterClass *TRC = isThumb2 ?
6271 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6272 (const TargetRegisterClass*)&ARM::GPRRegClass;
6273 const TargetRegisterClass *TRC_Vec = 0;
6276 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6277 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6279 } else if (Align & 2) {
6280 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6281 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6284 // Check whether we can use NEON instructions.
6285 if (!MF->getFunction()->hasFnAttr(Attribute::NoImplicitFloat) &&
6286 Subtarget->hasNEON()) {
6287 if ((Align % 16 == 0) && SizeVal >= 16) {
6288 ldrOpc = ARM::VLD1q32wb_fixed;
6289 strOpc = ARM::VST1q32wb_fixed;
6291 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6293 else if ((Align % 8 == 0) && SizeVal >= 8) {
6294 ldrOpc = ARM::VLD1d32wb_fixed;
6295 strOpc = ARM::VST1d32wb_fixed;
6297 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6300 // Can't use NEON instructions.
6301 if (UnitSize == 0) {
6302 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6303 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6308 unsigned BytesLeft = SizeVal % UnitSize;
6309 unsigned LoopSize = SizeVal - BytesLeft;
6311 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6312 // Use LDR and STR to copy.
6313 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6314 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6315 unsigned srcIn = src;
6316 unsigned destIn = dest;
6317 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6318 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6319 unsigned srcOut = MRI.createVirtualRegister(TRC);
6320 unsigned destOut = MRI.createVirtualRegister(TRC);
6321 if (UnitSize >= 8) {
6322 AddDefaultPred(BuildMI(*BB, MI, dl,
6323 TII->get(ldrOpc), scratch)
6324 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6326 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6327 .addReg(destIn).addImm(0).addReg(scratch));
6328 } else if (isThumb2) {
6329 AddDefaultPred(BuildMI(*BB, MI, dl,
6330 TII->get(ldrOpc), scratch)
6331 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6333 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6334 .addReg(scratch).addReg(destIn)
6337 AddDefaultPred(BuildMI(*BB, MI, dl,
6338 TII->get(ldrOpc), scratch)
6339 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6342 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6343 .addReg(scratch).addReg(destIn)
6344 .addReg(0).addImm(UnitSize));
6350 // Handle the leftover bytes with LDRB and STRB.
6351 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6352 // [destOut] = STRB_POST(scratch, destIn, 1)
6353 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6354 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6355 for (unsigned i = 0; i < BytesLeft; i++) {
6356 unsigned scratch = MRI.createVirtualRegister(TRC);
6357 unsigned srcOut = MRI.createVirtualRegister(TRC);
6358 unsigned destOut = MRI.createVirtualRegister(TRC);
6360 AddDefaultPred(BuildMI(*BB, MI, dl,
6361 TII->get(ldrOpc),scratch)
6362 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6364 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6365 .addReg(scratch).addReg(destIn)
6366 .addReg(0).addImm(1));
6368 AddDefaultPred(BuildMI(*BB, MI, dl,
6369 TII->get(ldrOpc),scratch)
6370 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6372 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6373 .addReg(scratch).addReg(destIn)
6374 .addReg(0).addImm(1));
6379 MI->eraseFromParent(); // The instruction is gone now.
6383 // Expand the pseudo op to a loop.
6386 // movw varEnd, # --> with thumb2
6388 // ldrcp varEnd, idx --> without thumb2
6389 // fallthrough --> loopMBB
6391 // PHI varPhi, varEnd, varLoop
6392 // PHI srcPhi, src, srcLoop
6393 // PHI destPhi, dst, destLoop
6394 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6395 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6396 // subs varLoop, varPhi, #UnitSize
6398 // fallthrough --> exitMBB
6400 // epilogue to handle left-over bytes
6401 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6402 // [destOut] = STRB_POST(scratch, destLoop, 1)
6403 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6404 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6405 MF->insert(It, loopMBB);
6406 MF->insert(It, exitMBB);
6408 // Transfer the remainder of BB and its successor edges to exitMBB.
6409 exitMBB->splice(exitMBB->begin(), BB,
6410 llvm::next(MachineBasicBlock::iterator(MI)),
6412 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6414 // Load an immediate to varEnd.
6415 unsigned varEnd = MRI.createVirtualRegister(TRC);
6417 unsigned VReg1 = varEnd;
6418 if ((LoopSize & 0xFFFF0000) != 0)
6419 VReg1 = MRI.createVirtualRegister(TRC);
6420 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6421 .addImm(LoopSize & 0xFFFF));
6423 if ((LoopSize & 0xFFFF0000) != 0)
6424 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6426 .addImm(LoopSize >> 16));
6428 MachineConstantPool *ConstantPool = MF->getConstantPool();
6429 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6430 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6432 // MachineConstantPool wants an explicit alignment.
6433 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6435 Align = getTargetData()->getTypeAllocSize(C->getType());
6436 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6438 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6439 .addReg(varEnd, RegState::Define)
6440 .addConstantPoolIndex(Idx)
6443 BB->addSuccessor(loopMBB);
6445 // Generate the loop body:
6446 // varPhi = PHI(varLoop, varEnd)
6447 // srcPhi = PHI(srcLoop, src)
6448 // destPhi = PHI(destLoop, dst)
6449 MachineBasicBlock *entryBB = BB;
6451 unsigned varLoop = MRI.createVirtualRegister(TRC);
6452 unsigned varPhi = MRI.createVirtualRegister(TRC);
6453 unsigned srcLoop = MRI.createVirtualRegister(TRC);
6454 unsigned srcPhi = MRI.createVirtualRegister(TRC);
6455 unsigned destLoop = MRI.createVirtualRegister(TRC);
6456 unsigned destPhi = MRI.createVirtualRegister(TRC);
6458 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6459 .addReg(varLoop).addMBB(loopMBB)
6460 .addReg(varEnd).addMBB(entryBB);
6461 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6462 .addReg(srcLoop).addMBB(loopMBB)
6463 .addReg(src).addMBB(entryBB);
6464 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6465 .addReg(destLoop).addMBB(loopMBB)
6466 .addReg(dest).addMBB(entryBB);
6468 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6469 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6470 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6471 if (UnitSize >= 8) {
6472 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6473 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6475 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6476 .addReg(destPhi).addImm(0).addReg(scratch));
6477 } else if (isThumb2) {
6478 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6479 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6481 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6482 .addReg(scratch).addReg(destPhi)
6485 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6486 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6489 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6490 .addReg(scratch).addReg(destPhi)
6491 .addReg(0).addImm(UnitSize));
6494 // Decrement loop variable by UnitSize.
6495 MachineInstrBuilder MIB = BuildMI(BB, dl,
6496 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6497 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6498 MIB->getOperand(5).setReg(ARM::CPSR);
6499 MIB->getOperand(5).setIsDef(true);
6501 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6502 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6504 // loopMBB can loop back to loopMBB or fall through to exitMBB.
6505 BB->addSuccessor(loopMBB);
6506 BB->addSuccessor(exitMBB);
6508 // Add epilogue to handle BytesLeft.
6510 MachineInstr *StartOfExit = exitMBB->begin();
6511 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6512 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6514 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6515 // [destOut] = STRB_POST(scratch, destLoop, 1)
6516 unsigned srcIn = srcLoop;
6517 unsigned destIn = destLoop;
6518 for (unsigned i = 0; i < BytesLeft; i++) {
6519 unsigned scratch = MRI.createVirtualRegister(TRC);
6520 unsigned srcOut = MRI.createVirtualRegister(TRC);
6521 unsigned destOut = MRI.createVirtualRegister(TRC);
6523 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6524 TII->get(ldrOpc),scratch)
6525 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6527 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6528 .addReg(scratch).addReg(destIn)
6531 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6532 TII->get(ldrOpc),scratch)
6533 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6535 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6536 .addReg(scratch).addReg(destIn)
6537 .addReg(0).addImm(1));
6543 MI->eraseFromParent(); // The instruction is gone now.
6548 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6549 MachineBasicBlock *BB) const {
6550 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6551 DebugLoc dl = MI->getDebugLoc();
6552 bool isThumb2 = Subtarget->isThumb2();
6553 switch (MI->getOpcode()) {
6556 llvm_unreachable("Unexpected instr type to insert");
6558 // The Thumb2 pre-indexed stores have the same MI operands, they just
6559 // define them differently in the .td files from the isel patterns, so
6560 // they need pseudos.
6561 case ARM::t2STR_preidx:
6562 MI->setDesc(TII->get(ARM::t2STR_PRE));
6564 case ARM::t2STRB_preidx:
6565 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6567 case ARM::t2STRH_preidx:
6568 MI->setDesc(TII->get(ARM::t2STRH_PRE));
6571 case ARM::STRi_preidx:
6572 case ARM::STRBi_preidx: {
6573 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6574 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6575 // Decode the offset.
6576 unsigned Offset = MI->getOperand(4).getImm();
6577 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6578 Offset = ARM_AM::getAM2Offset(Offset);
6582 MachineMemOperand *MMO = *MI->memoperands_begin();
6583 BuildMI(*BB, MI, dl, TII->get(NewOpc))
6584 .addOperand(MI->getOperand(0)) // Rn_wb
6585 .addOperand(MI->getOperand(1)) // Rt
6586 .addOperand(MI->getOperand(2)) // Rn
6587 .addImm(Offset) // offset (skip GPR==zero_reg)
6588 .addOperand(MI->getOperand(5)) // pred
6589 .addOperand(MI->getOperand(6))
6590 .addMemOperand(MMO);
6591 MI->eraseFromParent();
6594 case ARM::STRr_preidx:
6595 case ARM::STRBr_preidx:
6596 case ARM::STRH_preidx: {
6598 switch (MI->getOpcode()) {
6599 default: llvm_unreachable("unexpected opcode!");
6600 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6601 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6602 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6604 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6605 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6606 MIB.addOperand(MI->getOperand(i));
6607 MI->eraseFromParent();
6610 case ARM::ATOMIC_LOAD_ADD_I8:
6611 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6612 case ARM::ATOMIC_LOAD_ADD_I16:
6613 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6614 case ARM::ATOMIC_LOAD_ADD_I32:
6615 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6617 case ARM::ATOMIC_LOAD_AND_I8:
6618 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6619 case ARM::ATOMIC_LOAD_AND_I16:
6620 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6621 case ARM::ATOMIC_LOAD_AND_I32:
6622 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6624 case ARM::ATOMIC_LOAD_OR_I8:
6625 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6626 case ARM::ATOMIC_LOAD_OR_I16:
6627 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6628 case ARM::ATOMIC_LOAD_OR_I32:
6629 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6631 case ARM::ATOMIC_LOAD_XOR_I8:
6632 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6633 case ARM::ATOMIC_LOAD_XOR_I16:
6634 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6635 case ARM::ATOMIC_LOAD_XOR_I32:
6636 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6638 case ARM::ATOMIC_LOAD_NAND_I8:
6639 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6640 case ARM::ATOMIC_LOAD_NAND_I16:
6641 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6642 case ARM::ATOMIC_LOAD_NAND_I32:
6643 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6645 case ARM::ATOMIC_LOAD_SUB_I8:
6646 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6647 case ARM::ATOMIC_LOAD_SUB_I16:
6648 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6649 case ARM::ATOMIC_LOAD_SUB_I32:
6650 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6652 case ARM::ATOMIC_LOAD_MIN_I8:
6653 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6654 case ARM::ATOMIC_LOAD_MIN_I16:
6655 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6656 case ARM::ATOMIC_LOAD_MIN_I32:
6657 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6659 case ARM::ATOMIC_LOAD_MAX_I8:
6660 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6661 case ARM::ATOMIC_LOAD_MAX_I16:
6662 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6663 case ARM::ATOMIC_LOAD_MAX_I32:
6664 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6666 case ARM::ATOMIC_LOAD_UMIN_I8:
6667 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6668 case ARM::ATOMIC_LOAD_UMIN_I16:
6669 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6670 case ARM::ATOMIC_LOAD_UMIN_I32:
6671 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6673 case ARM::ATOMIC_LOAD_UMAX_I8:
6674 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6675 case ARM::ATOMIC_LOAD_UMAX_I16:
6676 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6677 case ARM::ATOMIC_LOAD_UMAX_I32:
6678 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6680 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
6681 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6682 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6684 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
6685 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6686 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6689 case ARM::ATOMADD6432:
6690 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6691 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6692 /*NeedsCarry*/ true);
6693 case ARM::ATOMSUB6432:
6694 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6695 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6696 /*NeedsCarry*/ true);
6697 case ARM::ATOMOR6432:
6698 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6699 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6700 case ARM::ATOMXOR6432:
6701 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6702 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6703 case ARM::ATOMAND6432:
6704 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6705 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6706 case ARM::ATOMSWAP6432:
6707 return EmitAtomicBinary64(MI, BB, 0, 0, false);
6708 case ARM::ATOMCMPXCHG6432:
6709 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6710 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6711 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6713 case ARM::tMOVCCr_pseudo: {
6714 // To "insert" a SELECT_CC instruction, we actually have to insert the
6715 // diamond control-flow pattern. The incoming instruction knows the
6716 // destination vreg to set, the condition code register to branch on, the
6717 // true/false values to select between, and a branch opcode to use.
6718 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6719 MachineFunction::iterator It = BB;
6725 // cmpTY ccX, r1, r2
6727 // fallthrough --> copy0MBB
6728 MachineBasicBlock *thisMBB = BB;
6729 MachineFunction *F = BB->getParent();
6730 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6731 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6732 F->insert(It, copy0MBB);
6733 F->insert(It, sinkMBB);
6735 // Transfer the remainder of BB and its successor edges to sinkMBB.
6736 sinkMBB->splice(sinkMBB->begin(), BB,
6737 llvm::next(MachineBasicBlock::iterator(MI)),
6739 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6741 BB->addSuccessor(copy0MBB);
6742 BB->addSuccessor(sinkMBB);
6744 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6745 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6748 // %FalseValue = ...
6749 // # fallthrough to sinkMBB
6752 // Update machine-CFG edges
6753 BB->addSuccessor(sinkMBB);
6756 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6759 BuildMI(*BB, BB->begin(), dl,
6760 TII->get(ARM::PHI), MI->getOperand(0).getReg())
6761 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6762 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6764 MI->eraseFromParent(); // The pseudo instruction is gone now.
6769 case ARM::BCCZi64: {
6770 // If there is an unconditional branch to the other successor, remove it.
6771 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6773 // Compare both parts that make up the double comparison separately for
6775 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6777 unsigned LHS1 = MI->getOperand(1).getReg();
6778 unsigned LHS2 = MI->getOperand(2).getReg();
6780 AddDefaultPred(BuildMI(BB, dl,
6781 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6782 .addReg(LHS1).addImm(0));
6783 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6784 .addReg(LHS2).addImm(0)
6785 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6787 unsigned RHS1 = MI->getOperand(3).getReg();
6788 unsigned RHS2 = MI->getOperand(4).getReg();
6789 AddDefaultPred(BuildMI(BB, dl,
6790 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6791 .addReg(LHS1).addReg(RHS1));
6792 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6793 .addReg(LHS2).addReg(RHS2)
6794 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6797 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6798 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6799 if (MI->getOperand(0).getImm() == ARMCC::NE)
6800 std::swap(destMBB, exitMBB);
6802 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6803 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6805 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6807 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6809 MI->eraseFromParent(); // The pseudo instruction is gone now.
6813 case ARM::Int_eh_sjlj_setjmp:
6814 case ARM::Int_eh_sjlj_setjmp_nofp:
6815 case ARM::tInt_eh_sjlj_setjmp:
6816 case ARM::t2Int_eh_sjlj_setjmp:
6817 case ARM::t2Int_eh_sjlj_setjmp_nofp:
6818 EmitSjLjDispatchBlock(MI, BB);
6823 // To insert an ABS instruction, we have to insert the
6824 // diamond control-flow pattern. The incoming instruction knows the
6825 // source vreg to test against 0, the destination vreg to set,
6826 // the condition code register to branch on, the
6827 // true/false values to select between, and a branch opcode to use.
6832 // BCC (branch to SinkBB if V0 >= 0)
6833 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
6834 // SinkBB: V1 = PHI(V2, V3)
6835 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6836 MachineFunction::iterator BBI = BB;
6838 MachineFunction *Fn = BB->getParent();
6839 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6840 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6841 Fn->insert(BBI, RSBBB);
6842 Fn->insert(BBI, SinkBB);
6844 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6845 unsigned int ABSDstReg = MI->getOperand(0).getReg();
6846 bool isThumb2 = Subtarget->isThumb2();
6847 MachineRegisterInfo &MRI = Fn->getRegInfo();
6848 // In Thumb mode S must not be specified if source register is the SP or
6849 // PC and if destination register is the SP, so restrict register class
6850 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6851 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6852 (const TargetRegisterClass*)&ARM::GPRRegClass);
6854 // Transfer the remainder of BB and its successor edges to sinkMBB.
6855 SinkBB->splice(SinkBB->begin(), BB,
6856 llvm::next(MachineBasicBlock::iterator(MI)),
6858 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6860 BB->addSuccessor(RSBBB);
6861 BB->addSuccessor(SinkBB);
6863 // fall through to SinkMBB
6864 RSBBB->addSuccessor(SinkBB);
6866 // insert a cmp at the end of BB
6867 AddDefaultPred(BuildMI(BB, dl,
6868 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6869 .addReg(ABSSrcReg).addImm(0));
6871 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6873 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6874 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6876 // insert rsbri in RSBBB
6877 // Note: BCC and rsbri will be converted into predicated rsbmi
6878 // by if-conversion pass
6879 BuildMI(*RSBBB, RSBBB->begin(), dl,
6880 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6881 .addReg(ABSSrcReg, RegState::Kill)
6882 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6884 // insert PHI in SinkBB,
6885 // reuse ABSDstReg to not change uses of ABS instruction
6886 BuildMI(*SinkBB, SinkBB->begin(), dl,
6887 TII->get(ARM::PHI), ABSDstReg)
6888 .addReg(NewRsbDstReg).addMBB(RSBBB)
6889 .addReg(ABSSrcReg).addMBB(BB);
6891 // remove ABS instruction
6892 MI->eraseFromParent();
6894 // return last added BB
6897 case ARM::COPY_STRUCT_BYVAL_I32:
6899 return EmitStructByval(MI, BB);
6903 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6904 SDNode *Node) const {
6905 if (!MI->hasPostISelHook()) {
6906 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6907 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6911 const MCInstrDesc *MCID = &MI->getDesc();
6912 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6913 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6914 // operand is still set to noreg. If needed, set the optional operand's
6915 // register to CPSR, and remove the redundant implicit def.
6917 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6919 // Rename pseudo opcodes.
6920 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6922 const ARMBaseInstrInfo *TII =
6923 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6924 MCID = &TII->get(NewOpc);
6926 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6927 "converted opcode should be the same except for cc_out");
6931 // Add the optional cc_out operand
6932 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6934 unsigned ccOutIdx = MCID->getNumOperands() - 1;
6936 // Any ARM instruction that sets the 's' bit should specify an optional
6937 // "cc_out" operand in the last operand position.
6938 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6939 assert(!NewOpc && "Optional cc_out operand required");
6942 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6943 // since we already have an optional CPSR def.
6944 bool definesCPSR = false;
6945 bool deadCPSR = false;
6946 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6948 const MachineOperand &MO = MI->getOperand(i);
6949 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6953 MI->RemoveOperand(i);
6958 assert(!NewOpc && "Optional cc_out operand required");
6961 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6963 assert(!MI->getOperand(ccOutIdx).getReg() &&
6964 "expect uninitialized optional cc_out operand");
6968 // If this instruction was defined with an optional CPSR def and its dag node
6969 // had a live implicit CPSR def, then activate the optional CPSR def.
6970 MachineOperand &MO = MI->getOperand(ccOutIdx);
6971 MO.setReg(ARM::CPSR);
6975 //===----------------------------------------------------------------------===//
6976 // ARM Optimization Hooks
6977 //===----------------------------------------------------------------------===//
6979 // Helper function that checks if N is a null or all ones constant.
6980 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
6981 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
6984 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
6987 // Return true if N is conditionally 0 or all ones.
6988 // Detects these expressions where cc is an i1 value:
6990 // (select cc 0, y) [AllOnes=0]
6991 // (select cc y, 0) [AllOnes=0]
6992 // (zext cc) [AllOnes=0]
6993 // (sext cc) [AllOnes=0/1]
6994 // (select cc -1, y) [AllOnes=1]
6995 // (select cc y, -1) [AllOnes=1]
6997 // Invert is set when N is the null/all ones constant when CC is false.
6998 // OtherOp is set to the alternative value of N.
6999 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7000 SDValue &CC, bool &Invert,
7002 SelectionDAG &DAG) {
7003 switch (N->getOpcode()) {
7004 default: return false;
7006 CC = N->getOperand(0);
7007 SDValue N1 = N->getOperand(1);
7008 SDValue N2 = N->getOperand(2);
7009 if (isZeroOrAllOnes(N1, AllOnes)) {
7014 if (isZeroOrAllOnes(N2, AllOnes)) {
7021 case ISD::ZERO_EXTEND:
7022 // (zext cc) can never be the all ones value.
7026 case ISD::SIGN_EXTEND: {
7027 EVT VT = N->getValueType(0);
7028 CC = N->getOperand(0);
7029 if (CC.getValueType() != MVT::i1)
7033 // When looking for an AllOnes constant, N is an sext, and the 'other'
7035 OtherOp = DAG.getConstant(0, VT);
7036 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7037 // When looking for a 0 constant, N can be zext or sext.
7038 OtherOp = DAG.getConstant(1, VT);
7040 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7046 // Combine a constant select operand into its use:
7048 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7049 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7050 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7051 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7052 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7054 // The transform is rejected if the select doesn't have a constant operand that
7055 // is null, or all ones when AllOnes is set.
7057 // Also recognize sext/zext from i1:
7059 // (add (zext cc), x) -> (select cc (add x, 1), x)
7060 // (add (sext cc), x) -> (select cc (add x, -1), x)
7062 // These transformations eventually create predicated instructions.
7064 // @param N The node to transform.
7065 // @param Slct The N operand that is a select.
7066 // @param OtherOp The other N operand (x above).
7067 // @param DCI Context.
7068 // @param AllOnes Require the select constant to be all ones instead of null.
7069 // @returns The new node, or SDValue() on failure.
7071 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7072 TargetLowering::DAGCombinerInfo &DCI,
7073 bool AllOnes = false) {
7074 SelectionDAG &DAG = DCI.DAG;
7075 EVT VT = N->getValueType(0);
7076 SDValue NonConstantVal;
7079 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7080 NonConstantVal, DAG))
7083 // Slct is now know to be the desired identity constant when CC is true.
7084 SDValue TrueVal = OtherOp;
7085 SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7086 OtherOp, NonConstantVal);
7087 // Unless SwapSelectOps says CC should be false.
7089 std::swap(TrueVal, FalseVal);
7091 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7092 CCOp, TrueVal, FalseVal);
7095 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7097 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7098 TargetLowering::DAGCombinerInfo &DCI) {
7099 SDValue N0 = N->getOperand(0);
7100 SDValue N1 = N->getOperand(1);
7101 if (N0.getNode()->hasOneUse()) {
7102 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7103 if (Result.getNode())
7106 if (N1.getNode()->hasOneUse()) {
7107 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7108 if (Result.getNode())
7114 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7115 // (only after legalization).
7116 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7117 TargetLowering::DAGCombinerInfo &DCI,
7118 const ARMSubtarget *Subtarget) {
7120 // Only perform optimization if after legalize, and if NEON is available. We
7121 // also expected both operands to be BUILD_VECTORs.
7122 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7123 || N0.getOpcode() != ISD::BUILD_VECTOR
7124 || N1.getOpcode() != ISD::BUILD_VECTOR)
7127 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7128 EVT VT = N->getValueType(0);
7129 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7132 // Check that the vector operands are of the right form.
7133 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7134 // operands, where N is the size of the formed vector.
7135 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7136 // index such that we have a pair wise add pattern.
7138 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7139 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7141 SDValue Vec = N0->getOperand(0)->getOperand(0);
7142 SDNode *V = Vec.getNode();
7143 unsigned nextIndex = 0;
7145 // For each operands to the ADD which are BUILD_VECTORs,
7146 // check to see if each of their operands are an EXTRACT_VECTOR with
7147 // the same vector and appropriate index.
7148 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7149 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7150 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7152 SDValue ExtVec0 = N0->getOperand(i);
7153 SDValue ExtVec1 = N1->getOperand(i);
7155 // First operand is the vector, verify its the same.
7156 if (V != ExtVec0->getOperand(0).getNode() ||
7157 V != ExtVec1->getOperand(0).getNode())
7160 // Second is the constant, verify its correct.
7161 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7162 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7164 // For the constant, we want to see all the even or all the odd.
7165 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7166 || C1->getZExtValue() != nextIndex+1)
7175 // Create VPADDL node.
7176 SelectionDAG &DAG = DCI.DAG;
7177 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7179 // Build operand list.
7180 SmallVector<SDValue, 8> Ops;
7181 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7182 TLI.getPointerTy()));
7184 // Input is the vector.
7187 // Get widened type and narrowed type.
7189 unsigned numElem = VT.getVectorNumElements();
7190 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7191 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7192 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7193 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7195 llvm_unreachable("Invalid vector element type for padd optimization.");
7198 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7199 widenType, &Ops[0], Ops.size());
7200 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7203 static SDValue findMUL_LOHI(SDValue V) {
7204 if (V->getOpcode() == ISD::UMUL_LOHI ||
7205 V->getOpcode() == ISD::SMUL_LOHI)
7210 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7211 TargetLowering::DAGCombinerInfo &DCI,
7212 const ARMSubtarget *Subtarget) {
7214 if (Subtarget->isThumb1Only()) return SDValue();
7216 // Only perform the checks after legalize when the pattern is available.
7217 if (DCI.isBeforeLegalize()) return SDValue();
7219 // Look for multiply add opportunities.
7220 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7221 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7222 // a glue link from the first add to the second add.
7223 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7224 // a S/UMLAL instruction.
7227 // \ / \ [no multiline comment]
7233 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7234 SDValue AddcOp0 = AddcNode->getOperand(0);
7235 SDValue AddcOp1 = AddcNode->getOperand(1);
7237 // Check if the two operands are from the same mul_lohi node.
7238 if (AddcOp0.getNode() == AddcOp1.getNode())
7241 assert(AddcNode->getNumValues() == 2 &&
7242 AddcNode->getValueType(0) == MVT::i32 &&
7243 AddcNode->getValueType(1) == MVT::Glue &&
7244 "Expect ADDC with two result values: i32, glue");
7246 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7247 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7248 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7249 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7250 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7253 // Look for the glued ADDE.
7254 SDNode* AddeNode = AddcNode->getGluedUser();
7255 if (AddeNode == NULL)
7258 // Make sure it is really an ADDE.
7259 if (AddeNode->getOpcode() != ISD::ADDE)
7262 assert(AddeNode->getNumOperands() == 3 &&
7263 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7264 "ADDE node has the wrong inputs");
7266 // Check for the triangle shape.
7267 SDValue AddeOp0 = AddeNode->getOperand(0);
7268 SDValue AddeOp1 = AddeNode->getOperand(1);
7270 // Make sure that the ADDE operands are not coming from the same node.
7271 if (AddeOp0.getNode() == AddeOp1.getNode())
7274 // Find the MUL_LOHI node walking up ADDE's operands.
7275 bool IsLeftOperandMUL = false;
7276 SDValue MULOp = findMUL_LOHI(AddeOp0);
7277 if (MULOp == SDValue())
7278 MULOp = findMUL_LOHI(AddeOp1);
7280 IsLeftOperandMUL = true;
7281 if (MULOp == SDValue())
7284 // Figure out the right opcode.
7285 unsigned Opc = MULOp->getOpcode();
7286 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7288 // Figure out the high and low input values to the MLAL node.
7289 SDValue* HiMul = &MULOp;
7290 SDValue* HiAdd = NULL;
7291 SDValue* LoMul = NULL;
7292 SDValue* LowAdd = NULL;
7294 if (IsLeftOperandMUL)
7300 if (AddcOp0->getOpcode() == Opc) {
7304 if (AddcOp1->getOpcode() == Opc) {
7312 if (LoMul->getNode() != HiMul->getNode())
7315 // Create the merged node.
7316 SelectionDAG &DAG = DCI.DAG;
7318 // Build operand list.
7319 SmallVector<SDValue, 8> Ops;
7320 Ops.push_back(LoMul->getOperand(0));
7321 Ops.push_back(LoMul->getOperand(1));
7322 Ops.push_back(*LowAdd);
7323 Ops.push_back(*HiAdd);
7325 SDValue MLALNode = DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7326 DAG.getVTList(MVT::i32, MVT::i32),
7327 &Ops[0], Ops.size());
7329 // Replace the ADDs' nodes uses by the MLA node's values.
7330 SDValue HiMLALResult(MLALNode.getNode(), 1);
7331 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7333 SDValue LoMLALResult(MLALNode.getNode(), 0);
7334 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7336 // Return original node to notify the driver to stop replacing.
7337 SDValue resNode(AddcNode, 0);
7341 /// PerformADDCCombine - Target-specific dag combine transform from
7342 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7343 static SDValue PerformADDCCombine(SDNode *N,
7344 TargetLowering::DAGCombinerInfo &DCI,
7345 const ARMSubtarget *Subtarget) {
7347 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7351 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7352 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7353 /// called with the default operands, and if that fails, with commuted
7355 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7356 TargetLowering::DAGCombinerInfo &DCI,
7357 const ARMSubtarget *Subtarget){
7359 // Attempt to create vpaddl for this add.
7360 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7361 if (Result.getNode())
7364 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7365 if (N0.getNode()->hasOneUse()) {
7366 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7367 if (Result.getNode()) return Result;
7372 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7374 static SDValue PerformADDCombine(SDNode *N,
7375 TargetLowering::DAGCombinerInfo &DCI,
7376 const ARMSubtarget *Subtarget) {
7377 SDValue N0 = N->getOperand(0);
7378 SDValue N1 = N->getOperand(1);
7380 // First try with the default operand order.
7381 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7382 if (Result.getNode())
7385 // If that didn't work, try again with the operands commuted.
7386 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7389 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7391 static SDValue PerformSUBCombine(SDNode *N,
7392 TargetLowering::DAGCombinerInfo &DCI) {
7393 SDValue N0 = N->getOperand(0);
7394 SDValue N1 = N->getOperand(1);
7396 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7397 if (N1.getNode()->hasOneUse()) {
7398 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7399 if (Result.getNode()) return Result;
7405 /// PerformVMULCombine
7406 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7407 /// special multiplier accumulator forwarding.
7413 static SDValue PerformVMULCombine(SDNode *N,
7414 TargetLowering::DAGCombinerInfo &DCI,
7415 const ARMSubtarget *Subtarget) {
7416 if (!Subtarget->hasVMLxForwarding())
7419 SelectionDAG &DAG = DCI.DAG;
7420 SDValue N0 = N->getOperand(0);
7421 SDValue N1 = N->getOperand(1);
7422 unsigned Opcode = N0.getOpcode();
7423 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7424 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7425 Opcode = N1.getOpcode();
7426 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7427 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7432 EVT VT = N->getValueType(0);
7433 DebugLoc DL = N->getDebugLoc();
7434 SDValue N00 = N0->getOperand(0);
7435 SDValue N01 = N0->getOperand(1);
7436 return DAG.getNode(Opcode, DL, VT,
7437 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7438 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7441 static SDValue PerformMULCombine(SDNode *N,
7442 TargetLowering::DAGCombinerInfo &DCI,
7443 const ARMSubtarget *Subtarget) {
7444 SelectionDAG &DAG = DCI.DAG;
7446 if (Subtarget->isThumb1Only())
7449 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7452 EVT VT = N->getValueType(0);
7453 if (VT.is64BitVector() || VT.is128BitVector())
7454 return PerformVMULCombine(N, DCI, Subtarget);
7458 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7462 int64_t MulAmt = C->getSExtValue();
7463 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7465 ShiftAmt = ShiftAmt & (32 - 1);
7466 SDValue V = N->getOperand(0);
7467 DebugLoc DL = N->getDebugLoc();
7470 MulAmt >>= ShiftAmt;
7473 if (isPowerOf2_32(MulAmt - 1)) {
7474 // (mul x, 2^N + 1) => (add (shl x, N), x)
7475 Res = DAG.getNode(ISD::ADD, DL, VT,
7477 DAG.getNode(ISD::SHL, DL, VT,
7479 DAG.getConstant(Log2_32(MulAmt - 1),
7481 } else if (isPowerOf2_32(MulAmt + 1)) {
7482 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7483 Res = DAG.getNode(ISD::SUB, DL, VT,
7484 DAG.getNode(ISD::SHL, DL, VT,
7486 DAG.getConstant(Log2_32(MulAmt + 1),
7492 uint64_t MulAmtAbs = -MulAmt;
7493 if (isPowerOf2_32(MulAmtAbs + 1)) {
7494 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7495 Res = DAG.getNode(ISD::SUB, DL, VT,
7497 DAG.getNode(ISD::SHL, DL, VT,
7499 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7501 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7502 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7503 Res = DAG.getNode(ISD::ADD, DL, VT,
7505 DAG.getNode(ISD::SHL, DL, VT,
7507 DAG.getConstant(Log2_32(MulAmtAbs-1),
7509 Res = DAG.getNode(ISD::SUB, DL, VT,
7510 DAG.getConstant(0, MVT::i32),Res);
7517 Res = DAG.getNode(ISD::SHL, DL, VT,
7518 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7520 // Do not add new nodes to DAG combiner worklist.
7521 DCI.CombineTo(N, Res, false);
7525 static SDValue PerformANDCombine(SDNode *N,
7526 TargetLowering::DAGCombinerInfo &DCI,
7527 const ARMSubtarget *Subtarget) {
7529 // Attempt to use immediate-form VBIC
7530 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7531 DebugLoc dl = N->getDebugLoc();
7532 EVT VT = N->getValueType(0);
7533 SelectionDAG &DAG = DCI.DAG;
7535 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7538 APInt SplatBits, SplatUndef;
7539 unsigned SplatBitSize;
7542 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7543 if (SplatBitSize <= 64) {
7545 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7546 SplatUndef.getZExtValue(), SplatBitSize,
7547 DAG, VbicVT, VT.is128BitVector(),
7549 if (Val.getNode()) {
7551 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7552 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7553 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7558 if (!Subtarget->isThumb1Only()) {
7559 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7560 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7561 if (Result.getNode())
7568 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7569 static SDValue PerformORCombine(SDNode *N,
7570 TargetLowering::DAGCombinerInfo &DCI,
7571 const ARMSubtarget *Subtarget) {
7572 // Attempt to use immediate-form VORR
7573 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7574 DebugLoc dl = N->getDebugLoc();
7575 EVT VT = N->getValueType(0);
7576 SelectionDAG &DAG = DCI.DAG;
7578 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7581 APInt SplatBits, SplatUndef;
7582 unsigned SplatBitSize;
7584 if (BVN && Subtarget->hasNEON() &&
7585 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7586 if (SplatBitSize <= 64) {
7588 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7589 SplatUndef.getZExtValue(), SplatBitSize,
7590 DAG, VorrVT, VT.is128BitVector(),
7592 if (Val.getNode()) {
7594 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7595 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7596 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7601 if (!Subtarget->isThumb1Only()) {
7602 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7603 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7604 if (Result.getNode())
7608 // The code below optimizes (or (and X, Y), Z).
7609 // The AND operand needs to have a single user to make these optimizations
7611 SDValue N0 = N->getOperand(0);
7612 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7614 SDValue N1 = N->getOperand(1);
7616 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7617 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7618 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7620 unsigned SplatBitSize;
7623 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7625 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7626 HasAnyUndefs) && !HasAnyUndefs) {
7627 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7629 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7630 HasAnyUndefs) && !HasAnyUndefs &&
7631 SplatBits0 == ~SplatBits1) {
7632 // Canonicalize the vector type to make instruction selection simpler.
7633 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7634 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7635 N0->getOperand(1), N0->getOperand(0),
7637 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7642 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7645 // BFI is only available on V6T2+
7646 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7649 DebugLoc DL = N->getDebugLoc();
7650 // 1) or (and A, mask), val => ARMbfi A, val, mask
7651 // iff (val & mask) == val
7653 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7654 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7655 // && mask == ~mask2
7656 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7657 // && ~mask == mask2
7658 // (i.e., copy a bitfield value into another bitfield of the same width)
7663 SDValue N00 = N0.getOperand(0);
7665 // The value and the mask need to be constants so we can verify this is
7666 // actually a bitfield set. If the mask is 0xffff, we can do better
7667 // via a movt instruction, so don't use BFI in that case.
7668 SDValue MaskOp = N0.getOperand(1);
7669 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7672 unsigned Mask = MaskC->getZExtValue();
7676 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7677 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7679 unsigned Val = N1C->getZExtValue();
7680 if ((Val & ~Mask) != Val)
7683 if (ARM::isBitFieldInvertedMask(Mask)) {
7684 Val >>= CountTrailingZeros_32(~Mask);
7686 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7687 DAG.getConstant(Val, MVT::i32),
7688 DAG.getConstant(Mask, MVT::i32));
7690 // Do not add new nodes to DAG combiner worklist.
7691 DCI.CombineTo(N, Res, false);
7694 } else if (N1.getOpcode() == ISD::AND) {
7695 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7696 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7699 unsigned Mask2 = N11C->getZExtValue();
7701 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7703 if (ARM::isBitFieldInvertedMask(Mask) &&
7705 // The pack halfword instruction works better for masks that fit it,
7706 // so use that when it's available.
7707 if (Subtarget->hasT2ExtractPack() &&
7708 (Mask == 0xffff || Mask == 0xffff0000))
7711 unsigned amt = CountTrailingZeros_32(Mask2);
7712 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7713 DAG.getConstant(amt, MVT::i32));
7714 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7715 DAG.getConstant(Mask, MVT::i32));
7716 // Do not add new nodes to DAG combiner worklist.
7717 DCI.CombineTo(N, Res, false);
7719 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7721 // The pack halfword instruction works better for masks that fit it,
7722 // so use that when it's available.
7723 if (Subtarget->hasT2ExtractPack() &&
7724 (Mask2 == 0xffff || Mask2 == 0xffff0000))
7727 unsigned lsb = CountTrailingZeros_32(Mask);
7728 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7729 DAG.getConstant(lsb, MVT::i32));
7730 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7731 DAG.getConstant(Mask2, MVT::i32));
7732 // Do not add new nodes to DAG combiner worklist.
7733 DCI.CombineTo(N, Res, false);
7738 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7739 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7740 ARM::isBitFieldInvertedMask(~Mask)) {
7741 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7742 // where lsb(mask) == #shamt and masked bits of B are known zero.
7743 SDValue ShAmt = N00.getOperand(1);
7744 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7745 unsigned LSB = CountTrailingZeros_32(Mask);
7749 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7750 DAG.getConstant(~Mask, MVT::i32));
7752 // Do not add new nodes to DAG combiner worklist.
7753 DCI.CombineTo(N, Res, false);
7759 static SDValue PerformXORCombine(SDNode *N,
7760 TargetLowering::DAGCombinerInfo &DCI,
7761 const ARMSubtarget *Subtarget) {
7762 EVT VT = N->getValueType(0);
7763 SelectionDAG &DAG = DCI.DAG;
7765 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7768 if (!Subtarget->isThumb1Only()) {
7769 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7770 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7771 if (Result.getNode())
7778 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7779 /// the bits being cleared by the AND are not demanded by the BFI.
7780 static SDValue PerformBFICombine(SDNode *N,
7781 TargetLowering::DAGCombinerInfo &DCI) {
7782 SDValue N1 = N->getOperand(1);
7783 if (N1.getOpcode() == ISD::AND) {
7784 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7787 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7788 unsigned LSB = CountTrailingZeros_32(~InvMask);
7789 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7790 unsigned Mask = (1 << Width)-1;
7791 unsigned Mask2 = N11C->getZExtValue();
7792 if ((Mask & (~Mask2)) == 0)
7793 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7794 N->getOperand(0), N1.getOperand(0),
7800 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7801 /// ARMISD::VMOVRRD.
7802 static SDValue PerformVMOVRRDCombine(SDNode *N,
7803 TargetLowering::DAGCombinerInfo &DCI) {
7804 // vmovrrd(vmovdrr x, y) -> x,y
7805 SDValue InDouble = N->getOperand(0);
7806 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7807 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7809 // vmovrrd(load f64) -> (load i32), (load i32)
7810 SDNode *InNode = InDouble.getNode();
7811 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7812 InNode->getValueType(0) == MVT::f64 &&
7813 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7814 !cast<LoadSDNode>(InNode)->isVolatile()) {
7815 // TODO: Should this be done for non-FrameIndex operands?
7816 LoadSDNode *LD = cast<LoadSDNode>(InNode);
7818 SelectionDAG &DAG = DCI.DAG;
7819 DebugLoc DL = LD->getDebugLoc();
7820 SDValue BasePtr = LD->getBasePtr();
7821 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7822 LD->getPointerInfo(), LD->isVolatile(),
7823 LD->isNonTemporal(), LD->isInvariant(),
7824 LD->getAlignment());
7826 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7827 DAG.getConstant(4, MVT::i32));
7828 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7829 LD->getPointerInfo(), LD->isVolatile(),
7830 LD->isNonTemporal(), LD->isInvariant(),
7831 std::min(4U, LD->getAlignment() / 2));
7833 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7834 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7835 DCI.RemoveFromWorklist(LD);
7843 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7844 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
7845 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7846 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7847 SDValue Op0 = N->getOperand(0);
7848 SDValue Op1 = N->getOperand(1);
7849 if (Op0.getOpcode() == ISD::BITCAST)
7850 Op0 = Op0.getOperand(0);
7851 if (Op1.getOpcode() == ISD::BITCAST)
7852 Op1 = Op1.getOperand(0);
7853 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7854 Op0.getNode() == Op1.getNode() &&
7855 Op0.getResNo() == 0 && Op1.getResNo() == 1)
7856 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7857 N->getValueType(0), Op0.getOperand(0));
7861 /// PerformSTORECombine - Target-specific dag combine xforms for
7863 static SDValue PerformSTORECombine(SDNode *N,
7864 TargetLowering::DAGCombinerInfo &DCI) {
7865 StoreSDNode *St = cast<StoreSDNode>(N);
7866 if (St->isVolatile())
7869 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
7870 // pack all of the elements in one place. Next, store to memory in fewer
7872 SDValue StVal = St->getValue();
7873 EVT VT = StVal.getValueType();
7874 if (St->isTruncatingStore() && VT.isVector()) {
7875 SelectionDAG &DAG = DCI.DAG;
7876 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7877 EVT StVT = St->getMemoryVT();
7878 unsigned NumElems = VT.getVectorNumElements();
7879 assert(StVT != VT && "Cannot truncate to the same type");
7880 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7881 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7883 // From, To sizes and ElemCount must be pow of two
7884 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7886 // We are going to use the original vector elt for storing.
7887 // Accumulated smaller vector elements must be a multiple of the store size.
7888 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7890 unsigned SizeRatio = FromEltSz / ToEltSz;
7891 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7893 // Create a type on which we perform the shuffle.
7894 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7895 NumElems*SizeRatio);
7896 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7898 DebugLoc DL = St->getDebugLoc();
7899 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7900 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7901 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7903 // Can't shuffle using an illegal type.
7904 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7906 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7907 DAG.getUNDEF(WideVec.getValueType()),
7909 // At this point all of the data is stored at the bottom of the
7910 // register. We now need to save it to mem.
7912 // Find the largest store unit
7913 MVT StoreType = MVT::i8;
7914 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7915 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7916 MVT Tp = (MVT::SimpleValueType)tp;
7917 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7920 // Didn't find a legal store type.
7921 if (!TLI.isTypeLegal(StoreType))
7924 // Bitcast the original vector into a vector of store-size units
7925 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7926 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7927 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7928 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7929 SmallVector<SDValue, 8> Chains;
7930 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7931 TLI.getPointerTy());
7932 SDValue BasePtr = St->getBasePtr();
7934 // Perform one or more big stores into memory.
7935 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7936 for (unsigned I = 0; I < E; I++) {
7937 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7938 StoreType, ShuffWide,
7939 DAG.getIntPtrConstant(I));
7940 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7941 St->getPointerInfo(), St->isVolatile(),
7942 St->isNonTemporal(), St->getAlignment());
7943 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7945 Chains.push_back(Ch);
7947 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7951 if (!ISD::isNormalStore(St))
7954 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7955 // ARM stores of arguments in the same cache line.
7956 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7957 StVal.getNode()->hasOneUse()) {
7958 SelectionDAG &DAG = DCI.DAG;
7959 DebugLoc DL = St->getDebugLoc();
7960 SDValue BasePtr = St->getBasePtr();
7961 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7962 StVal.getNode()->getOperand(0), BasePtr,
7963 St->getPointerInfo(), St->isVolatile(),
7964 St->isNonTemporal(), St->getAlignment());
7966 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7967 DAG.getConstant(4, MVT::i32));
7968 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7969 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7970 St->isNonTemporal(),
7971 std::min(4U, St->getAlignment() / 2));
7974 if (StVal.getValueType() != MVT::i64 ||
7975 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7978 // Bitcast an i64 store extracted from a vector to f64.
7979 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7980 SelectionDAG &DAG = DCI.DAG;
7981 DebugLoc dl = StVal.getDebugLoc();
7982 SDValue IntVec = StVal.getOperand(0);
7983 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7984 IntVec.getValueType().getVectorNumElements());
7985 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7986 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7987 Vec, StVal.getOperand(1));
7988 dl = N->getDebugLoc();
7989 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7990 // Make the DAGCombiner fold the bitcasts.
7991 DCI.AddToWorklist(Vec.getNode());
7992 DCI.AddToWorklist(ExtElt.getNode());
7993 DCI.AddToWorklist(V.getNode());
7994 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7995 St->getPointerInfo(), St->isVolatile(),
7996 St->isNonTemporal(), St->getAlignment(),
8000 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8001 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8002 /// i64 vector to have f64 elements, since the value can then be loaded
8003 /// directly into a VFP register.
8004 static bool hasNormalLoadOperand(SDNode *N) {
8005 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8006 for (unsigned i = 0; i < NumElts; ++i) {
8007 SDNode *Elt = N->getOperand(i).getNode();
8008 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8014 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8015 /// ISD::BUILD_VECTOR.
8016 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8017 TargetLowering::DAGCombinerInfo &DCI){
8018 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8019 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8020 // into a pair of GPRs, which is fine when the value is used as a scalar,
8021 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8022 SelectionDAG &DAG = DCI.DAG;
8023 if (N->getNumOperands() == 2) {
8024 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8029 // Load i64 elements as f64 values so that type legalization does not split
8030 // them up into i32 values.
8031 EVT VT = N->getValueType(0);
8032 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8034 DebugLoc dl = N->getDebugLoc();
8035 SmallVector<SDValue, 8> Ops;
8036 unsigned NumElts = VT.getVectorNumElements();
8037 for (unsigned i = 0; i < NumElts; ++i) {
8038 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8040 // Make the DAGCombiner fold the bitcast.
8041 DCI.AddToWorklist(V.getNode());
8043 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8044 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8045 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8048 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8049 /// ISD::INSERT_VECTOR_ELT.
8050 static SDValue PerformInsertEltCombine(SDNode *N,
8051 TargetLowering::DAGCombinerInfo &DCI) {
8052 // Bitcast an i64 load inserted into a vector to f64.
8053 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8054 EVT VT = N->getValueType(0);
8055 SDNode *Elt = N->getOperand(1).getNode();
8056 if (VT.getVectorElementType() != MVT::i64 ||
8057 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8060 SelectionDAG &DAG = DCI.DAG;
8061 DebugLoc dl = N->getDebugLoc();
8062 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8063 VT.getVectorNumElements());
8064 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8065 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8066 // Make the DAGCombiner fold the bitcasts.
8067 DCI.AddToWorklist(Vec.getNode());
8068 DCI.AddToWorklist(V.getNode());
8069 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8070 Vec, V, N->getOperand(2));
8071 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8074 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8075 /// ISD::VECTOR_SHUFFLE.
8076 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8077 // The LLVM shufflevector instruction does not require the shuffle mask
8078 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8079 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8080 // operands do not match the mask length, they are extended by concatenating
8081 // them with undef vectors. That is probably the right thing for other
8082 // targets, but for NEON it is better to concatenate two double-register
8083 // size vector operands into a single quad-register size vector. Do that
8084 // transformation here:
8085 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8086 // shuffle(concat(v1, v2), undef)
8087 SDValue Op0 = N->getOperand(0);
8088 SDValue Op1 = N->getOperand(1);
8089 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8090 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8091 Op0.getNumOperands() != 2 ||
8092 Op1.getNumOperands() != 2)
8094 SDValue Concat0Op1 = Op0.getOperand(1);
8095 SDValue Concat1Op1 = Op1.getOperand(1);
8096 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8097 Concat1Op1.getOpcode() != ISD::UNDEF)
8099 // Skip the transformation if any of the types are illegal.
8100 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8101 EVT VT = N->getValueType(0);
8102 if (!TLI.isTypeLegal(VT) ||
8103 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8104 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8107 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8108 Op0.getOperand(0), Op1.getOperand(0));
8109 // Translate the shuffle mask.
8110 SmallVector<int, 16> NewMask;
8111 unsigned NumElts = VT.getVectorNumElements();
8112 unsigned HalfElts = NumElts/2;
8113 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8114 for (unsigned n = 0; n < NumElts; ++n) {
8115 int MaskElt = SVN->getMaskElt(n);
8117 if (MaskElt < (int)HalfElts)
8119 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8120 NewElt = HalfElts + MaskElt - NumElts;
8121 NewMask.push_back(NewElt);
8123 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8124 DAG.getUNDEF(VT), NewMask.data());
8127 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8128 /// NEON load/store intrinsics to merge base address updates.
8129 static SDValue CombineBaseUpdate(SDNode *N,
8130 TargetLowering::DAGCombinerInfo &DCI) {
8131 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8134 SelectionDAG &DAG = DCI.DAG;
8135 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8136 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8137 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8138 SDValue Addr = N->getOperand(AddrOpIdx);
8140 // Search for a use of the address operand that is an increment.
8141 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8142 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8144 if (User->getOpcode() != ISD::ADD ||
8145 UI.getUse().getResNo() != Addr.getResNo())
8148 // Check that the add is independent of the load/store. Otherwise, folding
8149 // it would create a cycle.
8150 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8153 // Find the new opcode for the updating load/store.
8155 bool isLaneOp = false;
8156 unsigned NewOpc = 0;
8157 unsigned NumVecs = 0;
8159 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8161 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8162 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8164 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8166 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8168 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8170 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8171 NumVecs = 2; isLaneOp = true; break;
8172 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8173 NumVecs = 3; isLaneOp = true; break;
8174 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8175 NumVecs = 4; isLaneOp = true; break;
8176 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8177 NumVecs = 1; isLoad = false; break;
8178 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8179 NumVecs = 2; isLoad = false; break;
8180 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8181 NumVecs = 3; isLoad = false; break;
8182 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8183 NumVecs = 4; isLoad = false; break;
8184 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8185 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8186 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8187 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8188 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8189 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8193 switch (N->getOpcode()) {
8194 default: llvm_unreachable("unexpected opcode for Neon base update");
8195 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8196 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8197 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8201 // Find the size of memory referenced by the load/store.
8204 VecTy = N->getValueType(0);
8206 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8207 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8209 NumBytes /= VecTy.getVectorNumElements();
8211 // If the increment is a constant, it must match the memory ref size.
8212 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8213 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8214 uint64_t IncVal = CInc->getZExtValue();
8215 if (IncVal != NumBytes)
8217 } else if (NumBytes >= 3 * 16) {
8218 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8219 // separate instructions that make it harder to use a non-constant update.
8223 // Create the new updating load/store node.
8225 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8227 for (n = 0; n < NumResultVecs; ++n)
8229 Tys[n++] = MVT::i32;
8230 Tys[n] = MVT::Other;
8231 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8232 SmallVector<SDValue, 8> Ops;
8233 Ops.push_back(N->getOperand(0)); // incoming chain
8234 Ops.push_back(N->getOperand(AddrOpIdx));
8236 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8237 Ops.push_back(N->getOperand(i));
8239 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8240 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8241 Ops.data(), Ops.size(),
8242 MemInt->getMemoryVT(),
8243 MemInt->getMemOperand());
8246 std::vector<SDValue> NewResults;
8247 for (unsigned i = 0; i < NumResultVecs; ++i) {
8248 NewResults.push_back(SDValue(UpdN.getNode(), i));
8250 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8251 DCI.CombineTo(N, NewResults);
8252 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8259 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8260 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8261 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8263 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8264 SelectionDAG &DAG = DCI.DAG;
8265 EVT VT = N->getValueType(0);
8266 // vldN-dup instructions only support 64-bit vectors for N > 1.
8267 if (!VT.is64BitVector())
8270 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8271 SDNode *VLD = N->getOperand(0).getNode();
8272 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8274 unsigned NumVecs = 0;
8275 unsigned NewOpc = 0;
8276 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8277 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8279 NewOpc = ARMISD::VLD2DUP;
8280 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8282 NewOpc = ARMISD::VLD3DUP;
8283 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8285 NewOpc = ARMISD::VLD4DUP;
8290 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8291 // numbers match the load.
8292 unsigned VLDLaneNo =
8293 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8294 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8296 // Ignore uses of the chain result.
8297 if (UI.getUse().getResNo() == NumVecs)
8300 if (User->getOpcode() != ARMISD::VDUPLANE ||
8301 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8305 // Create the vldN-dup node.
8308 for (n = 0; n < NumVecs; ++n)
8310 Tys[n] = MVT::Other;
8311 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8312 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8313 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8314 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8315 Ops, 2, VLDMemInt->getMemoryVT(),
8316 VLDMemInt->getMemOperand());
8319 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8321 unsigned ResNo = UI.getUse().getResNo();
8322 // Ignore uses of the chain result.
8323 if (ResNo == NumVecs)
8326 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8329 // Now the vldN-lane intrinsic is dead except for its chain result.
8330 // Update uses of the chain.
8331 std::vector<SDValue> VLDDupResults;
8332 for (unsigned n = 0; n < NumVecs; ++n)
8333 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8334 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8335 DCI.CombineTo(VLD, VLDDupResults);
8340 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8341 /// ARMISD::VDUPLANE.
8342 static SDValue PerformVDUPLANECombine(SDNode *N,
8343 TargetLowering::DAGCombinerInfo &DCI) {
8344 SDValue Op = N->getOperand(0);
8346 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8347 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8348 if (CombineVLDDUP(N, DCI))
8349 return SDValue(N, 0);
8351 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8352 // redundant. Ignore bit_converts for now; element sizes are checked below.
8353 while (Op.getOpcode() == ISD::BITCAST)
8354 Op = Op.getOperand(0);
8355 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8358 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8359 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8360 // The canonical VMOV for a zero vector uses a 32-bit element size.
8361 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8363 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8365 EVT VT = N->getValueType(0);
8366 if (EltSize > VT.getVectorElementType().getSizeInBits())
8369 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8372 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8373 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8374 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8378 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8380 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8385 APFloat APF = C->getValueAPF();
8386 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8387 != APFloat::opOK || !isExact)
8390 c0 = (I == 0) ? cN : c0;
8391 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8398 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8399 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8400 /// when the VMUL has a constant operand that is a power of 2.
8402 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8403 /// vmul.f32 d16, d17, d16
8404 /// vcvt.s32.f32 d16, d16
8406 /// vcvt.s32.f32 d16, d16, #3
8407 static SDValue PerformVCVTCombine(SDNode *N,
8408 TargetLowering::DAGCombinerInfo &DCI,
8409 const ARMSubtarget *Subtarget) {
8410 SelectionDAG &DAG = DCI.DAG;
8411 SDValue Op = N->getOperand(0);
8413 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8414 Op.getOpcode() != ISD::FMUL)
8418 SDValue N0 = Op->getOperand(0);
8419 SDValue ConstVec = Op->getOperand(1);
8420 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8422 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8423 !isConstVecPow2(ConstVec, isSigned, C))
8426 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8427 Intrinsic::arm_neon_vcvtfp2fxu;
8428 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8430 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8431 DAG.getConstant(Log2_64(C), MVT::i32));
8434 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8435 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8436 /// when the VDIV has a constant operand that is a power of 2.
8438 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8439 /// vcvt.f32.s32 d16, d16
8440 /// vdiv.f32 d16, d17, d16
8442 /// vcvt.f32.s32 d16, d16, #3
8443 static SDValue PerformVDIVCombine(SDNode *N,
8444 TargetLowering::DAGCombinerInfo &DCI,
8445 const ARMSubtarget *Subtarget) {
8446 SelectionDAG &DAG = DCI.DAG;
8447 SDValue Op = N->getOperand(0);
8448 unsigned OpOpcode = Op.getNode()->getOpcode();
8450 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8451 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8455 SDValue ConstVec = N->getOperand(1);
8456 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8458 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8459 !isConstVecPow2(ConstVec, isSigned, C))
8462 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8463 Intrinsic::arm_neon_vcvtfxu2fp;
8464 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8466 DAG.getConstant(IntrinsicOpcode, MVT::i32),
8467 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8470 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8471 /// operand of a vector shift operation, where all the elements of the
8472 /// build_vector must have the same constant integer value.
8473 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8474 // Ignore bit_converts.
8475 while (Op.getOpcode() == ISD::BITCAST)
8476 Op = Op.getOperand(0);
8477 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8478 APInt SplatBits, SplatUndef;
8479 unsigned SplatBitSize;
8481 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8482 HasAnyUndefs, ElementBits) ||
8483 SplatBitSize > ElementBits)
8485 Cnt = SplatBits.getSExtValue();
8489 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8490 /// operand of a vector shift left operation. That value must be in the range:
8491 /// 0 <= Value < ElementBits for a left shift; or
8492 /// 0 <= Value <= ElementBits for a long left shift.
8493 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8494 assert(VT.isVector() && "vector shift count is not a vector type");
8495 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8496 if (! getVShiftImm(Op, ElementBits, Cnt))
8498 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8501 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8502 /// operand of a vector shift right operation. For a shift opcode, the value
8503 /// is positive, but for an intrinsic the value count must be negative. The
8504 /// absolute value must be in the range:
8505 /// 1 <= |Value| <= ElementBits for a right shift; or
8506 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8507 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8509 assert(VT.isVector() && "vector shift count is not a vector type");
8510 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8511 if (! getVShiftImm(Op, ElementBits, Cnt))
8515 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8518 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8519 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8520 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8523 // Don't do anything for most intrinsics.
8526 // Vector shifts: check for immediate versions and lower them.
8527 // Note: This is done during DAG combining instead of DAG legalizing because
8528 // the build_vectors for 64-bit vector element shift counts are generally
8529 // not legal, and it is hard to see their values after they get legalized to
8530 // loads from a constant pool.
8531 case Intrinsic::arm_neon_vshifts:
8532 case Intrinsic::arm_neon_vshiftu:
8533 case Intrinsic::arm_neon_vshiftls:
8534 case Intrinsic::arm_neon_vshiftlu:
8535 case Intrinsic::arm_neon_vshiftn:
8536 case Intrinsic::arm_neon_vrshifts:
8537 case Intrinsic::arm_neon_vrshiftu:
8538 case Intrinsic::arm_neon_vrshiftn:
8539 case Intrinsic::arm_neon_vqshifts:
8540 case Intrinsic::arm_neon_vqshiftu:
8541 case Intrinsic::arm_neon_vqshiftsu:
8542 case Intrinsic::arm_neon_vqshiftns:
8543 case Intrinsic::arm_neon_vqshiftnu:
8544 case Intrinsic::arm_neon_vqshiftnsu:
8545 case Intrinsic::arm_neon_vqrshiftns:
8546 case Intrinsic::arm_neon_vqrshiftnu:
8547 case Intrinsic::arm_neon_vqrshiftnsu: {
8548 EVT VT = N->getOperand(1).getValueType();
8550 unsigned VShiftOpc = 0;
8553 case Intrinsic::arm_neon_vshifts:
8554 case Intrinsic::arm_neon_vshiftu:
8555 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8556 VShiftOpc = ARMISD::VSHL;
8559 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8560 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8561 ARMISD::VSHRs : ARMISD::VSHRu);
8566 case Intrinsic::arm_neon_vshiftls:
8567 case Intrinsic::arm_neon_vshiftlu:
8568 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8570 llvm_unreachable("invalid shift count for vshll intrinsic");
8572 case Intrinsic::arm_neon_vrshifts:
8573 case Intrinsic::arm_neon_vrshiftu:
8574 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8578 case Intrinsic::arm_neon_vqshifts:
8579 case Intrinsic::arm_neon_vqshiftu:
8580 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8584 case Intrinsic::arm_neon_vqshiftsu:
8585 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8587 llvm_unreachable("invalid shift count for vqshlu intrinsic");
8589 case Intrinsic::arm_neon_vshiftn:
8590 case Intrinsic::arm_neon_vrshiftn:
8591 case Intrinsic::arm_neon_vqshiftns:
8592 case Intrinsic::arm_neon_vqshiftnu:
8593 case Intrinsic::arm_neon_vqshiftnsu:
8594 case Intrinsic::arm_neon_vqrshiftns:
8595 case Intrinsic::arm_neon_vqrshiftnu:
8596 case Intrinsic::arm_neon_vqrshiftnsu:
8597 // Narrowing shifts require an immediate right shift.
8598 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8600 llvm_unreachable("invalid shift count for narrowing vector shift "
8604 llvm_unreachable("unhandled vector shift");
8608 case Intrinsic::arm_neon_vshifts:
8609 case Intrinsic::arm_neon_vshiftu:
8610 // Opcode already set above.
8612 case Intrinsic::arm_neon_vshiftls:
8613 case Intrinsic::arm_neon_vshiftlu:
8614 if (Cnt == VT.getVectorElementType().getSizeInBits())
8615 VShiftOpc = ARMISD::VSHLLi;
8617 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8618 ARMISD::VSHLLs : ARMISD::VSHLLu);
8620 case Intrinsic::arm_neon_vshiftn:
8621 VShiftOpc = ARMISD::VSHRN; break;
8622 case Intrinsic::arm_neon_vrshifts:
8623 VShiftOpc = ARMISD::VRSHRs; break;
8624 case Intrinsic::arm_neon_vrshiftu:
8625 VShiftOpc = ARMISD::VRSHRu; break;
8626 case Intrinsic::arm_neon_vrshiftn:
8627 VShiftOpc = ARMISD::VRSHRN; break;
8628 case Intrinsic::arm_neon_vqshifts:
8629 VShiftOpc = ARMISD::VQSHLs; break;
8630 case Intrinsic::arm_neon_vqshiftu:
8631 VShiftOpc = ARMISD::VQSHLu; break;
8632 case Intrinsic::arm_neon_vqshiftsu:
8633 VShiftOpc = ARMISD::VQSHLsu; break;
8634 case Intrinsic::arm_neon_vqshiftns:
8635 VShiftOpc = ARMISD::VQSHRNs; break;
8636 case Intrinsic::arm_neon_vqshiftnu:
8637 VShiftOpc = ARMISD::VQSHRNu; break;
8638 case Intrinsic::arm_neon_vqshiftnsu:
8639 VShiftOpc = ARMISD::VQSHRNsu; break;
8640 case Intrinsic::arm_neon_vqrshiftns:
8641 VShiftOpc = ARMISD::VQRSHRNs; break;
8642 case Intrinsic::arm_neon_vqrshiftnu:
8643 VShiftOpc = ARMISD::VQRSHRNu; break;
8644 case Intrinsic::arm_neon_vqrshiftnsu:
8645 VShiftOpc = ARMISD::VQRSHRNsu; break;
8648 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8649 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8652 case Intrinsic::arm_neon_vshiftins: {
8653 EVT VT = N->getOperand(1).getValueType();
8655 unsigned VShiftOpc = 0;
8657 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8658 VShiftOpc = ARMISD::VSLI;
8659 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8660 VShiftOpc = ARMISD::VSRI;
8662 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8665 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8666 N->getOperand(1), N->getOperand(2),
8667 DAG.getConstant(Cnt, MVT::i32));
8670 case Intrinsic::arm_neon_vqrshifts:
8671 case Intrinsic::arm_neon_vqrshiftu:
8672 // No immediate versions of these to check for.
8679 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8680 /// lowers them. As with the vector shift intrinsics, this is done during DAG
8681 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8682 /// vector element shift counts are generally not legal, and it is hard to see
8683 /// their values after they get legalized to loads from a constant pool.
8684 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8685 const ARMSubtarget *ST) {
8686 EVT VT = N->getValueType(0);
8687 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8688 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8689 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8690 SDValue N1 = N->getOperand(1);
8691 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8692 SDValue N0 = N->getOperand(0);
8693 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8694 DAG.MaskedValueIsZero(N0.getOperand(0),
8695 APInt::getHighBitsSet(32, 16)))
8696 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8700 // Nothing to be done for scalar shifts.
8701 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8702 if (!VT.isVector() || !TLI.isTypeLegal(VT))
8705 assert(ST->hasNEON() && "unexpected vector shift");
8708 switch (N->getOpcode()) {
8709 default: llvm_unreachable("unexpected shift opcode");
8712 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8713 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8714 DAG.getConstant(Cnt, MVT::i32));
8719 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8720 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8721 ARMISD::VSHRs : ARMISD::VSHRu);
8722 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8723 DAG.getConstant(Cnt, MVT::i32));
8729 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8730 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8731 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8732 const ARMSubtarget *ST) {
8733 SDValue N0 = N->getOperand(0);
8735 // Check for sign- and zero-extensions of vector extract operations of 8-
8736 // and 16-bit vector elements. NEON supports these directly. They are
8737 // handled during DAG combining because type legalization will promote them
8738 // to 32-bit types and it is messy to recognize the operations after that.
8739 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8740 SDValue Vec = N0.getOperand(0);
8741 SDValue Lane = N0.getOperand(1);
8742 EVT VT = N->getValueType(0);
8743 EVT EltVT = N0.getValueType();
8744 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8746 if (VT == MVT::i32 &&
8747 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8748 TLI.isTypeLegal(Vec.getValueType()) &&
8749 isa<ConstantSDNode>(Lane)) {
8752 switch (N->getOpcode()) {
8753 default: llvm_unreachable("unexpected opcode");
8754 case ISD::SIGN_EXTEND:
8755 Opc = ARMISD::VGETLANEs;
8757 case ISD::ZERO_EXTEND:
8758 case ISD::ANY_EXTEND:
8759 Opc = ARMISD::VGETLANEu;
8762 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8769 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8770 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8771 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8772 const ARMSubtarget *ST) {
8773 // If the target supports NEON, try to use vmax/vmin instructions for f32
8774 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
8775 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
8776 // a NaN; only do the transformation when it matches that behavior.
8778 // For now only do this when using NEON for FP operations; if using VFP, it
8779 // is not obvious that the benefit outweighs the cost of switching to the
8781 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8782 N->getValueType(0) != MVT::f32)
8785 SDValue CondLHS = N->getOperand(0);
8786 SDValue CondRHS = N->getOperand(1);
8787 SDValue LHS = N->getOperand(2);
8788 SDValue RHS = N->getOperand(3);
8789 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8791 unsigned Opcode = 0;
8793 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8794 IsReversed = false; // x CC y ? x : y
8795 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8796 IsReversed = true ; // x CC y ? y : x
8810 // If LHS is NaN, an ordered comparison will be false and the result will
8811 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
8812 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8813 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8814 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8816 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8817 // will return -0, so vmin can only be used for unsafe math or if one of
8818 // the operands is known to be nonzero.
8819 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8820 !DAG.getTarget().Options.UnsafeFPMath &&
8821 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8823 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8832 // If LHS is NaN, an ordered comparison will be false and the result will
8833 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
8834 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8835 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8836 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8838 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8839 // will return +0, so vmax can only be used for unsafe math or if one of
8840 // the operands is known to be nonzero.
8841 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8842 !DAG.getTarget().Options.UnsafeFPMath &&
8843 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8845 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8851 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8854 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8856 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8857 SDValue Cmp = N->getOperand(4);
8858 if (Cmp.getOpcode() != ARMISD::CMPZ)
8859 // Only looking at EQ and NE cases.
8862 EVT VT = N->getValueType(0);
8863 DebugLoc dl = N->getDebugLoc();
8864 SDValue LHS = Cmp.getOperand(0);
8865 SDValue RHS = Cmp.getOperand(1);
8866 SDValue FalseVal = N->getOperand(0);
8867 SDValue TrueVal = N->getOperand(1);
8868 SDValue ARMcc = N->getOperand(2);
8869 ARMCC::CondCodes CC =
8870 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8888 /// FIXME: Turn this into a target neutral optimization?
8890 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8891 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8892 N->getOperand(3), Cmp);
8893 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8895 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8896 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8897 N->getOperand(3), NewCmp);
8900 if (Res.getNode()) {
8901 APInt KnownZero, KnownOne;
8902 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8903 // Capture demanded bits information that would be otherwise lost.
8904 if (KnownZero == 0xfffffffe)
8905 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8906 DAG.getValueType(MVT::i1));
8907 else if (KnownZero == 0xffffff00)
8908 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8909 DAG.getValueType(MVT::i8));
8910 else if (KnownZero == 0xffff0000)
8911 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8912 DAG.getValueType(MVT::i16));
8918 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8919 DAGCombinerInfo &DCI) const {
8920 switch (N->getOpcode()) {
8922 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
8923 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
8924 case ISD::SUB: return PerformSUBCombine(N, DCI);
8925 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
8926 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
8927 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
8928 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
8929 case ARMISD::BFI: return PerformBFICombine(N, DCI);
8930 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8931 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8932 case ISD::STORE: return PerformSTORECombine(N, DCI);
8933 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8934 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8935 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8936 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8937 case ISD::FP_TO_SINT:
8938 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8939 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
8940 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8943 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
8944 case ISD::SIGN_EXTEND:
8945 case ISD::ZERO_EXTEND:
8946 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8947 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8948 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8949 case ARMISD::VLD2DUP:
8950 case ARMISD::VLD3DUP:
8951 case ARMISD::VLD4DUP:
8952 return CombineBaseUpdate(N, DCI);
8953 case ISD::INTRINSIC_VOID:
8954 case ISD::INTRINSIC_W_CHAIN:
8955 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8956 case Intrinsic::arm_neon_vld1:
8957 case Intrinsic::arm_neon_vld2:
8958 case Intrinsic::arm_neon_vld3:
8959 case Intrinsic::arm_neon_vld4:
8960 case Intrinsic::arm_neon_vld2lane:
8961 case Intrinsic::arm_neon_vld3lane:
8962 case Intrinsic::arm_neon_vld4lane:
8963 case Intrinsic::arm_neon_vst1:
8964 case Intrinsic::arm_neon_vst2:
8965 case Intrinsic::arm_neon_vst3:
8966 case Intrinsic::arm_neon_vst4:
8967 case Intrinsic::arm_neon_vst2lane:
8968 case Intrinsic::arm_neon_vst3lane:
8969 case Intrinsic::arm_neon_vst4lane:
8970 return CombineBaseUpdate(N, DCI);
8978 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8980 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8983 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8984 if (!Subtarget->allowsUnalignedMem())
8987 switch (VT.getSimpleVT().SimpleTy) {
8995 return Subtarget->hasNEON();
8996 // FIXME: VLD1 etc with standard alignment is legal.
9000 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9001 unsigned AlignCheck) {
9002 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9003 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9006 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9007 unsigned DstAlign, unsigned SrcAlign,
9010 MachineFunction &MF) const {
9011 const Function *F = MF.getFunction();
9013 // See if we can use NEON instructions for this...
9015 !F->hasFnAttr(Attribute::NoImplicitFloat) &&
9016 Subtarget->hasNEON()) {
9017 if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
9019 } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
9024 // Lowering to i32/i16 if the size permits.
9027 } else if (Size >= 2) {
9031 // Let the target-independent logic figure it out.
9035 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9040 switch (VT.getSimpleVT().SimpleTy) {
9041 default: return false;
9056 if ((V & (Scale - 1)) != 0)
9059 return V == (V & ((1LL << 5) - 1));
9062 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9063 const ARMSubtarget *Subtarget) {
9070 switch (VT.getSimpleVT().SimpleTy) {
9071 default: return false;
9076 // + imm12 or - imm8
9078 return V == (V & ((1LL << 8) - 1));
9079 return V == (V & ((1LL << 12) - 1));
9082 // Same as ARM mode. FIXME: NEON?
9083 if (!Subtarget->hasVFP2())
9088 return V == (V & ((1LL << 8) - 1));
9092 /// isLegalAddressImmediate - Return true if the integer value can be used
9093 /// as the offset of the target addressing mode for load / store of the
9095 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9096 const ARMSubtarget *Subtarget) {
9103 if (Subtarget->isThumb1Only())
9104 return isLegalT1AddressImmediate(V, VT);
9105 else if (Subtarget->isThumb2())
9106 return isLegalT2AddressImmediate(V, VT, Subtarget);
9111 switch (VT.getSimpleVT().SimpleTy) {
9112 default: return false;
9117 return V == (V & ((1LL << 12) - 1));
9120 return V == (V & ((1LL << 8) - 1));
9123 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9128 return V == (V & ((1LL << 8) - 1));
9132 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9134 int Scale = AM.Scale;
9138 switch (VT.getSimpleVT().SimpleTy) {
9139 default: return false;
9148 return Scale == 2 || Scale == 4 || Scale == 8;
9151 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9155 // Note, we allow "void" uses (basically, uses that aren't loads or
9156 // stores), because arm allows folding a scale into many arithmetic
9157 // operations. This should be made more precise and revisited later.
9159 // Allow r << imm, but the imm has to be a multiple of two.
9160 if (Scale & 1) return false;
9161 return isPowerOf2_32(Scale);
9165 /// isLegalAddressingMode - Return true if the addressing mode represented
9166 /// by AM is legal for this target, for a load/store of the specified type.
9167 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9169 EVT VT = getValueType(Ty, true);
9170 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9173 // Can never fold addr of global into load/store.
9178 case 0: // no scale reg, must be "r+i" or "r", or "i".
9181 if (Subtarget->isThumb1Only())
9185 // ARM doesn't support any R+R*scale+imm addr modes.
9192 if (Subtarget->isThumb2())
9193 return isLegalT2ScaledAddressingMode(AM, VT);
9195 int Scale = AM.Scale;
9196 switch (VT.getSimpleVT().SimpleTy) {
9197 default: return false;
9201 if (Scale < 0) Scale = -Scale;
9205 return isPowerOf2_32(Scale & ~1);
9209 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9214 // Note, we allow "void" uses (basically, uses that aren't loads or
9215 // stores), because arm allows folding a scale into many arithmetic
9216 // operations. This should be made more precise and revisited later.
9218 // Allow r << imm, but the imm has to be a multiple of two.
9219 if (Scale & 1) return false;
9220 return isPowerOf2_32(Scale);
9226 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9227 /// icmp immediate, that is the target has icmp instructions which can compare
9228 /// a register against the immediate without having to materialize the
9229 /// immediate into a register.
9230 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9231 // Thumb2 and ARM modes can use cmn for negative immediates.
9232 if (!Subtarget->isThumb())
9233 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9234 if (Subtarget->isThumb2())
9235 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9236 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9237 return Imm >= 0 && Imm <= 255;
9240 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9241 /// *or sub* immediate, that is the target has add or sub instructions which can
9242 /// add a register with the immediate without having to materialize the
9243 /// immediate into a register.
9244 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9245 // Same encoding for add/sub, just flip the sign.
9246 int64_t AbsImm = llvm::abs64(Imm);
9247 if (!Subtarget->isThumb())
9248 return ARM_AM::getSOImmVal(AbsImm) != -1;
9249 if (Subtarget->isThumb2())
9250 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9251 // Thumb1 only has 8-bit unsigned immediate.
9252 return AbsImm >= 0 && AbsImm <= 255;
9255 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9256 bool isSEXTLoad, SDValue &Base,
9257 SDValue &Offset, bool &isInc,
9258 SelectionDAG &DAG) {
9259 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9262 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9264 Base = Ptr->getOperand(0);
9265 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9266 int RHSC = (int)RHS->getZExtValue();
9267 if (RHSC < 0 && RHSC > -256) {
9268 assert(Ptr->getOpcode() == ISD::ADD);
9270 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9274 isInc = (Ptr->getOpcode() == ISD::ADD);
9275 Offset = Ptr->getOperand(1);
9277 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9279 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9280 int RHSC = (int)RHS->getZExtValue();
9281 if (RHSC < 0 && RHSC > -0x1000) {
9282 assert(Ptr->getOpcode() == ISD::ADD);
9284 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9285 Base = Ptr->getOperand(0);
9290 if (Ptr->getOpcode() == ISD::ADD) {
9292 ARM_AM::ShiftOpc ShOpcVal=
9293 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9294 if (ShOpcVal != ARM_AM::no_shift) {
9295 Base = Ptr->getOperand(1);
9296 Offset = Ptr->getOperand(0);
9298 Base = Ptr->getOperand(0);
9299 Offset = Ptr->getOperand(1);
9304 isInc = (Ptr->getOpcode() == ISD::ADD);
9305 Base = Ptr->getOperand(0);
9306 Offset = Ptr->getOperand(1);
9310 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9314 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9315 bool isSEXTLoad, SDValue &Base,
9316 SDValue &Offset, bool &isInc,
9317 SelectionDAG &DAG) {
9318 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9321 Base = Ptr->getOperand(0);
9322 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9323 int RHSC = (int)RHS->getZExtValue();
9324 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9325 assert(Ptr->getOpcode() == ISD::ADD);
9327 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9329 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9330 isInc = Ptr->getOpcode() == ISD::ADD;
9331 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9339 /// getPreIndexedAddressParts - returns true by value, base pointer and
9340 /// offset pointer and addressing mode by reference if the node's address
9341 /// can be legally represented as pre-indexed load / store address.
9343 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9345 ISD::MemIndexedMode &AM,
9346 SelectionDAG &DAG) const {
9347 if (Subtarget->isThumb1Only())
9352 bool isSEXTLoad = false;
9353 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9354 Ptr = LD->getBasePtr();
9355 VT = LD->getMemoryVT();
9356 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9357 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9358 Ptr = ST->getBasePtr();
9359 VT = ST->getMemoryVT();
9364 bool isLegal = false;
9365 if (Subtarget->isThumb2())
9366 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9367 Offset, isInc, DAG);
9369 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9370 Offset, isInc, DAG);
9374 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9378 /// getPostIndexedAddressParts - returns true by value, base pointer and
9379 /// offset pointer and addressing mode by reference if this node can be
9380 /// combined with a load / store to form a post-indexed load / store.
9381 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9384 ISD::MemIndexedMode &AM,
9385 SelectionDAG &DAG) const {
9386 if (Subtarget->isThumb1Only())
9391 bool isSEXTLoad = false;
9392 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9393 VT = LD->getMemoryVT();
9394 Ptr = LD->getBasePtr();
9395 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9396 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9397 VT = ST->getMemoryVT();
9398 Ptr = ST->getBasePtr();
9403 bool isLegal = false;
9404 if (Subtarget->isThumb2())
9405 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9408 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9414 // Swap base ptr and offset to catch more post-index load / store when
9415 // it's legal. In Thumb2 mode, offset must be an immediate.
9416 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9417 !Subtarget->isThumb2())
9418 std::swap(Base, Offset);
9420 // Post-indexed load / store update the base pointer.
9425 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9429 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9432 const SelectionDAG &DAG,
9433 unsigned Depth) const {
9434 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9435 switch (Op.getOpcode()) {
9437 case ARMISD::CMOV: {
9438 // Bits are known zero/one if known on the LHS and RHS.
9439 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9440 if (KnownZero == 0 && KnownOne == 0) return;
9442 APInt KnownZeroRHS, KnownOneRHS;
9443 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9444 KnownZero &= KnownZeroRHS;
9445 KnownOne &= KnownOneRHS;
9451 //===----------------------------------------------------------------------===//
9452 // ARM Inline Assembly Support
9453 //===----------------------------------------------------------------------===//
9455 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9456 // Looking for "rev" which is V6+.
9457 if (!Subtarget->hasV6Ops())
9460 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9461 std::string AsmStr = IA->getAsmString();
9462 SmallVector<StringRef, 4> AsmPieces;
9463 SplitString(AsmStr, AsmPieces, ";\n");
9465 switch (AsmPieces.size()) {
9466 default: return false;
9468 AsmStr = AsmPieces[0];
9470 SplitString(AsmStr, AsmPieces, " \t,");
9473 if (AsmPieces.size() == 3 &&
9474 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9475 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9476 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9477 if (Ty && Ty->getBitWidth() == 32)
9478 return IntrinsicLowering::LowerToByteSwap(CI);
9486 /// getConstraintType - Given a constraint letter, return the type of
9487 /// constraint it is for this target.
9488 ARMTargetLowering::ConstraintType
9489 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9490 if (Constraint.size() == 1) {
9491 switch (Constraint[0]) {
9493 case 'l': return C_RegisterClass;
9494 case 'w': return C_RegisterClass;
9495 case 'h': return C_RegisterClass;
9496 case 'x': return C_RegisterClass;
9497 case 't': return C_RegisterClass;
9498 case 'j': return C_Other; // Constant for movw.
9499 // An address with a single base register. Due to the way we
9500 // currently handle addresses it is the same as an 'r' memory constraint.
9501 case 'Q': return C_Memory;
9503 } else if (Constraint.size() == 2) {
9504 switch (Constraint[0]) {
9506 // All 'U+' constraints are addresses.
9507 case 'U': return C_Memory;
9510 return TargetLowering::getConstraintType(Constraint);
9513 /// Examine constraint type and operand type and determine a weight value.
9514 /// This object must already have been set up with the operand type
9515 /// and the current alternative constraint selected.
9516 TargetLowering::ConstraintWeight
9517 ARMTargetLowering::getSingleConstraintMatchWeight(
9518 AsmOperandInfo &info, const char *constraint) const {
9519 ConstraintWeight weight = CW_Invalid;
9520 Value *CallOperandVal = info.CallOperandVal;
9521 // If we don't have a value, we can't do a match,
9522 // but allow it at the lowest weight.
9523 if (CallOperandVal == NULL)
9525 Type *type = CallOperandVal->getType();
9526 // Look at the constraint type.
9527 switch (*constraint) {
9529 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9532 if (type->isIntegerTy()) {
9533 if (Subtarget->isThumb())
9534 weight = CW_SpecificReg;
9536 weight = CW_Register;
9540 if (type->isFloatingPointTy())
9541 weight = CW_Register;
9547 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9549 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9551 if (Constraint.size() == 1) {
9552 // GCC ARM Constraint Letters
9553 switch (Constraint[0]) {
9554 case 'l': // Low regs or general regs.
9555 if (Subtarget->isThumb())
9556 return RCPair(0U, &ARM::tGPRRegClass);
9557 return RCPair(0U, &ARM::GPRRegClass);
9558 case 'h': // High regs or no regs.
9559 if (Subtarget->isThumb())
9560 return RCPair(0U, &ARM::hGPRRegClass);
9563 return RCPair(0U, &ARM::GPRRegClass);
9566 return RCPair(0U, &ARM::SPRRegClass);
9567 if (VT.getSizeInBits() == 64)
9568 return RCPair(0U, &ARM::DPRRegClass);
9569 if (VT.getSizeInBits() == 128)
9570 return RCPair(0U, &ARM::QPRRegClass);
9574 return RCPair(0U, &ARM::SPR_8RegClass);
9575 if (VT.getSizeInBits() == 64)
9576 return RCPair(0U, &ARM::DPR_8RegClass);
9577 if (VT.getSizeInBits() == 128)
9578 return RCPair(0U, &ARM::QPR_8RegClass);
9582 return RCPair(0U, &ARM::SPRRegClass);
9586 if (StringRef("{cc}").equals_lower(Constraint))
9587 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9589 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9592 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9593 /// vector. If it is invalid, don't add anything to Ops.
9594 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9595 std::string &Constraint,
9596 std::vector<SDValue>&Ops,
9597 SelectionDAG &DAG) const {
9598 SDValue Result(0, 0);
9600 // Currently only support length 1 constraints.
9601 if (Constraint.length() != 1) return;
9603 char ConstraintLetter = Constraint[0];
9604 switch (ConstraintLetter) {
9607 case 'I': case 'J': case 'K': case 'L':
9608 case 'M': case 'N': case 'O':
9609 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9613 int64_t CVal64 = C->getSExtValue();
9614 int CVal = (int) CVal64;
9615 // None of these constraints allow values larger than 32 bits. Check
9616 // that the value fits in an int.
9620 switch (ConstraintLetter) {
9622 // Constant suitable for movw, must be between 0 and
9624 if (Subtarget->hasV6T2Ops())
9625 if (CVal >= 0 && CVal <= 65535)
9629 if (Subtarget->isThumb1Only()) {
9630 // This must be a constant between 0 and 255, for ADD
9632 if (CVal >= 0 && CVal <= 255)
9634 } else if (Subtarget->isThumb2()) {
9635 // A constant that can be used as an immediate value in a
9636 // data-processing instruction.
9637 if (ARM_AM::getT2SOImmVal(CVal) != -1)
9640 // A constant that can be used as an immediate value in a
9641 // data-processing instruction.
9642 if (ARM_AM::getSOImmVal(CVal) != -1)
9648 if (Subtarget->isThumb()) { // FIXME thumb2
9649 // This must be a constant between -255 and -1, for negated ADD
9650 // immediates. This can be used in GCC with an "n" modifier that
9651 // prints the negated value, for use with SUB instructions. It is
9652 // not useful otherwise but is implemented for compatibility.
9653 if (CVal >= -255 && CVal <= -1)
9656 // This must be a constant between -4095 and 4095. It is not clear
9657 // what this constraint is intended for. Implemented for
9658 // compatibility with GCC.
9659 if (CVal >= -4095 && CVal <= 4095)
9665 if (Subtarget->isThumb1Only()) {
9666 // A 32-bit value where only one byte has a nonzero value. Exclude
9667 // zero to match GCC. This constraint is used by GCC internally for
9668 // constants that can be loaded with a move/shift combination.
9669 // It is not useful otherwise but is implemented for compatibility.
9670 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9672 } else if (Subtarget->isThumb2()) {
9673 // A constant whose bitwise inverse can be used as an immediate
9674 // value in a data-processing instruction. This can be used in GCC
9675 // with a "B" modifier that prints the inverted value, for use with
9676 // BIC and MVN instructions. It is not useful otherwise but is
9677 // implemented for compatibility.
9678 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9681 // A constant whose bitwise inverse can be used as an immediate
9682 // value in a data-processing instruction. This can be used in GCC
9683 // with a "B" modifier that prints the inverted value, for use with
9684 // BIC and MVN instructions. It is not useful otherwise but is
9685 // implemented for compatibility.
9686 if (ARM_AM::getSOImmVal(~CVal) != -1)
9692 if (Subtarget->isThumb1Only()) {
9693 // This must be a constant between -7 and 7,
9694 // for 3-operand ADD/SUB immediate instructions.
9695 if (CVal >= -7 && CVal < 7)
9697 } else if (Subtarget->isThumb2()) {
9698 // A constant whose negation can be used as an immediate value in a
9699 // data-processing instruction. This can be used in GCC with an "n"
9700 // modifier that prints the negated value, for use with SUB
9701 // instructions. It is not useful otherwise but is implemented for
9703 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9706 // A constant whose negation can be used as an immediate value in a
9707 // data-processing instruction. This can be used in GCC with an "n"
9708 // modifier that prints the negated value, for use with SUB
9709 // instructions. It is not useful otherwise but is implemented for
9711 if (ARM_AM::getSOImmVal(-CVal) != -1)
9717 if (Subtarget->isThumb()) { // FIXME thumb2
9718 // This must be a multiple of 4 between 0 and 1020, for
9719 // ADD sp + immediate.
9720 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9723 // A power of two or a constant between 0 and 32. This is used in
9724 // GCC for the shift amount on shifted register operands, but it is
9725 // useful in general for any shift amounts.
9726 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9732 if (Subtarget->isThumb()) { // FIXME thumb2
9733 // This must be a constant between 0 and 31, for shift amounts.
9734 if (CVal >= 0 && CVal <= 31)
9740 if (Subtarget->isThumb()) { // FIXME thumb2
9741 // This must be a multiple of 4 between -508 and 508, for
9742 // ADD/SUB sp = sp + immediate.
9743 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9748 Result = DAG.getTargetConstant(CVal, Op.getValueType());
9752 if (Result.getNode()) {
9753 Ops.push_back(Result);
9756 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9760 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9761 // The ARM target isn't yet aware of offsets.
9765 bool ARM::isBitFieldInvertedMask(unsigned v) {
9766 if (v == 0xffffffff)
9768 // there can be 1's on either or both "outsides", all the "inside"
9770 unsigned int lsb = 0, msb = 31;
9771 while (v & (1 << msb)) --msb;
9772 while (v & (1 << lsb)) ++lsb;
9773 for (unsigned int i = lsb; i <= msb; ++i) {
9780 /// isFPImmLegal - Returns true if the target can instruction select the
9781 /// specified FP immediate natively. If false, the legalizer will
9782 /// materialize the FP immediate as a load from a constant pool.
9783 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9784 if (!Subtarget->hasVFP3())
9787 return ARM_AM::getFP32Imm(Imm) != -1;
9789 return ARM_AM::getFP64Imm(Imm) != -1;
9793 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9794 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
9795 /// specified in the intrinsic calls.
9796 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9798 unsigned Intrinsic) const {
9799 switch (Intrinsic) {
9800 case Intrinsic::arm_neon_vld1:
9801 case Intrinsic::arm_neon_vld2:
9802 case Intrinsic::arm_neon_vld3:
9803 case Intrinsic::arm_neon_vld4:
9804 case Intrinsic::arm_neon_vld2lane:
9805 case Intrinsic::arm_neon_vld3lane:
9806 case Intrinsic::arm_neon_vld4lane: {
9807 Info.opc = ISD::INTRINSIC_W_CHAIN;
9808 // Conservatively set memVT to the entire set of vectors loaded.
9809 uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9810 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9811 Info.ptrVal = I.getArgOperand(0);
9813 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9814 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9815 Info.vol = false; // volatile loads with NEON intrinsics not supported
9816 Info.readMem = true;
9817 Info.writeMem = false;
9820 case Intrinsic::arm_neon_vst1:
9821 case Intrinsic::arm_neon_vst2:
9822 case Intrinsic::arm_neon_vst3:
9823 case Intrinsic::arm_neon_vst4:
9824 case Intrinsic::arm_neon_vst2lane:
9825 case Intrinsic::arm_neon_vst3lane:
9826 case Intrinsic::arm_neon_vst4lane: {
9827 Info.opc = ISD::INTRINSIC_VOID;
9828 // Conservatively set memVT to the entire set of vectors stored.
9829 unsigned NumElts = 0;
9830 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9831 Type *ArgTy = I.getArgOperand(ArgI)->getType();
9832 if (!ArgTy->isVectorTy())
9834 NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9836 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9837 Info.ptrVal = I.getArgOperand(0);
9839 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9840 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9841 Info.vol = false; // volatile stores with NEON intrinsics not supported
9842 Info.readMem = false;
9843 Info.writeMem = true;
9846 case Intrinsic::arm_strexd: {
9847 Info.opc = ISD::INTRINSIC_W_CHAIN;
9848 Info.memVT = MVT::i64;
9849 Info.ptrVal = I.getArgOperand(2);
9853 Info.readMem = false;
9854 Info.writeMem = true;
9857 case Intrinsic::arm_ldrexd: {
9858 Info.opc = ISD::INTRINSIC_W_CHAIN;
9859 Info.memVT = MVT::i64;
9860 Info.ptrVal = I.getArgOperand(0);
9864 Info.readMem = true;
9865 Info.writeMem = false;