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);
799 setTargetDAGCombine(ISD::AND);
800 setTargetDAGCombine(ISD::OR);
801 setTargetDAGCombine(ISD::XOR);
803 if (Subtarget->hasV6Ops())
804 setTargetDAGCombine(ISD::SRL);
806 setStackPointerRegisterToSaveRestore(ARM::SP);
808 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
809 !Subtarget->hasVFP2())
810 setSchedulingPreference(Sched::RegPressure);
812 setSchedulingPreference(Sched::Hybrid);
814 //// temporary - rewrite interface to use type
815 maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
816 maxStoresPerMemset = 16;
817 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
819 // On ARM arguments smaller than 4 bytes are extended, so all arguments
820 // are at least 4 bytes aligned.
821 setMinStackArgumentAlignment(4);
823 benefitFromCodePlacementOpt = true;
825 // Prefer likely predicted branches to selects on out-of-order cores.
826 predictableSelectIsExpensive = Subtarget->isCortexA9();
828 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
831 // FIXME: It might make sense to define the representative register class as the
832 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
833 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
834 // SPR's representative would be DPR_VFP2. This should work well if register
835 // pressure tracking were modified such that a register use would increment the
836 // pressure of the register class's representative and all of it's super
837 // classes' representatives transitively. We have not implemented this because
838 // of the difficulty prior to coalescing of modeling operand register classes
839 // due to the common occurrence of cross class copies and subregister insertions
841 std::pair<const TargetRegisterClass*, uint8_t>
842 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
843 const TargetRegisterClass *RRC = 0;
845 switch (VT.getSimpleVT().SimpleTy) {
847 return TargetLowering::findRepresentativeClass(VT);
848 // Use DPR as representative register class for all floating point
849 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
850 // the cost is 1 for both f32 and f64.
851 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
852 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
853 RRC = &ARM::DPRRegClass;
854 // When NEON is used for SP, only half of the register file is available
855 // because operations that define both SP and DP results will be constrained
856 // to the VFP2 class (D0-D15). We currently model this constraint prior to
857 // coalescing by double-counting the SP regs. See the FIXME above.
858 if (Subtarget->useNEONForSinglePrecisionFP())
861 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
862 case MVT::v4f32: case MVT::v2f64:
863 RRC = &ARM::DPRRegClass;
867 RRC = &ARM::DPRRegClass;
871 RRC = &ARM::DPRRegClass;
875 return std::make_pair(RRC, Cost);
878 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
881 case ARMISD::Wrapper: return "ARMISD::Wrapper";
882 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
883 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
884 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
885 case ARMISD::CALL: return "ARMISD::CALL";
886 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
887 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
888 case ARMISD::tCALL: return "ARMISD::tCALL";
889 case ARMISD::BRCOND: return "ARMISD::BRCOND";
890 case ARMISD::BR_JT: return "ARMISD::BR_JT";
891 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
892 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
893 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
894 case ARMISD::CMP: return "ARMISD::CMP";
895 case ARMISD::CMN: return "ARMISD::CMN";
896 case ARMISD::CMPZ: return "ARMISD::CMPZ";
897 case ARMISD::CMPFP: return "ARMISD::CMPFP";
898 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
899 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
900 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
902 case ARMISD::CMOV: return "ARMISD::CMOV";
904 case ARMISD::RBIT: return "ARMISD::RBIT";
906 case ARMISD::FTOSI: return "ARMISD::FTOSI";
907 case ARMISD::FTOUI: return "ARMISD::FTOUI";
908 case ARMISD::SITOF: return "ARMISD::SITOF";
909 case ARMISD::UITOF: return "ARMISD::UITOF";
911 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
912 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
913 case ARMISD::RRX: return "ARMISD::RRX";
915 case ARMISD::ADDC: return "ARMISD::ADDC";
916 case ARMISD::ADDE: return "ARMISD::ADDE";
917 case ARMISD::SUBC: return "ARMISD::SUBC";
918 case ARMISD::SUBE: return "ARMISD::SUBE";
920 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
921 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
923 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
924 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
926 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
928 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
930 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
932 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
933 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
935 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
937 case ARMISD::VCEQ: return "ARMISD::VCEQ";
938 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
939 case ARMISD::VCGE: return "ARMISD::VCGE";
940 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
941 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
942 case ARMISD::VCGEU: return "ARMISD::VCGEU";
943 case ARMISD::VCGT: return "ARMISD::VCGT";
944 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
945 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
946 case ARMISD::VCGTU: return "ARMISD::VCGTU";
947 case ARMISD::VTST: return "ARMISD::VTST";
949 case ARMISD::VSHL: return "ARMISD::VSHL";
950 case ARMISD::VSHRs: return "ARMISD::VSHRs";
951 case ARMISD::VSHRu: return "ARMISD::VSHRu";
952 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
953 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
954 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
955 case ARMISD::VSHRN: return "ARMISD::VSHRN";
956 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
957 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
958 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
959 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
960 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
961 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
962 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
963 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
964 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
965 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
966 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
967 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
968 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
969 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
970 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
971 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
972 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
973 case ARMISD::VDUP: return "ARMISD::VDUP";
974 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
975 case ARMISD::VEXT: return "ARMISD::VEXT";
976 case ARMISD::VREV64: return "ARMISD::VREV64";
977 case ARMISD::VREV32: return "ARMISD::VREV32";
978 case ARMISD::VREV16: return "ARMISD::VREV16";
979 case ARMISD::VZIP: return "ARMISD::VZIP";
980 case ARMISD::VUZP: return "ARMISD::VUZP";
981 case ARMISD::VTRN: return "ARMISD::VTRN";
982 case ARMISD::VTBL1: return "ARMISD::VTBL1";
983 case ARMISD::VTBL2: return "ARMISD::VTBL2";
984 case ARMISD::VMULLs: return "ARMISD::VMULLs";
985 case ARMISD::VMULLu: return "ARMISD::VMULLu";
986 case ARMISD::UMLAL: return "ARMISD::UMLAL";
987 case ARMISD::SMLAL: return "ARMISD::SMLAL";
988 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
989 case ARMISD::FMAX: return "ARMISD::FMAX";
990 case ARMISD::FMIN: return "ARMISD::FMIN";
991 case ARMISD::BFI: return "ARMISD::BFI";
992 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
993 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
994 case ARMISD::VBSL: return "ARMISD::VBSL";
995 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
996 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
997 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
998 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
999 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1000 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1001 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1002 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1003 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1004 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1005 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1006 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1007 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1008 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1009 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1010 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1011 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1012 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1013 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1014 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1018 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1019 if (!VT.isVector()) return getPointerTy();
1020 return VT.changeVectorElementTypeToInteger();
1023 /// getRegClassFor - Return the register class that should be used for the
1024 /// specified value type.
1025 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1026 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1027 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1028 // load / store 4 to 8 consecutive D registers.
1029 if (Subtarget->hasNEON()) {
1030 if (VT == MVT::v4i64)
1031 return &ARM::QQPRRegClass;
1032 if (VT == MVT::v8i64)
1033 return &ARM::QQQQPRRegClass;
1035 return TargetLowering::getRegClassFor(VT);
1038 // Create a fast isel object.
1040 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1041 const TargetLibraryInfo *libInfo) const {
1042 return ARM::createFastISel(funcInfo, libInfo);
1045 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1046 /// be used for loads / stores from the global.
1047 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1048 return (Subtarget->isThumb1Only() ? 127 : 4095);
1051 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1052 unsigned NumVals = N->getNumValues();
1054 return Sched::RegPressure;
1056 for (unsigned i = 0; i != NumVals; ++i) {
1057 EVT VT = N->getValueType(i);
1058 if (VT == MVT::Glue || VT == MVT::Other)
1060 if (VT.isFloatingPoint() || VT.isVector())
1064 if (!N->isMachineOpcode())
1065 return Sched::RegPressure;
1067 // Load are scheduled for latency even if there instruction itinerary
1068 // is not available.
1069 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1070 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1072 if (MCID.getNumDefs() == 0)
1073 return Sched::RegPressure;
1074 if (!Itins->isEmpty() &&
1075 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1078 return Sched::RegPressure;
1081 //===----------------------------------------------------------------------===//
1083 //===----------------------------------------------------------------------===//
1085 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1086 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1088 default: llvm_unreachable("Unknown condition code!");
1089 case ISD::SETNE: return ARMCC::NE;
1090 case ISD::SETEQ: return ARMCC::EQ;
1091 case ISD::SETGT: return ARMCC::GT;
1092 case ISD::SETGE: return ARMCC::GE;
1093 case ISD::SETLT: return ARMCC::LT;
1094 case ISD::SETLE: return ARMCC::LE;
1095 case ISD::SETUGT: return ARMCC::HI;
1096 case ISD::SETUGE: return ARMCC::HS;
1097 case ISD::SETULT: return ARMCC::LO;
1098 case ISD::SETULE: return ARMCC::LS;
1102 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1103 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1104 ARMCC::CondCodes &CondCode2) {
1105 CondCode2 = ARMCC::AL;
1107 default: llvm_unreachable("Unknown FP condition!");
1109 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1111 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1113 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1114 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1115 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1116 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1117 case ISD::SETO: CondCode = ARMCC::VC; break;
1118 case ISD::SETUO: CondCode = ARMCC::VS; break;
1119 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1120 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1121 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1123 case ISD::SETULT: CondCode = ARMCC::LT; break;
1125 case ISD::SETULE: CondCode = ARMCC::LE; break;
1127 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1131 //===----------------------------------------------------------------------===//
1132 // Calling Convention Implementation
1133 //===----------------------------------------------------------------------===//
1135 #include "ARMGenCallingConv.inc"
1137 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1138 /// given CallingConvention value.
1139 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1141 bool isVarArg) const {
1144 llvm_unreachable("Unsupported calling convention");
1145 case CallingConv::Fast:
1146 if (Subtarget->hasVFP2() && !isVarArg) {
1147 if (!Subtarget->isAAPCS_ABI())
1148 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1149 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1150 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1153 case CallingConv::C: {
1154 // Use target triple & subtarget features to do actual dispatch.
1155 if (!Subtarget->isAAPCS_ABI())
1156 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1157 else if (Subtarget->hasVFP2() &&
1158 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1160 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1161 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1163 case CallingConv::ARM_AAPCS_VFP:
1165 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1167 case CallingConv::ARM_AAPCS:
1168 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1169 case CallingConv::ARM_APCS:
1170 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1171 case CallingConv::GHC:
1172 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1176 /// LowerCallResult - Lower the result values of a call into the
1177 /// appropriate copies out of appropriate physical registers.
1179 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1180 CallingConv::ID CallConv, bool isVarArg,
1181 const SmallVectorImpl<ISD::InputArg> &Ins,
1182 DebugLoc dl, SelectionDAG &DAG,
1183 SmallVectorImpl<SDValue> &InVals) const {
1185 // Assign locations to each value returned by this call.
1186 SmallVector<CCValAssign, 16> RVLocs;
1187 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1188 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1189 CCInfo.AnalyzeCallResult(Ins,
1190 CCAssignFnForNode(CallConv, /* Return*/ true,
1193 // Copy all of the result registers out of their specified physreg.
1194 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1195 CCValAssign VA = RVLocs[i];
1198 if (VA.needsCustom()) {
1199 // Handle f64 or half of a v2f64.
1200 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1202 Chain = Lo.getValue(1);
1203 InFlag = Lo.getValue(2);
1204 VA = RVLocs[++i]; // skip ahead to next loc
1205 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1207 Chain = Hi.getValue(1);
1208 InFlag = Hi.getValue(2);
1209 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1211 if (VA.getLocVT() == MVT::v2f64) {
1212 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1213 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1214 DAG.getConstant(0, MVT::i32));
1216 VA = RVLocs[++i]; // skip ahead to next loc
1217 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1218 Chain = Lo.getValue(1);
1219 InFlag = Lo.getValue(2);
1220 VA = RVLocs[++i]; // skip ahead to next loc
1221 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1222 Chain = Hi.getValue(1);
1223 InFlag = Hi.getValue(2);
1224 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1225 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1226 DAG.getConstant(1, MVT::i32));
1229 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1231 Chain = Val.getValue(1);
1232 InFlag = Val.getValue(2);
1235 switch (VA.getLocInfo()) {
1236 default: llvm_unreachable("Unknown loc info!");
1237 case CCValAssign::Full: break;
1238 case CCValAssign::BCvt:
1239 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1243 InVals.push_back(Val);
1249 /// LowerMemOpCallTo - Store the argument to the stack.
1251 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1252 SDValue StackPtr, SDValue Arg,
1253 DebugLoc dl, SelectionDAG &DAG,
1254 const CCValAssign &VA,
1255 ISD::ArgFlagsTy Flags) const {
1256 unsigned LocMemOffset = VA.getLocMemOffset();
1257 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1258 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1259 return DAG.getStore(Chain, dl, Arg, PtrOff,
1260 MachinePointerInfo::getStack(LocMemOffset),
1264 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1265 SDValue Chain, SDValue &Arg,
1266 RegsToPassVector &RegsToPass,
1267 CCValAssign &VA, CCValAssign &NextVA,
1269 SmallVector<SDValue, 8> &MemOpChains,
1270 ISD::ArgFlagsTy Flags) const {
1272 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1273 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1274 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1276 if (NextVA.isRegLoc())
1277 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1279 assert(NextVA.isMemLoc());
1280 if (StackPtr.getNode() == 0)
1281 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1283 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1289 /// LowerCall - Lowering a call into a callseq_start <-
1290 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1293 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1294 SmallVectorImpl<SDValue> &InVals) const {
1295 SelectionDAG &DAG = CLI.DAG;
1296 DebugLoc &dl = CLI.DL;
1297 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1298 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1299 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1300 SDValue Chain = CLI.Chain;
1301 SDValue Callee = CLI.Callee;
1302 bool &isTailCall = CLI.IsTailCall;
1303 CallingConv::ID CallConv = CLI.CallConv;
1304 bool doesNotRet = CLI.DoesNotReturn;
1305 bool isVarArg = CLI.IsVarArg;
1307 MachineFunction &MF = DAG.getMachineFunction();
1308 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1309 bool IsSibCall = false;
1310 // Disable tail calls if they're not supported.
1311 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1314 // Check if it's really possible to do a tail call.
1315 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1316 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1317 Outs, OutVals, Ins, DAG);
1318 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1319 // detected sibcalls.
1326 // Analyze operands of the call, assigning locations to each operand.
1327 SmallVector<CCValAssign, 16> ArgLocs;
1328 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1329 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1330 CCInfo.AnalyzeCallOperands(Outs,
1331 CCAssignFnForNode(CallConv, /* Return*/ false,
1334 // Get a count of how many bytes are to be pushed on the stack.
1335 unsigned NumBytes = CCInfo.getNextStackOffset();
1337 // For tail calls, memory operands are available in our caller's stack.
1341 // Adjust the stack pointer for the new arguments...
1342 // These operations are automatically eliminated by the prolog/epilog pass
1344 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1346 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1348 RegsToPassVector RegsToPass;
1349 SmallVector<SDValue, 8> MemOpChains;
1351 // Walk the register/memloc assignments, inserting copies/loads. In the case
1352 // of tail call optimization, arguments are handled later.
1353 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1355 ++i, ++realArgIdx) {
1356 CCValAssign &VA = ArgLocs[i];
1357 SDValue Arg = OutVals[realArgIdx];
1358 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1359 bool isByVal = Flags.isByVal();
1361 // Promote the value if needed.
1362 switch (VA.getLocInfo()) {
1363 default: llvm_unreachable("Unknown loc info!");
1364 case CCValAssign::Full: break;
1365 case CCValAssign::SExt:
1366 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1368 case CCValAssign::ZExt:
1369 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1371 case CCValAssign::AExt:
1372 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1374 case CCValAssign::BCvt:
1375 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1379 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1380 if (VA.needsCustom()) {
1381 if (VA.getLocVT() == MVT::v2f64) {
1382 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1383 DAG.getConstant(0, MVT::i32));
1384 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1385 DAG.getConstant(1, MVT::i32));
1387 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1388 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1390 VA = ArgLocs[++i]; // skip ahead to next loc
1391 if (VA.isRegLoc()) {
1392 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1393 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1395 assert(VA.isMemLoc());
1397 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1398 dl, DAG, VA, Flags));
1401 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1402 StackPtr, MemOpChains, Flags);
1404 } else if (VA.isRegLoc()) {
1405 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1406 } else if (isByVal) {
1407 assert(VA.isMemLoc());
1408 unsigned offset = 0;
1410 // True if this byval aggregate will be split between registers
1412 if (CCInfo.isFirstByValRegValid()) {
1413 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1415 for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1416 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1417 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1418 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1419 MachinePointerInfo(),
1420 false, false, false, 0);
1421 MemOpChains.push_back(Load.getValue(1));
1422 RegsToPass.push_back(std::make_pair(j, Load));
1424 offset = ARM::R4 - CCInfo.getFirstByValReg();
1425 CCInfo.clearFirstByValReg();
1428 if (Flags.getByValSize() - 4*offset > 0) {
1429 unsigned LocMemOffset = VA.getLocMemOffset();
1430 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1431 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1433 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1434 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1435 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1437 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1439 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1440 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1441 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1442 Ops, array_lengthof(Ops)));
1444 } else if (!IsSibCall) {
1445 assert(VA.isMemLoc());
1447 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1448 dl, DAG, VA, Flags));
1452 if (!MemOpChains.empty())
1453 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1454 &MemOpChains[0], MemOpChains.size());
1456 // Build a sequence of copy-to-reg nodes chained together with token chain
1457 // and flag operands which copy the outgoing args into the appropriate regs.
1459 // Tail call byval lowering might overwrite argument registers so in case of
1460 // tail call optimization the copies to registers are lowered later.
1462 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1463 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1464 RegsToPass[i].second, InFlag);
1465 InFlag = Chain.getValue(1);
1468 // For tail calls lower the arguments to the 'real' stack slot.
1470 // Force all the incoming stack arguments to be loaded from the stack
1471 // before any new outgoing arguments are stored to the stack, because the
1472 // outgoing stack slots may alias the incoming argument stack slots, and
1473 // the alias isn't otherwise explicit. This is slightly more conservative
1474 // than necessary, because it means that each store effectively depends
1475 // on every argument instead of just those arguments it would clobber.
1477 // Do not flag preceding copytoreg stuff together with the following stuff.
1479 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1480 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1481 RegsToPass[i].second, InFlag);
1482 InFlag = Chain.getValue(1);
1487 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1488 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1489 // node so that legalize doesn't hack it.
1490 bool isDirect = false;
1491 bool isARMFunc = false;
1492 bool isLocalARMFunc = false;
1493 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1495 if (EnableARMLongCalls) {
1496 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1497 && "long-calls with non-static relocation model!");
1498 // Handle a global address or an external symbol. If it's not one of
1499 // those, the target's already in a register, so we don't need to do
1501 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1502 const GlobalValue *GV = G->getGlobal();
1503 // Create a constant pool entry for the callee address
1504 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1505 ARMConstantPoolValue *CPV =
1506 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1508 // Get the address of the callee into a register
1509 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1510 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1511 Callee = DAG.getLoad(getPointerTy(), dl,
1512 DAG.getEntryNode(), CPAddr,
1513 MachinePointerInfo::getConstantPool(),
1514 false, false, false, 0);
1515 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1516 const char *Sym = S->getSymbol();
1518 // Create a constant pool entry for the callee address
1519 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1520 ARMConstantPoolValue *CPV =
1521 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1522 ARMPCLabelIndex, 0);
1523 // Get the address of the callee into a register
1524 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1525 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1526 Callee = DAG.getLoad(getPointerTy(), dl,
1527 DAG.getEntryNode(), CPAddr,
1528 MachinePointerInfo::getConstantPool(),
1529 false, false, false, 0);
1531 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1532 const GlobalValue *GV = G->getGlobal();
1534 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1535 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1536 getTargetMachine().getRelocationModel() != Reloc::Static;
1537 isARMFunc = !Subtarget->isThumb() || isStub;
1538 // ARM call to a local ARM function is predicable.
1539 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1540 // tBX takes a register source operand.
1541 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1542 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1543 ARMConstantPoolValue *CPV =
1544 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1545 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1546 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1547 Callee = DAG.getLoad(getPointerTy(), dl,
1548 DAG.getEntryNode(), CPAddr,
1549 MachinePointerInfo::getConstantPool(),
1550 false, false, false, 0);
1551 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1552 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1553 getPointerTy(), Callee, PICLabel);
1555 // On ELF targets for PIC code, direct calls should go through the PLT
1556 unsigned OpFlags = 0;
1557 if (Subtarget->isTargetELF() &&
1558 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1559 OpFlags = ARMII::MO_PLT;
1560 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1562 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1564 bool isStub = Subtarget->isTargetDarwin() &&
1565 getTargetMachine().getRelocationModel() != Reloc::Static;
1566 isARMFunc = !Subtarget->isThumb() || isStub;
1567 // tBX takes a register source operand.
1568 const char *Sym = S->getSymbol();
1569 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1570 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1571 ARMConstantPoolValue *CPV =
1572 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1573 ARMPCLabelIndex, 4);
1574 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1575 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1576 Callee = DAG.getLoad(getPointerTy(), dl,
1577 DAG.getEntryNode(), CPAddr,
1578 MachinePointerInfo::getConstantPool(),
1579 false, false, false, 0);
1580 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1581 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1582 getPointerTy(), Callee, PICLabel);
1584 unsigned OpFlags = 0;
1585 // On ELF targets for PIC code, direct calls should go through the PLT
1586 if (Subtarget->isTargetELF() &&
1587 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1588 OpFlags = ARMII::MO_PLT;
1589 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1593 // FIXME: handle tail calls differently.
1595 if (Subtarget->isThumb()) {
1596 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1597 CallOpc = ARMISD::CALL_NOLINK;
1598 else if (doesNotRet && isDirect && !isARMFunc &&
1599 Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1600 // "mov lr, pc; b _foo" to avoid confusing the RSP
1601 CallOpc = ARMISD::CALL_NOLINK;
1603 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1605 if (!isDirect && !Subtarget->hasV5TOps()) {
1606 CallOpc = ARMISD::CALL_NOLINK;
1607 } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1608 // "mov lr, pc; b _foo" to avoid confusing the RSP
1609 CallOpc = ARMISD::CALL_NOLINK;
1611 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1614 std::vector<SDValue> Ops;
1615 Ops.push_back(Chain);
1616 Ops.push_back(Callee);
1618 // Add argument registers to the end of the list so that they are known live
1620 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1621 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1622 RegsToPass[i].second.getValueType()));
1624 // Add a register mask operand representing the call-preserved registers.
1625 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1626 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1627 assert(Mask && "Missing call preserved mask for calling convention");
1628 Ops.push_back(DAG.getRegisterMask(Mask));
1630 if (InFlag.getNode())
1631 Ops.push_back(InFlag);
1633 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1635 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1637 // Returns a chain and a flag for retval copy to use.
1638 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1639 InFlag = Chain.getValue(1);
1641 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1642 DAG.getIntPtrConstant(0, true), InFlag);
1644 InFlag = Chain.getValue(1);
1646 // Handle result values, copying them out of physregs into vregs that we
1648 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1652 /// HandleByVal - Every parameter *after* a byval parameter is passed
1653 /// on the stack. Remember the next parameter register to allocate,
1654 /// and then confiscate the rest of the parameter registers to insure
1657 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1658 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1659 assert((State->getCallOrPrologue() == Prologue ||
1660 State->getCallOrPrologue() == Call) &&
1661 "unhandled ParmContext");
1662 if ((!State->isFirstByValRegValid()) &&
1663 (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1664 State->setFirstByValReg(reg);
1665 // At a call site, a byval parameter that is split between
1666 // registers and memory needs its size truncated here. In a
1667 // function prologue, such byval parameters are reassembled in
1668 // memory, and are not truncated.
1669 if (State->getCallOrPrologue() == Call) {
1670 unsigned excess = 4 * (ARM::R4 - reg);
1671 assert(size >= excess && "expected larger existing stack allocation");
1675 // Confiscate any remaining parameter registers to preclude their
1676 // assignment to subsequent parameters.
1677 while (State->AllocateReg(GPRArgRegs, 4))
1681 /// MatchingStackOffset - Return true if the given stack call argument is
1682 /// already available in the same position (relatively) of the caller's
1683 /// incoming argument stack.
1685 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1686 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1687 const TargetInstrInfo *TII) {
1688 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1690 if (Arg.getOpcode() == ISD::CopyFromReg) {
1691 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1692 if (!TargetRegisterInfo::isVirtualRegister(VR))
1694 MachineInstr *Def = MRI->getVRegDef(VR);
1697 if (!Flags.isByVal()) {
1698 if (!TII->isLoadFromStackSlot(Def, FI))
1703 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1704 if (Flags.isByVal())
1705 // ByVal argument is passed in as a pointer but it's now being
1706 // dereferenced. e.g.
1707 // define @foo(%struct.X* %A) {
1708 // tail call @bar(%struct.X* byval %A)
1711 SDValue Ptr = Ld->getBasePtr();
1712 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1715 FI = FINode->getIndex();
1719 assert(FI != INT_MAX);
1720 if (!MFI->isFixedObjectIndex(FI))
1722 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1725 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1726 /// for tail call optimization. Targets which want to do tail call
1727 /// optimization should implement this function.
1729 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1730 CallingConv::ID CalleeCC,
1732 bool isCalleeStructRet,
1733 bool isCallerStructRet,
1734 const SmallVectorImpl<ISD::OutputArg> &Outs,
1735 const SmallVectorImpl<SDValue> &OutVals,
1736 const SmallVectorImpl<ISD::InputArg> &Ins,
1737 SelectionDAG& DAG) const {
1738 const Function *CallerF = DAG.getMachineFunction().getFunction();
1739 CallingConv::ID CallerCC = CallerF->getCallingConv();
1740 bool CCMatch = CallerCC == CalleeCC;
1742 // Look for obvious safe cases to perform tail call optimization that do not
1743 // require ABI changes. This is what gcc calls sibcall.
1745 // Do not sibcall optimize vararg calls unless the call site is not passing
1747 if (isVarArg && !Outs.empty())
1750 // Also avoid sibcall optimization if either caller or callee uses struct
1751 // return semantics.
1752 if (isCalleeStructRet || isCallerStructRet)
1755 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1756 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1757 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1758 // support in the assembler and linker to be used. This would need to be
1759 // fixed to fully support tail calls in Thumb1.
1761 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1762 // LR. This means if we need to reload LR, it takes an extra instructions,
1763 // which outweighs the value of the tail call; but here we don't know yet
1764 // whether LR is going to be used. Probably the right approach is to
1765 // generate the tail call here and turn it back into CALL/RET in
1766 // emitEpilogue if LR is used.
1768 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1769 // but we need to make sure there are enough registers; the only valid
1770 // registers are the 4 used for parameters. We don't currently do this
1772 if (Subtarget->isThumb1Only())
1775 // If the calling conventions do not match, then we'd better make sure the
1776 // results are returned in the same way as what the caller expects.
1778 SmallVector<CCValAssign, 16> RVLocs1;
1779 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1780 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1781 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1783 SmallVector<CCValAssign, 16> RVLocs2;
1784 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1785 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1786 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1788 if (RVLocs1.size() != RVLocs2.size())
1790 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1791 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1793 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1795 if (RVLocs1[i].isRegLoc()) {
1796 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1799 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1805 // If the callee takes no arguments then go on to check the results of the
1807 if (!Outs.empty()) {
1808 // Check if stack adjustment is needed. For now, do not do this if any
1809 // argument is passed on the stack.
1810 SmallVector<CCValAssign, 16> ArgLocs;
1811 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1812 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1813 CCInfo.AnalyzeCallOperands(Outs,
1814 CCAssignFnForNode(CalleeCC, false, isVarArg));
1815 if (CCInfo.getNextStackOffset()) {
1816 MachineFunction &MF = DAG.getMachineFunction();
1818 // Check if the arguments are already laid out in the right way as
1819 // the caller's fixed stack objects.
1820 MachineFrameInfo *MFI = MF.getFrameInfo();
1821 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1822 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1823 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1825 ++i, ++realArgIdx) {
1826 CCValAssign &VA = ArgLocs[i];
1827 EVT RegVT = VA.getLocVT();
1828 SDValue Arg = OutVals[realArgIdx];
1829 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1830 if (VA.getLocInfo() == CCValAssign::Indirect)
1832 if (VA.needsCustom()) {
1833 // f64 and vector types are split into multiple registers or
1834 // register/stack-slot combinations. The types will not match
1835 // the registers; give up on memory f64 refs until we figure
1836 // out what to do about this.
1839 if (!ArgLocs[++i].isRegLoc())
1841 if (RegVT == MVT::v2f64) {
1842 if (!ArgLocs[++i].isRegLoc())
1844 if (!ArgLocs[++i].isRegLoc())
1847 } else if (!VA.isRegLoc()) {
1848 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1860 ARMTargetLowering::LowerReturn(SDValue Chain,
1861 CallingConv::ID CallConv, bool isVarArg,
1862 const SmallVectorImpl<ISD::OutputArg> &Outs,
1863 const SmallVectorImpl<SDValue> &OutVals,
1864 DebugLoc dl, SelectionDAG &DAG) const {
1866 // CCValAssign - represent the assignment of the return value to a location.
1867 SmallVector<CCValAssign, 16> RVLocs;
1869 // CCState - Info about the registers and stack slots.
1870 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1871 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1873 // Analyze outgoing return values.
1874 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1877 // If this is the first return lowered for this function, add
1878 // the regs to the liveout set for the function.
1879 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1880 for (unsigned i = 0; i != RVLocs.size(); ++i)
1881 if (RVLocs[i].isRegLoc())
1882 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1887 // Copy the result values into the output registers.
1888 for (unsigned i = 0, realRVLocIdx = 0;
1890 ++i, ++realRVLocIdx) {
1891 CCValAssign &VA = RVLocs[i];
1892 assert(VA.isRegLoc() && "Can only return in registers!");
1894 SDValue Arg = OutVals[realRVLocIdx];
1896 switch (VA.getLocInfo()) {
1897 default: llvm_unreachable("Unknown loc info!");
1898 case CCValAssign::Full: break;
1899 case CCValAssign::BCvt:
1900 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1904 if (VA.needsCustom()) {
1905 if (VA.getLocVT() == MVT::v2f64) {
1906 // Extract the first half and return it in two registers.
1907 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1908 DAG.getConstant(0, MVT::i32));
1909 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1910 DAG.getVTList(MVT::i32, MVT::i32), Half);
1912 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1913 Flag = Chain.getValue(1);
1914 VA = RVLocs[++i]; // skip ahead to next loc
1915 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1916 HalfGPRs.getValue(1), Flag);
1917 Flag = Chain.getValue(1);
1918 VA = RVLocs[++i]; // skip ahead to next loc
1920 // Extract the 2nd half and fall through to handle it as an f64 value.
1921 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1922 DAG.getConstant(1, MVT::i32));
1924 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1926 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1927 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1928 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1929 Flag = Chain.getValue(1);
1930 VA = RVLocs[++i]; // skip ahead to next loc
1931 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1934 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1936 // Guarantee that all emitted copies are
1937 // stuck together, avoiding something bad.
1938 Flag = Chain.getValue(1);
1943 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1945 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1950 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1951 if (N->getNumValues() != 1)
1953 if (!N->hasNUsesOfValue(1, 0))
1956 SDValue TCChain = Chain;
1957 SDNode *Copy = *N->use_begin();
1958 if (Copy->getOpcode() == ISD::CopyToReg) {
1959 // If the copy has a glue operand, we conservatively assume it isn't safe to
1960 // perform a tail call.
1961 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1963 TCChain = Copy->getOperand(0);
1964 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1965 SDNode *VMov = Copy;
1966 // f64 returned in a pair of GPRs.
1967 SmallPtrSet<SDNode*, 2> Copies;
1968 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1970 if (UI->getOpcode() != ISD::CopyToReg)
1974 if (Copies.size() > 2)
1977 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1979 SDValue UseChain = UI->getOperand(0);
1980 if (Copies.count(UseChain.getNode()))
1987 } else if (Copy->getOpcode() == ISD::BITCAST) {
1988 // f32 returned in a single GPR.
1989 if (!Copy->hasOneUse())
1991 Copy = *Copy->use_begin();
1992 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
1994 Chain = Copy->getOperand(0);
1999 bool HasRet = false;
2000 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2002 if (UI->getOpcode() != ARMISD::RET_FLAG)
2014 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2015 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2018 if (!CI->isTailCall())
2021 return !Subtarget->isThumb1Only();
2024 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2025 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2026 // one of the above mentioned nodes. It has to be wrapped because otherwise
2027 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2028 // be used to form addressing mode. These wrapped nodes will be selected
2030 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2031 EVT PtrVT = Op.getValueType();
2032 // FIXME there is no actual debug info here
2033 DebugLoc dl = Op.getDebugLoc();
2034 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2036 if (CP->isMachineConstantPoolEntry())
2037 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2038 CP->getAlignment());
2040 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2041 CP->getAlignment());
2042 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2045 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2046 return MachineJumpTableInfo::EK_Inline;
2049 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2050 SelectionDAG &DAG) const {
2051 MachineFunction &MF = DAG.getMachineFunction();
2052 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2053 unsigned ARMPCLabelIndex = 0;
2054 DebugLoc DL = Op.getDebugLoc();
2055 EVT PtrVT = getPointerTy();
2056 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2057 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2059 if (RelocM == Reloc::Static) {
2060 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2062 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2063 ARMPCLabelIndex = AFI->createPICLabelUId();
2064 ARMConstantPoolValue *CPV =
2065 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2066 ARMCP::CPBlockAddress, PCAdj);
2067 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2069 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2070 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2071 MachinePointerInfo::getConstantPool(),
2072 false, false, false, 0);
2073 if (RelocM == Reloc::Static)
2075 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2076 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2079 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2081 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2082 SelectionDAG &DAG) const {
2083 DebugLoc dl = GA->getDebugLoc();
2084 EVT PtrVT = getPointerTy();
2085 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2086 MachineFunction &MF = DAG.getMachineFunction();
2087 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2088 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2089 ARMConstantPoolValue *CPV =
2090 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2091 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2092 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2093 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2094 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2095 MachinePointerInfo::getConstantPool(),
2096 false, false, false, 0);
2097 SDValue Chain = Argument.getValue(1);
2099 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2100 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2102 // call __tls_get_addr.
2105 Entry.Node = Argument;
2106 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2107 Args.push_back(Entry);
2108 // FIXME: is there useful debug info available here?
2109 TargetLowering::CallLoweringInfo CLI(Chain,
2110 (Type *) Type::getInt32Ty(*DAG.getContext()),
2111 false, false, false, false,
2112 0, CallingConv::C, /*isTailCall=*/false,
2113 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2114 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2115 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2116 return CallResult.first;
2119 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2120 // "local exec" model.
2122 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2124 TLSModel::Model model) const {
2125 const GlobalValue *GV = GA->getGlobal();
2126 DebugLoc dl = GA->getDebugLoc();
2128 SDValue Chain = DAG.getEntryNode();
2129 EVT PtrVT = getPointerTy();
2130 // Get the Thread Pointer
2131 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2133 if (model == TLSModel::InitialExec) {
2134 MachineFunction &MF = DAG.getMachineFunction();
2135 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2136 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2137 // Initial exec model.
2138 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2139 ARMConstantPoolValue *CPV =
2140 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2141 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2143 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2144 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2145 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2146 MachinePointerInfo::getConstantPool(),
2147 false, false, false, 0);
2148 Chain = Offset.getValue(1);
2150 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2151 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2153 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2154 MachinePointerInfo::getConstantPool(),
2155 false, false, false, 0);
2158 assert(model == TLSModel::LocalExec);
2159 ARMConstantPoolValue *CPV =
2160 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2161 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2162 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2163 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2164 MachinePointerInfo::getConstantPool(),
2165 false, false, false, 0);
2168 // The address of the thread local variable is the add of the thread
2169 // pointer with the offset of the variable.
2170 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2174 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2175 // TODO: implement the "local dynamic" model
2176 assert(Subtarget->isTargetELF() &&
2177 "TLS not implemented for non-ELF targets");
2178 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2180 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2183 case TLSModel::GeneralDynamic:
2184 case TLSModel::LocalDynamic:
2185 return LowerToTLSGeneralDynamicModel(GA, DAG);
2186 case TLSModel::InitialExec:
2187 case TLSModel::LocalExec:
2188 return LowerToTLSExecModels(GA, DAG, model);
2190 llvm_unreachable("bogus TLS model");
2193 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2194 SelectionDAG &DAG) const {
2195 EVT PtrVT = getPointerTy();
2196 DebugLoc dl = Op.getDebugLoc();
2197 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2198 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2199 if (RelocM == Reloc::PIC_) {
2200 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2201 ARMConstantPoolValue *CPV =
2202 ARMConstantPoolConstant::Create(GV,
2203 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2204 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2205 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2206 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2208 MachinePointerInfo::getConstantPool(),
2209 false, false, false, 0);
2210 SDValue Chain = Result.getValue(1);
2211 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2212 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2214 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2215 MachinePointerInfo::getGOT(),
2216 false, false, false, 0);
2220 // If we have T2 ops, we can materialize the address directly via movt/movw
2221 // pair. This is always cheaper.
2222 if (Subtarget->useMovt()) {
2224 // FIXME: Once remat is capable of dealing with instructions with register
2225 // operands, expand this into two nodes.
2226 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2227 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2229 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2230 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2231 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2232 MachinePointerInfo::getConstantPool(),
2233 false, false, false, 0);
2237 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2238 SelectionDAG &DAG) const {
2239 EVT PtrVT = getPointerTy();
2240 DebugLoc dl = Op.getDebugLoc();
2241 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2242 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2243 MachineFunction &MF = DAG.getMachineFunction();
2244 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2246 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2247 // update ARMFastISel::ARMMaterializeGV.
2248 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2250 // FIXME: Once remat is capable of dealing with instructions with register
2251 // operands, expand this into two nodes.
2252 if (RelocM == Reloc::Static)
2253 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2254 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2256 unsigned Wrapper = (RelocM == Reloc::PIC_)
2257 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2258 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2259 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2260 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2261 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2262 MachinePointerInfo::getGOT(),
2263 false, false, false, 0);
2267 unsigned ARMPCLabelIndex = 0;
2269 if (RelocM == Reloc::Static) {
2270 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2272 ARMPCLabelIndex = AFI->createPICLabelUId();
2273 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2274 ARMConstantPoolValue *CPV =
2275 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2277 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2279 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2281 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2282 MachinePointerInfo::getConstantPool(),
2283 false, false, false, 0);
2284 SDValue Chain = Result.getValue(1);
2286 if (RelocM == Reloc::PIC_) {
2287 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2288 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2291 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2292 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2293 false, false, false, 0);
2298 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2299 SelectionDAG &DAG) const {
2300 assert(Subtarget->isTargetELF() &&
2301 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2302 MachineFunction &MF = DAG.getMachineFunction();
2303 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2304 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2305 EVT PtrVT = getPointerTy();
2306 DebugLoc dl = Op.getDebugLoc();
2307 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2308 ARMConstantPoolValue *CPV =
2309 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2310 ARMPCLabelIndex, PCAdj);
2311 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2312 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2313 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2314 MachinePointerInfo::getConstantPool(),
2315 false, false, false, 0);
2316 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2317 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2321 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2322 DebugLoc dl = Op.getDebugLoc();
2323 SDValue Val = DAG.getConstant(0, MVT::i32);
2324 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2325 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2326 Op.getOperand(1), Val);
2330 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2331 DebugLoc dl = Op.getDebugLoc();
2332 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2333 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2337 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2338 const ARMSubtarget *Subtarget) const {
2339 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2340 DebugLoc dl = Op.getDebugLoc();
2342 default: return SDValue(); // Don't custom lower most intrinsics.
2343 case Intrinsic::arm_thread_pointer: {
2344 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2345 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2347 case Intrinsic::eh_sjlj_lsda: {
2348 MachineFunction &MF = DAG.getMachineFunction();
2349 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2350 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2351 EVT PtrVT = getPointerTy();
2352 DebugLoc dl = Op.getDebugLoc();
2353 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2355 unsigned PCAdj = (RelocM != Reloc::PIC_)
2356 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2357 ARMConstantPoolValue *CPV =
2358 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2359 ARMCP::CPLSDA, PCAdj);
2360 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2361 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2363 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2364 MachinePointerInfo::getConstantPool(),
2365 false, false, false, 0);
2367 if (RelocM == Reloc::PIC_) {
2368 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2369 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2373 case Intrinsic::arm_neon_vmulls:
2374 case Intrinsic::arm_neon_vmullu: {
2375 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2376 ? ARMISD::VMULLs : ARMISD::VMULLu;
2377 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2378 Op.getOperand(1), Op.getOperand(2));
2383 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2384 const ARMSubtarget *Subtarget) {
2385 DebugLoc dl = Op.getDebugLoc();
2386 if (!Subtarget->hasDataBarrier()) {
2387 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2388 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2390 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2391 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2392 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2393 DAG.getConstant(0, MVT::i32));
2396 SDValue Op5 = Op.getOperand(5);
2397 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2398 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2399 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2400 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2402 ARM_MB::MemBOpt DMBOpt;
2403 if (isDeviceBarrier)
2404 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2406 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2407 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2408 DAG.getConstant(DMBOpt, MVT::i32));
2412 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2413 const ARMSubtarget *Subtarget) {
2414 // FIXME: handle "fence singlethread" more efficiently.
2415 DebugLoc dl = Op.getDebugLoc();
2416 if (!Subtarget->hasDataBarrier()) {
2417 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2418 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2420 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2421 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2422 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2423 DAG.getConstant(0, MVT::i32));
2426 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2427 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2430 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2431 const ARMSubtarget *Subtarget) {
2432 // ARM pre v5TE and Thumb1 does not have preload instructions.
2433 if (!(Subtarget->isThumb2() ||
2434 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2435 // Just preserve the chain.
2436 return Op.getOperand(0);
2438 DebugLoc dl = Op.getDebugLoc();
2439 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2441 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2442 // ARMv7 with MP extension has PLDW.
2443 return Op.getOperand(0);
2445 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2446 if (Subtarget->isThumb()) {
2448 isRead = ~isRead & 1;
2449 isData = ~isData & 1;
2452 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2453 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2454 DAG.getConstant(isData, MVT::i32));
2457 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2458 MachineFunction &MF = DAG.getMachineFunction();
2459 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2461 // vastart just stores the address of the VarArgsFrameIndex slot into the
2462 // memory location argument.
2463 DebugLoc dl = Op.getDebugLoc();
2464 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2465 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2466 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2467 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2468 MachinePointerInfo(SV), false, false, 0);
2472 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2473 SDValue &Root, SelectionDAG &DAG,
2474 DebugLoc dl) const {
2475 MachineFunction &MF = DAG.getMachineFunction();
2476 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2478 const TargetRegisterClass *RC;
2479 if (AFI->isThumb1OnlyFunction())
2480 RC = &ARM::tGPRRegClass;
2482 RC = &ARM::GPRRegClass;
2484 // Transform the arguments stored in physical registers into virtual ones.
2485 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2486 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2489 if (NextVA.isMemLoc()) {
2490 MachineFrameInfo *MFI = MF.getFrameInfo();
2491 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2493 // Create load node to retrieve arguments from the stack.
2494 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2495 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2496 MachinePointerInfo::getFixedStack(FI),
2497 false, false, false, 0);
2499 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2500 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2503 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2507 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2508 unsigned &VARegSize, unsigned &VARegSaveSize)
2511 if (CCInfo.isFirstByValRegValid())
2512 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2514 unsigned int firstUnalloced;
2515 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2516 sizeof(GPRArgRegs) /
2517 sizeof(GPRArgRegs[0]));
2518 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2521 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2522 VARegSize = NumGPRs * 4;
2523 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2526 // The remaining GPRs hold either the beginning of variable-argument
2527 // data, or the beginning of an aggregate passed by value (usuall
2528 // byval). Either way, we allocate stack slots adjacent to the data
2529 // provided by our caller, and store the unallocated registers there.
2530 // If this is a variadic function, the va_list pointer will begin with
2531 // these values; otherwise, this reassembles a (byval) structure that
2532 // was split between registers and memory.
2534 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2535 DebugLoc dl, SDValue &Chain,
2536 unsigned ArgOffset) const {
2537 MachineFunction &MF = DAG.getMachineFunction();
2538 MachineFrameInfo *MFI = MF.getFrameInfo();
2539 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2540 unsigned firstRegToSaveIndex;
2541 if (CCInfo.isFirstByValRegValid())
2542 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2544 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2545 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2548 unsigned VARegSize, VARegSaveSize;
2549 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2550 if (VARegSaveSize) {
2551 // If this function is vararg, store any remaining integer argument regs
2552 // to their spots on the stack so that they may be loaded by deferencing
2553 // the result of va_next.
2554 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2555 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2556 ArgOffset + VARegSaveSize
2559 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2562 SmallVector<SDValue, 4> MemOps;
2563 for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2564 const TargetRegisterClass *RC;
2565 if (AFI->isThumb1OnlyFunction())
2566 RC = &ARM::tGPRRegClass;
2568 RC = &ARM::GPRRegClass;
2570 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2571 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2573 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2574 MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2576 MemOps.push_back(Store);
2577 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2578 DAG.getConstant(4, getPointerTy()));
2580 if (!MemOps.empty())
2581 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2582 &MemOps[0], MemOps.size());
2584 // This will point to the next argument passed via stack.
2585 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2589 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2590 CallingConv::ID CallConv, bool isVarArg,
2591 const SmallVectorImpl<ISD::InputArg>
2593 DebugLoc dl, SelectionDAG &DAG,
2594 SmallVectorImpl<SDValue> &InVals)
2596 MachineFunction &MF = DAG.getMachineFunction();
2597 MachineFrameInfo *MFI = MF.getFrameInfo();
2599 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2601 // Assign locations to all of the incoming arguments.
2602 SmallVector<CCValAssign, 16> ArgLocs;
2603 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2604 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2605 CCInfo.AnalyzeFormalArguments(Ins,
2606 CCAssignFnForNode(CallConv, /* Return*/ false,
2609 SmallVector<SDValue, 16> ArgValues;
2610 int lastInsIndex = -1;
2613 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2614 CCValAssign &VA = ArgLocs[i];
2616 // Arguments stored in registers.
2617 if (VA.isRegLoc()) {
2618 EVT RegVT = VA.getLocVT();
2620 if (VA.needsCustom()) {
2621 // f64 and vector types are split up into multiple registers or
2622 // combinations of registers and stack slots.
2623 if (VA.getLocVT() == MVT::v2f64) {
2624 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2626 VA = ArgLocs[++i]; // skip ahead to next loc
2628 if (VA.isMemLoc()) {
2629 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2630 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2631 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2632 MachinePointerInfo::getFixedStack(FI),
2633 false, false, false, 0);
2635 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2638 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2639 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2640 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2641 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2642 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2644 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2647 const TargetRegisterClass *RC;
2649 if (RegVT == MVT::f32)
2650 RC = &ARM::SPRRegClass;
2651 else if (RegVT == MVT::f64)
2652 RC = &ARM::DPRRegClass;
2653 else if (RegVT == MVT::v2f64)
2654 RC = &ARM::QPRRegClass;
2655 else if (RegVT == MVT::i32)
2656 RC = AFI->isThumb1OnlyFunction() ?
2657 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2658 (const TargetRegisterClass*)&ARM::GPRRegClass;
2660 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2662 // Transform the arguments in physical registers into virtual ones.
2663 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2664 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2667 // If this is an 8 or 16-bit value, it is really passed promoted
2668 // to 32 bits. Insert an assert[sz]ext to capture this, then
2669 // truncate to the right size.
2670 switch (VA.getLocInfo()) {
2671 default: llvm_unreachable("Unknown loc info!");
2672 case CCValAssign::Full: break;
2673 case CCValAssign::BCvt:
2674 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2676 case CCValAssign::SExt:
2677 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2678 DAG.getValueType(VA.getValVT()));
2679 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2681 case CCValAssign::ZExt:
2682 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2683 DAG.getValueType(VA.getValVT()));
2684 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2688 InVals.push_back(ArgValue);
2690 } else { // VA.isRegLoc()
2693 assert(VA.isMemLoc());
2694 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2696 int index = ArgLocs[i].getValNo();
2698 // Some Ins[] entries become multiple ArgLoc[] entries.
2699 // Process them only once.
2700 if (index != lastInsIndex)
2702 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2703 // FIXME: For now, all byval parameter objects are marked mutable.
2704 // This can be changed with more analysis.
2705 // In case of tail call optimization mark all arguments mutable.
2706 // Since they could be overwritten by lowering of arguments in case of
2708 if (Flags.isByVal()) {
2709 unsigned VARegSize, VARegSaveSize;
2710 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2711 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2712 unsigned Bytes = Flags.getByValSize() - VARegSize;
2713 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2714 int FI = MFI->CreateFixedObject(Bytes,
2715 VA.getLocMemOffset(), false);
2716 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2718 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2719 VA.getLocMemOffset(), true);
2721 // Create load nodes to retrieve arguments from the stack.
2722 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2723 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2724 MachinePointerInfo::getFixedStack(FI),
2725 false, false, false, 0));
2727 lastInsIndex = index;
2734 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2739 /// isFloatingPointZero - Return true if this is +0.0.
2740 static bool isFloatingPointZero(SDValue Op) {
2741 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2742 return CFP->getValueAPF().isPosZero();
2743 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2744 // Maybe this has already been legalized into the constant pool?
2745 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2746 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2747 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2748 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2749 return CFP->getValueAPF().isPosZero();
2755 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2756 /// the given operands.
2758 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2759 SDValue &ARMcc, SelectionDAG &DAG,
2760 DebugLoc dl) const {
2761 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2762 unsigned C = RHSC->getZExtValue();
2763 if (!isLegalICmpImmediate(C)) {
2764 // Constant does not fit, try adjusting it by one?
2769 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2770 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2771 RHS = DAG.getConstant(C-1, MVT::i32);
2776 if (C != 0 && isLegalICmpImmediate(C-1)) {
2777 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2778 RHS = DAG.getConstant(C-1, MVT::i32);
2783 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2784 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2785 RHS = DAG.getConstant(C+1, MVT::i32);
2790 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2791 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2792 RHS = DAG.getConstant(C+1, MVT::i32);
2799 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2800 ARMISD::NodeType CompareType;
2803 CompareType = ARMISD::CMP;
2808 CompareType = ARMISD::CMPZ;
2811 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2812 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2815 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2817 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2818 DebugLoc dl) const {
2820 if (!isFloatingPointZero(RHS))
2821 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2823 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2824 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2827 /// duplicateCmp - Glue values can have only one use, so this function
2828 /// duplicates a comparison node.
2830 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2831 unsigned Opc = Cmp.getOpcode();
2832 DebugLoc DL = Cmp.getDebugLoc();
2833 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2834 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2836 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2837 Cmp = Cmp.getOperand(0);
2838 Opc = Cmp.getOpcode();
2839 if (Opc == ARMISD::CMPFP)
2840 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2842 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2843 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2845 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2848 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2849 SDValue Cond = Op.getOperand(0);
2850 SDValue SelectTrue = Op.getOperand(1);
2851 SDValue SelectFalse = Op.getOperand(2);
2852 DebugLoc dl = Op.getDebugLoc();
2856 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2857 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2859 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2860 const ConstantSDNode *CMOVTrue =
2861 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2862 const ConstantSDNode *CMOVFalse =
2863 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2865 if (CMOVTrue && CMOVFalse) {
2866 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2867 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2871 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2873 False = SelectFalse;
2874 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2879 if (True.getNode() && False.getNode()) {
2880 EVT VT = Op.getValueType();
2881 SDValue ARMcc = Cond.getOperand(2);
2882 SDValue CCR = Cond.getOperand(3);
2883 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2884 assert(True.getValueType() == VT);
2885 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2890 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2891 // undefined bits before doing a full-word comparison with zero.
2892 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2893 DAG.getConstant(1, Cond.getValueType()));
2895 return DAG.getSelectCC(dl, Cond,
2896 DAG.getConstant(0, Cond.getValueType()),
2897 SelectTrue, SelectFalse, ISD::SETNE);
2900 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2901 EVT VT = Op.getValueType();
2902 SDValue LHS = Op.getOperand(0);
2903 SDValue RHS = Op.getOperand(1);
2904 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2905 SDValue TrueVal = Op.getOperand(2);
2906 SDValue FalseVal = Op.getOperand(3);
2907 DebugLoc dl = Op.getDebugLoc();
2909 if (LHS.getValueType() == MVT::i32) {
2911 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2912 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2913 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2916 ARMCC::CondCodes CondCode, CondCode2;
2917 FPCCToARMCC(CC, CondCode, CondCode2);
2919 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2920 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2921 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2922 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2924 if (CondCode2 != ARMCC::AL) {
2925 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2926 // FIXME: Needs another CMP because flag can have but one use.
2927 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2928 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2929 Result, TrueVal, ARMcc2, CCR, Cmp2);
2934 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2935 /// to morph to an integer compare sequence.
2936 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2937 const ARMSubtarget *Subtarget) {
2938 SDNode *N = Op.getNode();
2939 if (!N->hasOneUse())
2940 // Otherwise it requires moving the value from fp to integer registers.
2942 if (!N->getNumValues())
2944 EVT VT = Op.getValueType();
2945 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2946 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2947 // vmrs are very slow, e.g. cortex-a8.
2950 if (isFloatingPointZero(Op)) {
2954 return ISD::isNormalLoad(N);
2957 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2958 if (isFloatingPointZero(Op))
2959 return DAG.getConstant(0, MVT::i32);
2961 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2962 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2963 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2964 Ld->isVolatile(), Ld->isNonTemporal(),
2965 Ld->isInvariant(), Ld->getAlignment());
2967 llvm_unreachable("Unknown VFP cmp argument!");
2970 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2971 SDValue &RetVal1, SDValue &RetVal2) {
2972 if (isFloatingPointZero(Op)) {
2973 RetVal1 = DAG.getConstant(0, MVT::i32);
2974 RetVal2 = DAG.getConstant(0, MVT::i32);
2978 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2979 SDValue Ptr = Ld->getBasePtr();
2980 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2981 Ld->getChain(), Ptr,
2982 Ld->getPointerInfo(),
2983 Ld->isVolatile(), Ld->isNonTemporal(),
2984 Ld->isInvariant(), Ld->getAlignment());
2986 EVT PtrType = Ptr.getValueType();
2987 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2988 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2989 PtrType, Ptr, DAG.getConstant(4, PtrType));
2990 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2991 Ld->getChain(), NewPtr,
2992 Ld->getPointerInfo().getWithOffset(4),
2993 Ld->isVolatile(), Ld->isNonTemporal(),
2994 Ld->isInvariant(), NewAlign);
2998 llvm_unreachable("Unknown VFP cmp argument!");
3001 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3002 /// f32 and even f64 comparisons to integer ones.
3004 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3005 SDValue Chain = Op.getOperand(0);
3006 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3007 SDValue LHS = Op.getOperand(2);
3008 SDValue RHS = Op.getOperand(3);
3009 SDValue Dest = Op.getOperand(4);
3010 DebugLoc dl = Op.getDebugLoc();
3012 bool LHSSeenZero = false;
3013 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3014 bool RHSSeenZero = false;
3015 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3016 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3017 // If unsafe fp math optimization is enabled and there are no other uses of
3018 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3019 // to an integer comparison.
3020 if (CC == ISD::SETOEQ)
3022 else if (CC == ISD::SETUNE)
3025 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3027 if (LHS.getValueType() == MVT::f32) {
3028 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3029 bitcastf32Toi32(LHS, DAG), Mask);
3030 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3031 bitcastf32Toi32(RHS, DAG), Mask);
3032 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3033 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3034 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3035 Chain, Dest, ARMcc, CCR, Cmp);
3040 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3041 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3042 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3043 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3044 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3045 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3046 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3047 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3048 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3054 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3055 SDValue Chain = Op.getOperand(0);
3056 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3057 SDValue LHS = Op.getOperand(2);
3058 SDValue RHS = Op.getOperand(3);
3059 SDValue Dest = Op.getOperand(4);
3060 DebugLoc dl = Op.getDebugLoc();
3062 if (LHS.getValueType() == MVT::i32) {
3064 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3065 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3066 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3067 Chain, Dest, ARMcc, CCR, Cmp);
3070 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3072 if (getTargetMachine().Options.UnsafeFPMath &&
3073 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3074 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3075 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3076 if (Result.getNode())
3080 ARMCC::CondCodes CondCode, CondCode2;
3081 FPCCToARMCC(CC, CondCode, CondCode2);
3083 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3084 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3085 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3086 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3087 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3088 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3089 if (CondCode2 != ARMCC::AL) {
3090 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3091 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3092 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3097 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3098 SDValue Chain = Op.getOperand(0);
3099 SDValue Table = Op.getOperand(1);
3100 SDValue Index = Op.getOperand(2);
3101 DebugLoc dl = Op.getDebugLoc();
3103 EVT PTy = getPointerTy();
3104 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3105 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3106 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3107 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3108 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3109 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3110 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3111 if (Subtarget->isThumb2()) {
3112 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3113 // which does another jump to the destination. This also makes it easier
3114 // to translate it to TBB / TBH later.
3115 // FIXME: This might not work if the function is extremely large.
3116 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3117 Addr, Op.getOperand(2), JTI, UId);
3119 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3120 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3121 MachinePointerInfo::getJumpTable(),
3122 false, false, false, 0);
3123 Chain = Addr.getValue(1);
3124 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3125 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3127 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3128 MachinePointerInfo::getJumpTable(),
3129 false, false, false, 0);
3130 Chain = Addr.getValue(1);
3131 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3135 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3136 EVT VT = Op.getValueType();
3137 DebugLoc dl = Op.getDebugLoc();
3139 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3140 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3142 return DAG.UnrollVectorOp(Op.getNode());
3145 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3146 "Invalid type for custom lowering!");
3147 if (VT != MVT::v4i16)
3148 return DAG.UnrollVectorOp(Op.getNode());
3150 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3151 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3154 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3155 EVT VT = Op.getValueType();
3157 return LowerVectorFP_TO_INT(Op, DAG);
3159 DebugLoc dl = Op.getDebugLoc();
3162 switch (Op.getOpcode()) {
3163 default: llvm_unreachable("Invalid opcode!");
3164 case ISD::FP_TO_SINT:
3165 Opc = ARMISD::FTOSI;
3167 case ISD::FP_TO_UINT:
3168 Opc = ARMISD::FTOUI;
3171 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3172 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3175 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3176 EVT VT = Op.getValueType();
3177 DebugLoc dl = Op.getDebugLoc();
3179 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3180 if (VT.getVectorElementType() == MVT::f32)
3182 return DAG.UnrollVectorOp(Op.getNode());
3185 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3186 "Invalid type for custom lowering!");
3187 if (VT != MVT::v4f32)
3188 return DAG.UnrollVectorOp(Op.getNode());
3192 switch (Op.getOpcode()) {
3193 default: llvm_unreachable("Invalid opcode!");
3194 case ISD::SINT_TO_FP:
3195 CastOpc = ISD::SIGN_EXTEND;
3196 Opc = ISD::SINT_TO_FP;
3198 case ISD::UINT_TO_FP:
3199 CastOpc = ISD::ZERO_EXTEND;
3200 Opc = ISD::UINT_TO_FP;
3204 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3205 return DAG.getNode(Opc, dl, VT, Op);
3208 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3209 EVT VT = Op.getValueType();
3211 return LowerVectorINT_TO_FP(Op, DAG);
3213 DebugLoc dl = Op.getDebugLoc();
3216 switch (Op.getOpcode()) {
3217 default: llvm_unreachable("Invalid opcode!");
3218 case ISD::SINT_TO_FP:
3219 Opc = ARMISD::SITOF;
3221 case ISD::UINT_TO_FP:
3222 Opc = ARMISD::UITOF;
3226 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3227 return DAG.getNode(Opc, dl, VT, Op);
3230 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3231 // Implement fcopysign with a fabs and a conditional fneg.
3232 SDValue Tmp0 = Op.getOperand(0);
3233 SDValue Tmp1 = Op.getOperand(1);
3234 DebugLoc dl = Op.getDebugLoc();
3235 EVT VT = Op.getValueType();
3236 EVT SrcVT = Tmp1.getValueType();
3237 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3238 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3239 bool UseNEON = !InGPR && Subtarget->hasNEON();
3242 // Use VBSL to copy the sign bit.
3243 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3244 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3245 DAG.getTargetConstant(EncodedVal, MVT::i32));
3246 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3248 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3249 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3250 DAG.getConstant(32, MVT::i32));
3251 else /*if (VT == MVT::f32)*/
3252 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3253 if (SrcVT == MVT::f32) {
3254 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3256 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3257 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3258 DAG.getConstant(32, MVT::i32));
3259 } else if (VT == MVT::f32)
3260 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3261 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3262 DAG.getConstant(32, MVT::i32));
3263 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3264 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3266 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3268 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3269 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3270 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3272 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3273 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3274 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3275 if (VT == MVT::f32) {
3276 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3277 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3278 DAG.getConstant(0, MVT::i32));
3280 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3286 // Bitcast operand 1 to i32.
3287 if (SrcVT == MVT::f64)
3288 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3289 &Tmp1, 1).getValue(1);
3290 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3292 // Or in the signbit with integer operations.
3293 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3294 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3295 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3296 if (VT == MVT::f32) {
3297 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3298 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3299 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3300 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3303 // f64: Or the high part with signbit and then combine two parts.
3304 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3306 SDValue Lo = Tmp0.getValue(0);
3307 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3308 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3309 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3312 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3313 MachineFunction &MF = DAG.getMachineFunction();
3314 MachineFrameInfo *MFI = MF.getFrameInfo();
3315 MFI->setReturnAddressIsTaken(true);
3317 EVT VT = Op.getValueType();
3318 DebugLoc dl = Op.getDebugLoc();
3319 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3321 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3322 SDValue Offset = DAG.getConstant(4, MVT::i32);
3323 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3324 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3325 MachinePointerInfo(), false, false, false, 0);
3328 // Return LR, which contains the return address. Mark it an implicit live-in.
3329 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3330 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3333 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3334 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3335 MFI->setFrameAddressIsTaken(true);
3337 EVT VT = Op.getValueType();
3338 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3339 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3340 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3341 ? ARM::R7 : ARM::R11;
3342 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3344 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3345 MachinePointerInfo(),
3346 false, false, false, 0);
3350 /// ExpandBITCAST - If the target supports VFP, this function is called to
3351 /// expand a bit convert where either the source or destination type is i64 to
3352 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3353 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3354 /// vectors), since the legalizer won't know what to do with that.
3355 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3356 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3357 DebugLoc dl = N->getDebugLoc();
3358 SDValue Op = N->getOperand(0);
3360 // This function is only supposed to be called for i64 types, either as the
3361 // source or destination of the bit convert.
3362 EVT SrcVT = Op.getValueType();
3363 EVT DstVT = N->getValueType(0);
3364 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3365 "ExpandBITCAST called for non-i64 type");
3367 // Turn i64->f64 into VMOVDRR.
3368 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3369 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3370 DAG.getConstant(0, MVT::i32));
3371 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3372 DAG.getConstant(1, MVT::i32));
3373 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3374 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3377 // Turn f64->i64 into VMOVRRD.
3378 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3379 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3380 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3381 // Merge the pieces into a single i64 value.
3382 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3388 /// getZeroVector - Returns a vector of specified type with all zero elements.
3389 /// Zero vectors are used to represent vector negation and in those cases
3390 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3391 /// not support i64 elements, so sometimes the zero vectors will need to be
3392 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3394 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3395 assert(VT.isVector() && "Expected a vector type");
3396 // The canonical modified immediate encoding of a zero vector is....0!
3397 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3398 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3399 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3400 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3403 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3404 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3405 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3406 SelectionDAG &DAG) const {
3407 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3408 EVT VT = Op.getValueType();
3409 unsigned VTBits = VT.getSizeInBits();
3410 DebugLoc dl = Op.getDebugLoc();
3411 SDValue ShOpLo = Op.getOperand(0);
3412 SDValue ShOpHi = Op.getOperand(1);
3413 SDValue ShAmt = Op.getOperand(2);
3415 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3417 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3419 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3420 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3421 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3422 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3423 DAG.getConstant(VTBits, MVT::i32));
3424 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3425 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3426 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3428 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3429 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3431 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3432 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3435 SDValue Ops[2] = { Lo, Hi };
3436 return DAG.getMergeValues(Ops, 2, dl);
3439 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3440 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3441 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3442 SelectionDAG &DAG) const {
3443 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3444 EVT VT = Op.getValueType();
3445 unsigned VTBits = VT.getSizeInBits();
3446 DebugLoc dl = Op.getDebugLoc();
3447 SDValue ShOpLo = Op.getOperand(0);
3448 SDValue ShOpHi = Op.getOperand(1);
3449 SDValue ShAmt = Op.getOperand(2);
3452 assert(Op.getOpcode() == ISD::SHL_PARTS);
3453 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3454 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3455 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3456 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3457 DAG.getConstant(VTBits, MVT::i32));
3458 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3459 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3461 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3462 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3463 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3465 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3466 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3469 SDValue Ops[2] = { Lo, Hi };
3470 return DAG.getMergeValues(Ops, 2, dl);
3473 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3474 SelectionDAG &DAG) const {
3475 // The rounding mode is in bits 23:22 of the FPSCR.
3476 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3477 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3478 // so that the shift + and get folded into a bitfield extract.
3479 DebugLoc dl = Op.getDebugLoc();
3480 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3481 DAG.getConstant(Intrinsic::arm_get_fpscr,
3483 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3484 DAG.getConstant(1U << 22, MVT::i32));
3485 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3486 DAG.getConstant(22, MVT::i32));
3487 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3488 DAG.getConstant(3, MVT::i32));
3491 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3492 const ARMSubtarget *ST) {
3493 EVT VT = N->getValueType(0);
3494 DebugLoc dl = N->getDebugLoc();
3496 if (!ST->hasV6T2Ops())
3499 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3500 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3503 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3504 const ARMSubtarget *ST) {
3505 EVT VT = N->getValueType(0);
3506 DebugLoc dl = N->getDebugLoc();
3511 // Lower vector shifts on NEON to use VSHL.
3512 assert(ST->hasNEON() && "unexpected vector shift");
3514 // Left shifts translate directly to the vshiftu intrinsic.
3515 if (N->getOpcode() == ISD::SHL)
3516 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3517 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3518 N->getOperand(0), N->getOperand(1));
3520 assert((N->getOpcode() == ISD::SRA ||
3521 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3523 // NEON uses the same intrinsics for both left and right shifts. For
3524 // right shifts, the shift amounts are negative, so negate the vector of
3526 EVT ShiftVT = N->getOperand(1).getValueType();
3527 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3528 getZeroVector(ShiftVT, DAG, dl),
3530 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3531 Intrinsic::arm_neon_vshifts :
3532 Intrinsic::arm_neon_vshiftu);
3533 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3534 DAG.getConstant(vshiftInt, MVT::i32),
3535 N->getOperand(0), NegatedCount);
3538 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3539 const ARMSubtarget *ST) {
3540 EVT VT = N->getValueType(0);
3541 DebugLoc dl = N->getDebugLoc();
3543 // We can get here for a node like i32 = ISD::SHL i32, i64
3547 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3548 "Unknown shift to lower!");
3550 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3551 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3552 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3555 // If we are in thumb mode, we don't have RRX.
3556 if (ST->isThumb1Only()) return SDValue();
3558 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3559 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3560 DAG.getConstant(0, MVT::i32));
3561 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3562 DAG.getConstant(1, MVT::i32));
3564 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3565 // captures the result into a carry flag.
3566 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3567 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3569 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3570 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3572 // Merge the pieces into a single i64 value.
3573 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3576 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3577 SDValue TmpOp0, TmpOp1;
3578 bool Invert = false;
3582 SDValue Op0 = Op.getOperand(0);
3583 SDValue Op1 = Op.getOperand(1);
3584 SDValue CC = Op.getOperand(2);
3585 EVT VT = Op.getValueType();
3586 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3587 DebugLoc dl = Op.getDebugLoc();
3589 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3590 switch (SetCCOpcode) {
3591 default: llvm_unreachable("Illegal FP comparison");
3593 case ISD::SETNE: Invert = true; // Fallthrough
3595 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3597 case ISD::SETLT: Swap = true; // Fallthrough
3599 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3601 case ISD::SETLE: Swap = true; // Fallthrough
3603 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3604 case ISD::SETUGE: Swap = true; // Fallthrough
3605 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3606 case ISD::SETUGT: Swap = true; // Fallthrough
3607 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3608 case ISD::SETUEQ: Invert = true; // Fallthrough
3610 // Expand this to (OLT | OGT).
3614 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3615 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3617 case ISD::SETUO: Invert = true; // Fallthrough
3619 // Expand this to (OLT | OGE).
3623 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3624 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3628 // Integer comparisons.
3629 switch (SetCCOpcode) {
3630 default: llvm_unreachable("Illegal integer comparison");
3631 case ISD::SETNE: Invert = true;
3632 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3633 case ISD::SETLT: Swap = true;
3634 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3635 case ISD::SETLE: Swap = true;
3636 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3637 case ISD::SETULT: Swap = true;
3638 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3639 case ISD::SETULE: Swap = true;
3640 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3643 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3644 if (Opc == ARMISD::VCEQ) {
3647 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3649 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3652 // Ignore bitconvert.
3653 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3654 AndOp = AndOp.getOperand(0);
3656 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3658 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3659 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3666 std::swap(Op0, Op1);
3668 // If one of the operands is a constant vector zero, attempt to fold the
3669 // comparison to a specialized compare-against-zero form.
3671 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3673 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3674 if (Opc == ARMISD::VCGE)
3675 Opc = ARMISD::VCLEZ;
3676 else if (Opc == ARMISD::VCGT)
3677 Opc = ARMISD::VCLTZ;
3682 if (SingleOp.getNode()) {
3685 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3687 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3689 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3691 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3693 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3695 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3698 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3702 Result = DAG.getNOT(dl, Result, VT);
3707 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3708 /// valid vector constant for a NEON instruction with a "modified immediate"
3709 /// operand (e.g., VMOV). If so, return the encoded value.
3710 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3711 unsigned SplatBitSize, SelectionDAG &DAG,
3712 EVT &VT, bool is128Bits, NEONModImmType type) {
3713 unsigned OpCmode, Imm;
3715 // SplatBitSize is set to the smallest size that splats the vector, so a
3716 // zero vector will always have SplatBitSize == 8. However, NEON modified
3717 // immediate instructions others than VMOV do not support the 8-bit encoding
3718 // of a zero vector, and the default encoding of zero is supposed to be the
3723 switch (SplatBitSize) {
3725 if (type != VMOVModImm)
3727 // Any 1-byte value is OK. Op=0, Cmode=1110.
3728 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3731 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3735 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3736 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3737 if ((SplatBits & ~0xff) == 0) {
3738 // Value = 0x00nn: Op=x, Cmode=100x.
3743 if ((SplatBits & ~0xff00) == 0) {
3744 // Value = 0xnn00: Op=x, Cmode=101x.
3746 Imm = SplatBits >> 8;
3752 // NEON's 32-bit VMOV supports splat values where:
3753 // * only one byte is nonzero, or
3754 // * the least significant byte is 0xff and the second byte is nonzero, or
3755 // * the least significant 2 bytes are 0xff and the third is nonzero.
3756 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3757 if ((SplatBits & ~0xff) == 0) {
3758 // Value = 0x000000nn: Op=x, Cmode=000x.
3763 if ((SplatBits & ~0xff00) == 0) {
3764 // Value = 0x0000nn00: Op=x, Cmode=001x.
3766 Imm = SplatBits >> 8;
3769 if ((SplatBits & ~0xff0000) == 0) {
3770 // Value = 0x00nn0000: Op=x, Cmode=010x.
3772 Imm = SplatBits >> 16;
3775 if ((SplatBits & ~0xff000000) == 0) {
3776 // Value = 0xnn000000: Op=x, Cmode=011x.
3778 Imm = SplatBits >> 24;
3782 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3783 if (type == OtherModImm) return SDValue();
3785 if ((SplatBits & ~0xffff) == 0 &&
3786 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3787 // Value = 0x0000nnff: Op=x, Cmode=1100.
3789 Imm = SplatBits >> 8;
3794 if ((SplatBits & ~0xffffff) == 0 &&
3795 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3796 // Value = 0x00nnffff: Op=x, Cmode=1101.
3798 Imm = SplatBits >> 16;
3799 SplatBits |= 0xffff;
3803 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3804 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3805 // VMOV.I32. A (very) minor optimization would be to replicate the value
3806 // and fall through here to test for a valid 64-bit splat. But, then the
3807 // caller would also need to check and handle the change in size.
3811 if (type != VMOVModImm)
3813 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3814 uint64_t BitMask = 0xff;
3816 unsigned ImmMask = 1;
3818 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3819 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3822 } else if ((SplatBits & BitMask) != 0) {
3828 // Op=1, Cmode=1110.
3831 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3836 llvm_unreachable("unexpected size for isNEONModifiedImm");
3839 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3840 return DAG.getTargetConstant(EncodedVal, MVT::i32);
3843 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3844 const ARMSubtarget *ST) const {
3845 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3848 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3849 assert(Op.getValueType() == MVT::f32 &&
3850 "ConstantFP custom lowering should only occur for f32.");
3852 // Try splatting with a VMOV.f32...
3853 APFloat FPVal = CFP->getValueAPF();
3854 int ImmVal = ARM_AM::getFP32Imm(FPVal);
3856 DebugLoc DL = Op.getDebugLoc();
3857 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3858 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3860 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3861 DAG.getConstant(0, MVT::i32));
3864 // If that fails, try a VMOV.i32
3866 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3867 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3869 if (NewVal != SDValue()) {
3870 DebugLoc DL = Op.getDebugLoc();
3871 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3873 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3875 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3876 DAG.getConstant(0, MVT::i32));
3879 // Finally, try a VMVN.i32
3880 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3882 if (NewVal != SDValue()) {
3883 DebugLoc DL = Op.getDebugLoc();
3884 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3885 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3887 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3888 DAG.getConstant(0, MVT::i32));
3895 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3896 bool &ReverseVEXT, unsigned &Imm) {
3897 unsigned NumElts = VT.getVectorNumElements();
3898 ReverseVEXT = false;
3900 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3906 // If this is a VEXT shuffle, the immediate value is the index of the first
3907 // element. The other shuffle indices must be the successive elements after
3909 unsigned ExpectedElt = Imm;
3910 for (unsigned i = 1; i < NumElts; ++i) {
3911 // Increment the expected index. If it wraps around, it may still be
3912 // a VEXT but the source vectors must be swapped.
3914 if (ExpectedElt == NumElts * 2) {
3919 if (M[i] < 0) continue; // ignore UNDEF indices
3920 if (ExpectedElt != static_cast<unsigned>(M[i]))
3924 // Adjust the index value if the source operands will be swapped.
3931 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3932 /// instruction with the specified blocksize. (The order of the elements
3933 /// within each block of the vector is reversed.)
3934 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3935 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3936 "Only possible block sizes for VREV are: 16, 32, 64");
3938 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3942 unsigned NumElts = VT.getVectorNumElements();
3943 unsigned BlockElts = M[0] + 1;
3944 // If the first shuffle index is UNDEF, be optimistic.
3946 BlockElts = BlockSize / EltSz;
3948 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3951 for (unsigned i = 0; i < NumElts; ++i) {
3952 if (M[i] < 0) continue; // ignore UNDEF indices
3953 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3960 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3961 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3962 // range, then 0 is placed into the resulting vector. So pretty much any mask
3963 // of 8 elements can work here.
3964 return VT == MVT::v8i8 && M.size() == 8;
3967 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3968 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3972 unsigned NumElts = VT.getVectorNumElements();
3973 WhichResult = (M[0] == 0 ? 0 : 1);
3974 for (unsigned i = 0; i < NumElts; i += 2) {
3975 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3976 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3982 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3983 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3984 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3985 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3986 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3990 unsigned NumElts = VT.getVectorNumElements();
3991 WhichResult = (M[0] == 0 ? 0 : 1);
3992 for (unsigned i = 0; i < NumElts; i += 2) {
3993 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3994 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4000 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4001 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4005 unsigned NumElts = VT.getVectorNumElements();
4006 WhichResult = (M[0] == 0 ? 0 : 1);
4007 for (unsigned i = 0; i != NumElts; ++i) {
4008 if (M[i] < 0) continue; // ignore UNDEF indices
4009 if ((unsigned) M[i] != 2 * i + WhichResult)
4013 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4014 if (VT.is64BitVector() && EltSz == 32)
4020 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4021 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4022 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4023 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4024 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4028 unsigned Half = VT.getVectorNumElements() / 2;
4029 WhichResult = (M[0] == 0 ? 0 : 1);
4030 for (unsigned j = 0; j != 2; ++j) {
4031 unsigned Idx = WhichResult;
4032 for (unsigned i = 0; i != Half; ++i) {
4033 int MIdx = M[i + j * Half];
4034 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4040 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4041 if (VT.is64BitVector() && EltSz == 32)
4047 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4048 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4052 unsigned NumElts = VT.getVectorNumElements();
4053 WhichResult = (M[0] == 0 ? 0 : 1);
4054 unsigned Idx = WhichResult * NumElts / 2;
4055 for (unsigned i = 0; i != NumElts; i += 2) {
4056 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4057 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4062 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4063 if (VT.is64BitVector() && EltSz == 32)
4069 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4070 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4071 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4072 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4073 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4077 unsigned NumElts = VT.getVectorNumElements();
4078 WhichResult = (M[0] == 0 ? 0 : 1);
4079 unsigned Idx = WhichResult * NumElts / 2;
4080 for (unsigned i = 0; i != NumElts; i += 2) {
4081 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4082 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4087 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4088 if (VT.is64BitVector() && EltSz == 32)
4094 // If N is an integer constant that can be moved into a register in one
4095 // instruction, return an SDValue of such a constant (will become a MOV
4096 // instruction). Otherwise return null.
4097 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4098 const ARMSubtarget *ST, DebugLoc dl) {
4100 if (!isa<ConstantSDNode>(N))
4102 Val = cast<ConstantSDNode>(N)->getZExtValue();
4104 if (ST->isThumb1Only()) {
4105 if (Val <= 255 || ~Val <= 255)
4106 return DAG.getConstant(Val, MVT::i32);
4108 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4109 return DAG.getConstant(Val, MVT::i32);
4114 // If this is a case we can't handle, return null and let the default
4115 // expansion code take care of it.
4116 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4117 const ARMSubtarget *ST) const {
4118 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4119 DebugLoc dl = Op.getDebugLoc();
4120 EVT VT = Op.getValueType();
4122 APInt SplatBits, SplatUndef;
4123 unsigned SplatBitSize;
4125 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4126 if (SplatBitSize <= 64) {
4127 // Check if an immediate VMOV works.
4129 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4130 SplatUndef.getZExtValue(), SplatBitSize,
4131 DAG, VmovVT, VT.is128BitVector(),
4133 if (Val.getNode()) {
4134 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4135 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4138 // Try an immediate VMVN.
4139 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4140 Val = isNEONModifiedImm(NegatedImm,
4141 SplatUndef.getZExtValue(), SplatBitSize,
4142 DAG, VmovVT, VT.is128BitVector(),
4144 if (Val.getNode()) {
4145 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4146 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4149 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4150 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4151 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4153 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4154 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4160 // Scan through the operands to see if only one value is used.
4162 // As an optimisation, even if more than one value is used it may be more
4163 // profitable to splat with one value then change some lanes.
4165 // Heuristically we decide to do this if the vector has a "dominant" value,
4166 // defined as splatted to more than half of the lanes.
4167 unsigned NumElts = VT.getVectorNumElements();
4168 bool isOnlyLowElement = true;
4169 bool usesOnlyOneValue = true;
4170 bool hasDominantValue = false;
4171 bool isConstant = true;
4173 // Map of the number of times a particular SDValue appears in the
4175 DenseMap<SDValue, unsigned> ValueCounts;
4177 for (unsigned i = 0; i < NumElts; ++i) {
4178 SDValue V = Op.getOperand(i);
4179 if (V.getOpcode() == ISD::UNDEF)
4182 isOnlyLowElement = false;
4183 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4186 ValueCounts.insert(std::make_pair(V, 0));
4187 unsigned &Count = ValueCounts[V];
4189 // Is this value dominant? (takes up more than half of the lanes)
4190 if (++Count > (NumElts / 2)) {
4191 hasDominantValue = true;
4195 if (ValueCounts.size() != 1)
4196 usesOnlyOneValue = false;
4197 if (!Value.getNode() && ValueCounts.size() > 0)
4198 Value = ValueCounts.begin()->first;
4200 if (ValueCounts.size() == 0)
4201 return DAG.getUNDEF(VT);
4203 if (isOnlyLowElement)
4204 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4206 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4208 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4209 // i32 and try again.
4210 if (hasDominantValue && EltSize <= 32) {
4214 // If we are VDUPing a value that comes directly from a vector, that will
4215 // cause an unnecessary move to and from a GPR, where instead we could
4216 // just use VDUPLANE.
4217 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT)
4218 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4219 Value->getOperand(0), Value->getOperand(1));
4221 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4223 if (!usesOnlyOneValue) {
4224 // The dominant value was splatted as 'N', but we now have to insert
4225 // all differing elements.
4226 for (unsigned I = 0; I < NumElts; ++I) {
4227 if (Op.getOperand(I) == Value)
4229 SmallVector<SDValue, 3> Ops;
4231 Ops.push_back(Op.getOperand(I));
4232 Ops.push_back(DAG.getConstant(I, MVT::i32));
4233 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4238 if (VT.getVectorElementType().isFloatingPoint()) {
4239 SmallVector<SDValue, 8> Ops;
4240 for (unsigned i = 0; i < NumElts; ++i)
4241 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4243 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4244 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4245 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4247 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4249 if (usesOnlyOneValue) {
4250 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4251 if (isConstant && Val.getNode())
4252 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4256 // If all elements are constants and the case above didn't get hit, fall back
4257 // to the default expansion, which will generate a load from the constant
4262 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4264 SDValue shuffle = ReconstructShuffle(Op, DAG);
4265 if (shuffle != SDValue())
4269 // Vectors with 32- or 64-bit elements can be built by directly assigning
4270 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4271 // will be legalized.
4272 if (EltSize >= 32) {
4273 // Do the expansion with floating-point types, since that is what the VFP
4274 // registers are defined to use, and since i64 is not legal.
4275 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4276 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4277 SmallVector<SDValue, 8> Ops;
4278 for (unsigned i = 0; i < NumElts; ++i)
4279 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4280 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4281 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4287 // Gather data to see if the operation can be modelled as a
4288 // shuffle in combination with VEXTs.
4289 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4290 SelectionDAG &DAG) const {
4291 DebugLoc dl = Op.getDebugLoc();
4292 EVT VT = Op.getValueType();
4293 unsigned NumElts = VT.getVectorNumElements();
4295 SmallVector<SDValue, 2> SourceVecs;
4296 SmallVector<unsigned, 2> MinElts;
4297 SmallVector<unsigned, 2> MaxElts;
4299 for (unsigned i = 0; i < NumElts; ++i) {
4300 SDValue V = Op.getOperand(i);
4301 if (V.getOpcode() == ISD::UNDEF)
4303 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4304 // A shuffle can only come from building a vector from various
4305 // elements of other vectors.
4307 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4308 VT.getVectorElementType()) {
4309 // This code doesn't know how to handle shuffles where the vector
4310 // element types do not match (this happens because type legalization
4311 // promotes the return type of EXTRACT_VECTOR_ELT).
4312 // FIXME: It might be appropriate to extend this code to handle
4313 // mismatched types.
4317 // Record this extraction against the appropriate vector if possible...
4318 SDValue SourceVec = V.getOperand(0);
4319 // If the element number isn't a constant, we can't effectively
4320 // analyze what's going on.
4321 if (!isa<ConstantSDNode>(V.getOperand(1)))
4323 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4324 bool FoundSource = false;
4325 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4326 if (SourceVecs[j] == SourceVec) {
4327 if (MinElts[j] > EltNo)
4329 if (MaxElts[j] < EltNo)
4336 // Or record a new source if not...
4338 SourceVecs.push_back(SourceVec);
4339 MinElts.push_back(EltNo);
4340 MaxElts.push_back(EltNo);
4344 // Currently only do something sane when at most two source vectors
4346 if (SourceVecs.size() > 2)
4349 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4350 int VEXTOffsets[2] = {0, 0};
4352 // This loop extracts the usage patterns of the source vectors
4353 // and prepares appropriate SDValues for a shuffle if possible.
4354 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4355 if (SourceVecs[i].getValueType() == VT) {
4356 // No VEXT necessary
4357 ShuffleSrcs[i] = SourceVecs[i];
4360 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4361 // It probably isn't worth padding out a smaller vector just to
4362 // break it down again in a shuffle.
4366 // Since only 64-bit and 128-bit vectors are legal on ARM and
4367 // we've eliminated the other cases...
4368 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4369 "unexpected vector sizes in ReconstructShuffle");
4371 if (MaxElts[i] - MinElts[i] >= NumElts) {
4372 // Span too large for a VEXT to cope
4376 if (MinElts[i] >= NumElts) {
4377 // The extraction can just take the second half
4378 VEXTOffsets[i] = NumElts;
4379 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4381 DAG.getIntPtrConstant(NumElts));
4382 } else if (MaxElts[i] < NumElts) {
4383 // The extraction can just take the first half
4385 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4387 DAG.getIntPtrConstant(0));
4389 // An actual VEXT is needed
4390 VEXTOffsets[i] = MinElts[i];
4391 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4393 DAG.getIntPtrConstant(0));
4394 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4396 DAG.getIntPtrConstant(NumElts));
4397 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4398 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4402 SmallVector<int, 8> Mask;
4404 for (unsigned i = 0; i < NumElts; ++i) {
4405 SDValue Entry = Op.getOperand(i);
4406 if (Entry.getOpcode() == ISD::UNDEF) {
4411 SDValue ExtractVec = Entry.getOperand(0);
4412 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4413 .getOperand(1))->getSExtValue();
4414 if (ExtractVec == SourceVecs[0]) {
4415 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4417 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4421 // Final check before we try to produce nonsense...
4422 if (isShuffleMaskLegal(Mask, VT))
4423 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4429 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4430 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4431 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4432 /// are assumed to be legal.
4434 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4436 if (VT.getVectorNumElements() == 4 &&
4437 (VT.is128BitVector() || VT.is64BitVector())) {
4438 unsigned PFIndexes[4];
4439 for (unsigned i = 0; i != 4; ++i) {
4443 PFIndexes[i] = M[i];
4446 // Compute the index in the perfect shuffle table.
4447 unsigned PFTableIndex =
4448 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4449 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4450 unsigned Cost = (PFEntry >> 30);
4457 unsigned Imm, WhichResult;
4459 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4460 return (EltSize >= 32 ||
4461 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4462 isVREVMask(M, VT, 64) ||
4463 isVREVMask(M, VT, 32) ||
4464 isVREVMask(M, VT, 16) ||
4465 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4466 isVTBLMask(M, VT) ||
4467 isVTRNMask(M, VT, WhichResult) ||
4468 isVUZPMask(M, VT, WhichResult) ||
4469 isVZIPMask(M, VT, WhichResult) ||
4470 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4471 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4472 isVZIP_v_undef_Mask(M, VT, WhichResult));
4475 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4476 /// the specified operations to build the shuffle.
4477 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4478 SDValue RHS, SelectionDAG &DAG,
4480 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4481 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4482 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4485 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4494 OP_VUZPL, // VUZP, left result
4495 OP_VUZPR, // VUZP, right result
4496 OP_VZIPL, // VZIP, left result
4497 OP_VZIPR, // VZIP, right result
4498 OP_VTRNL, // VTRN, left result
4499 OP_VTRNR // VTRN, right result
4502 if (OpNum == OP_COPY) {
4503 if (LHSID == (1*9+2)*9+3) return LHS;
4504 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4508 SDValue OpLHS, OpRHS;
4509 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4510 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4511 EVT VT = OpLHS.getValueType();
4514 default: llvm_unreachable("Unknown shuffle opcode!");
4516 // VREV divides the vector in half and swaps within the half.
4517 if (VT.getVectorElementType() == MVT::i32 ||
4518 VT.getVectorElementType() == MVT::f32)
4519 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4520 // vrev <4 x i16> -> VREV32
4521 if (VT.getVectorElementType() == MVT::i16)
4522 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4523 // vrev <4 x i8> -> VREV16
4524 assert(VT.getVectorElementType() == MVT::i8);
4525 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4530 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4531 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4535 return DAG.getNode(ARMISD::VEXT, dl, VT,
4537 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4540 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4541 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4544 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4545 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4548 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4549 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4553 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4554 ArrayRef<int> ShuffleMask,
4555 SelectionDAG &DAG) {
4556 // Check to see if we can use the VTBL instruction.
4557 SDValue V1 = Op.getOperand(0);
4558 SDValue V2 = Op.getOperand(1);
4559 DebugLoc DL = Op.getDebugLoc();
4561 SmallVector<SDValue, 8> VTBLMask;
4562 for (ArrayRef<int>::iterator
4563 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4564 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4566 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4567 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4568 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4571 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4572 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4576 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4577 SDValue V1 = Op.getOperand(0);
4578 SDValue V2 = Op.getOperand(1);
4579 DebugLoc dl = Op.getDebugLoc();
4580 EVT VT = Op.getValueType();
4581 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4583 // Convert shuffles that are directly supported on NEON to target-specific
4584 // DAG nodes, instead of keeping them as shuffles and matching them again
4585 // during code selection. This is more efficient and avoids the possibility
4586 // of inconsistencies between legalization and selection.
4587 // FIXME: floating-point vectors should be canonicalized to integer vectors
4588 // of the same time so that they get CSEd properly.
4589 ArrayRef<int> ShuffleMask = SVN->getMask();
4591 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4592 if (EltSize <= 32) {
4593 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4594 int Lane = SVN->getSplatIndex();
4595 // If this is undef splat, generate it via "just" vdup, if possible.
4596 if (Lane == -1) Lane = 0;
4598 // Test if V1 is a SCALAR_TO_VECTOR.
4599 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4600 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4602 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4603 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4605 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4606 !isa<ConstantSDNode>(V1.getOperand(0))) {
4607 bool IsScalarToVector = true;
4608 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4609 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4610 IsScalarToVector = false;
4613 if (IsScalarToVector)
4614 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4616 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4617 DAG.getConstant(Lane, MVT::i32));
4622 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4625 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4626 DAG.getConstant(Imm, MVT::i32));
4629 if (isVREVMask(ShuffleMask, VT, 64))
4630 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4631 if (isVREVMask(ShuffleMask, VT, 32))
4632 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4633 if (isVREVMask(ShuffleMask, VT, 16))
4634 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4636 // Check for Neon shuffles that modify both input vectors in place.
4637 // If both results are used, i.e., if there are two shuffles with the same
4638 // source operands and with masks corresponding to both results of one of
4639 // these operations, DAG memoization will ensure that a single node is
4640 // used for both shuffles.
4641 unsigned WhichResult;
4642 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4643 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4644 V1, V2).getValue(WhichResult);
4645 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4646 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4647 V1, V2).getValue(WhichResult);
4648 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4649 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4650 V1, V2).getValue(WhichResult);
4652 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4653 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4654 V1, V1).getValue(WhichResult);
4655 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4656 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4657 V1, V1).getValue(WhichResult);
4658 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4659 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4660 V1, V1).getValue(WhichResult);
4663 // If the shuffle is not directly supported and it has 4 elements, use
4664 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4665 unsigned NumElts = VT.getVectorNumElements();
4667 unsigned PFIndexes[4];
4668 for (unsigned i = 0; i != 4; ++i) {
4669 if (ShuffleMask[i] < 0)
4672 PFIndexes[i] = ShuffleMask[i];
4675 // Compute the index in the perfect shuffle table.
4676 unsigned PFTableIndex =
4677 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4678 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4679 unsigned Cost = (PFEntry >> 30);
4682 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4685 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4686 if (EltSize >= 32) {
4687 // Do the expansion with floating-point types, since that is what the VFP
4688 // registers are defined to use, and since i64 is not legal.
4689 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4690 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4691 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4692 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4693 SmallVector<SDValue, 8> Ops;
4694 for (unsigned i = 0; i < NumElts; ++i) {
4695 if (ShuffleMask[i] < 0)
4696 Ops.push_back(DAG.getUNDEF(EltVT));
4698 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4699 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4700 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4703 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4704 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4707 if (VT == MVT::v8i8) {
4708 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4709 if (NewOp.getNode())
4716 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4717 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4718 SDValue Lane = Op.getOperand(2);
4719 if (!isa<ConstantSDNode>(Lane))
4725 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4726 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4727 SDValue Lane = Op.getOperand(1);
4728 if (!isa<ConstantSDNode>(Lane))
4731 SDValue Vec = Op.getOperand(0);
4732 if (Op.getValueType() == MVT::i32 &&
4733 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4734 DebugLoc dl = Op.getDebugLoc();
4735 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4741 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4742 // The only time a CONCAT_VECTORS operation can have legal types is when
4743 // two 64-bit vectors are concatenated to a 128-bit vector.
4744 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4745 "unexpected CONCAT_VECTORS");
4746 DebugLoc dl = Op.getDebugLoc();
4747 SDValue Val = DAG.getUNDEF(MVT::v2f64);
4748 SDValue Op0 = Op.getOperand(0);
4749 SDValue Op1 = Op.getOperand(1);
4750 if (Op0.getOpcode() != ISD::UNDEF)
4751 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4752 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4753 DAG.getIntPtrConstant(0));
4754 if (Op1.getOpcode() != ISD::UNDEF)
4755 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4756 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4757 DAG.getIntPtrConstant(1));
4758 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4761 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4762 /// element has been zero/sign-extended, depending on the isSigned parameter,
4763 /// from an integer type half its size.
4764 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4766 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4767 EVT VT = N->getValueType(0);
4768 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4769 SDNode *BVN = N->getOperand(0).getNode();
4770 if (BVN->getValueType(0) != MVT::v4i32 ||
4771 BVN->getOpcode() != ISD::BUILD_VECTOR)
4773 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4774 unsigned HiElt = 1 - LoElt;
4775 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4776 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4777 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4778 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4779 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4782 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4783 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4786 if (Hi0->isNullValue() && Hi1->isNullValue())
4792 if (N->getOpcode() != ISD::BUILD_VECTOR)
4795 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4796 SDNode *Elt = N->getOperand(i).getNode();
4797 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4798 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4799 unsigned HalfSize = EltSize / 2;
4801 if (!isIntN(HalfSize, C->getSExtValue()))
4804 if (!isUIntN(HalfSize, C->getZExtValue()))
4815 /// isSignExtended - Check if a node is a vector value that is sign-extended
4816 /// or a constant BUILD_VECTOR with sign-extended elements.
4817 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4818 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4820 if (isExtendedBUILD_VECTOR(N, DAG, true))
4825 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4826 /// or a constant BUILD_VECTOR with zero-extended elements.
4827 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4828 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4830 if (isExtendedBUILD_VECTOR(N, DAG, false))
4835 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4836 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4837 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4838 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4839 return N->getOperand(0);
4840 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4841 return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4842 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4843 LD->isNonTemporal(), LD->isInvariant(),
4844 LD->getAlignment());
4845 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
4846 // have been legalized as a BITCAST from v4i32.
4847 if (N->getOpcode() == ISD::BITCAST) {
4848 SDNode *BVN = N->getOperand(0).getNode();
4849 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4850 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4851 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4852 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4853 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4855 // Construct a new BUILD_VECTOR with elements truncated to half the size.
4856 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4857 EVT VT = N->getValueType(0);
4858 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4859 unsigned NumElts = VT.getVectorNumElements();
4860 MVT TruncVT = MVT::getIntegerVT(EltSize);
4861 SmallVector<SDValue, 8> Ops;
4862 for (unsigned i = 0; i != NumElts; ++i) {
4863 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4864 const APInt &CInt = C->getAPIntValue();
4865 // Element types smaller than 32 bits are not legal, so use i32 elements.
4866 // The values are implicitly truncated so sext vs. zext doesn't matter.
4867 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4869 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4870 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4873 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4874 unsigned Opcode = N->getOpcode();
4875 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4876 SDNode *N0 = N->getOperand(0).getNode();
4877 SDNode *N1 = N->getOperand(1).getNode();
4878 return N0->hasOneUse() && N1->hasOneUse() &&
4879 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4884 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4885 unsigned Opcode = N->getOpcode();
4886 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4887 SDNode *N0 = N->getOperand(0).getNode();
4888 SDNode *N1 = N->getOperand(1).getNode();
4889 return N0->hasOneUse() && N1->hasOneUse() &&
4890 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4895 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4896 // Multiplications are only custom-lowered for 128-bit vectors so that
4897 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
4898 EVT VT = Op.getValueType();
4899 assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4900 SDNode *N0 = Op.getOperand(0).getNode();
4901 SDNode *N1 = Op.getOperand(1).getNode();
4902 unsigned NewOpc = 0;
4904 bool isN0SExt = isSignExtended(N0, DAG);
4905 bool isN1SExt = isSignExtended(N1, DAG);
4906 if (isN0SExt && isN1SExt)
4907 NewOpc = ARMISD::VMULLs;
4909 bool isN0ZExt = isZeroExtended(N0, DAG);
4910 bool isN1ZExt = isZeroExtended(N1, DAG);
4911 if (isN0ZExt && isN1ZExt)
4912 NewOpc = ARMISD::VMULLu;
4913 else if (isN1SExt || isN1ZExt) {
4914 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4915 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4916 if (isN1SExt && isAddSubSExt(N0, DAG)) {
4917 NewOpc = ARMISD::VMULLs;
4919 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4920 NewOpc = ARMISD::VMULLu;
4922 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4924 NewOpc = ARMISD::VMULLu;
4930 if (VT == MVT::v2i64)
4931 // Fall through to expand this. It is not legal.
4934 // Other vector multiplications are legal.
4939 // Legalize to a VMULL instruction.
4940 DebugLoc DL = Op.getDebugLoc();
4942 SDValue Op1 = SkipExtension(N1, DAG);
4944 Op0 = SkipExtension(N0, DAG);
4945 assert(Op0.getValueType().is64BitVector() &&
4946 Op1.getValueType().is64BitVector() &&
4947 "unexpected types for extended operands to VMULL");
4948 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4951 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4952 // isel lowering to take advantage of no-stall back to back vmul + vmla.
4959 SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4960 SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4961 EVT Op1VT = Op1.getValueType();
4962 return DAG.getNode(N0->getOpcode(), DL, VT,
4963 DAG.getNode(NewOpc, DL, VT,
4964 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4965 DAG.getNode(NewOpc, DL, VT,
4966 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4970 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4972 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4973 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4974 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4975 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4976 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4977 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4978 // Get reciprocal estimate.
4979 // float4 recip = vrecpeq_f32(yf);
4980 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4981 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4982 // Because char has a smaller range than uchar, we can actually get away
4983 // without any newton steps. This requires that we use a weird bias
4984 // of 0xb000, however (again, this has been exhaustively tested).
4985 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4986 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4987 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4988 Y = DAG.getConstant(0xb000, MVT::i32);
4989 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4990 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4991 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4992 // Convert back to short.
4993 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4994 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4999 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5001 // Convert to float.
5002 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5003 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5004 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5005 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5006 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5007 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5009 // Use reciprocal estimate and one refinement step.
5010 // float4 recip = vrecpeq_f32(yf);
5011 // recip *= vrecpsq_f32(yf, recip);
5012 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5013 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5014 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5015 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5017 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5018 // Because short has a smaller range than ushort, we can actually get away
5019 // with only a single newton step. This requires that we use a weird bias
5020 // of 89, however (again, this has been exhaustively tested).
5021 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5022 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5023 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5024 N1 = DAG.getConstant(0x89, MVT::i32);
5025 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5026 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5027 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5028 // Convert back to integer and return.
5029 // return vmovn_s32(vcvt_s32_f32(result));
5030 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5031 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5035 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5036 EVT VT = Op.getValueType();
5037 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5038 "unexpected type for custom-lowering ISD::SDIV");
5040 DebugLoc dl = Op.getDebugLoc();
5041 SDValue N0 = Op.getOperand(0);
5042 SDValue N1 = Op.getOperand(1);
5045 if (VT == MVT::v8i8) {
5046 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5047 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5049 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5050 DAG.getIntPtrConstant(4));
5051 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5052 DAG.getIntPtrConstant(4));
5053 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5054 DAG.getIntPtrConstant(0));
5055 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5056 DAG.getIntPtrConstant(0));
5058 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5059 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5061 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5062 N0 = LowerCONCAT_VECTORS(N0, DAG);
5064 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5067 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5070 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5071 EVT VT = Op.getValueType();
5072 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5073 "unexpected type for custom-lowering ISD::UDIV");
5075 DebugLoc dl = Op.getDebugLoc();
5076 SDValue N0 = Op.getOperand(0);
5077 SDValue N1 = Op.getOperand(1);
5080 if (VT == MVT::v8i8) {
5081 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5082 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5084 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5085 DAG.getIntPtrConstant(4));
5086 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5087 DAG.getIntPtrConstant(4));
5088 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5089 DAG.getIntPtrConstant(0));
5090 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5091 DAG.getIntPtrConstant(0));
5093 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5094 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5096 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5097 N0 = LowerCONCAT_VECTORS(N0, DAG);
5099 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5100 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5105 // v4i16 sdiv ... Convert to float.
5106 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5107 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5108 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5109 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5110 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5111 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5113 // Use reciprocal estimate and two refinement steps.
5114 // float4 recip = vrecpeq_f32(yf);
5115 // recip *= vrecpsq_f32(yf, recip);
5116 // recip *= vrecpsq_f32(yf, recip);
5117 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5118 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5119 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5120 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5122 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5123 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5124 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5126 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5127 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5128 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5129 // and that it will never cause us to return an answer too large).
5130 // float4 result = as_float4(as_int4(xf*recip) + 2);
5131 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5132 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5133 N1 = DAG.getConstant(2, MVT::i32);
5134 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5135 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5136 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5137 // Convert back to integer and return.
5138 // return vmovn_u32(vcvt_s32_f32(result));
5139 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5140 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5144 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5145 EVT VT = Op.getNode()->getValueType(0);
5146 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5149 bool ExtraOp = false;
5150 switch (Op.getOpcode()) {
5151 default: llvm_unreachable("Invalid code");
5152 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5153 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5154 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5155 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5159 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5161 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5162 Op.getOperand(1), Op.getOperand(2));
5165 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5166 // Monotonic load/store is legal for all targets
5167 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5170 // Aquire/Release load/store is not legal for targets without a
5171 // dmb or equivalent available.
5177 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5178 SelectionDAG &DAG, unsigned NewOp) {
5179 DebugLoc dl = Node->getDebugLoc();
5180 assert (Node->getValueType(0) == MVT::i64 &&
5181 "Only know how to expand i64 atomics");
5183 SmallVector<SDValue, 6> Ops;
5184 Ops.push_back(Node->getOperand(0)); // Chain
5185 Ops.push_back(Node->getOperand(1)); // Ptr
5187 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5188 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5189 // High part of Val1
5190 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5191 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5192 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5193 // High part of Val1
5194 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5195 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5196 // High part of Val2
5197 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5198 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5200 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5202 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5203 cast<MemSDNode>(Node)->getMemOperand());
5204 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5205 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5206 Results.push_back(Result.getValue(2));
5209 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5210 switch (Op.getOpcode()) {
5211 default: llvm_unreachable("Don't know how to custom lower this!");
5212 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5213 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5214 case ISD::GlobalAddress:
5215 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5216 LowerGlobalAddressELF(Op, DAG);
5217 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5218 case ISD::SELECT: return LowerSELECT(Op, DAG);
5219 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5220 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5221 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5222 case ISD::VASTART: return LowerVASTART(Op, DAG);
5223 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5224 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5225 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5226 case ISD::SINT_TO_FP:
5227 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5228 case ISD::FP_TO_SINT:
5229 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5230 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5231 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5232 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5233 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5234 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5235 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5236 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5238 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5241 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5242 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5243 case ISD::SRL_PARTS:
5244 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5245 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5246 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5247 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5248 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5249 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5250 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5251 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5252 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5253 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5254 case ISD::MUL: return LowerMUL(Op, DAG);
5255 case ISD::SDIV: return LowerSDIV(Op, DAG);
5256 case ISD::UDIV: return LowerUDIV(Op, DAG);
5260 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5261 case ISD::ATOMIC_LOAD:
5262 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5266 /// ReplaceNodeResults - Replace the results of node with an illegal result
5267 /// type with new values built out of custom code.
5268 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5269 SmallVectorImpl<SDValue>&Results,
5270 SelectionDAG &DAG) const {
5272 switch (N->getOpcode()) {
5274 llvm_unreachable("Don't know how to custom expand this!");
5276 Res = ExpandBITCAST(N, DAG);
5280 Res = Expand64BitShift(N, DAG, Subtarget);
5282 case ISD::ATOMIC_LOAD_ADD:
5283 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5285 case ISD::ATOMIC_LOAD_AND:
5286 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5288 case ISD::ATOMIC_LOAD_NAND:
5289 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5291 case ISD::ATOMIC_LOAD_OR:
5292 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5294 case ISD::ATOMIC_LOAD_SUB:
5295 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5297 case ISD::ATOMIC_LOAD_XOR:
5298 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5300 case ISD::ATOMIC_SWAP:
5301 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5303 case ISD::ATOMIC_CMP_SWAP:
5304 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5308 Results.push_back(Res);
5311 //===----------------------------------------------------------------------===//
5312 // ARM Scheduler Hooks
5313 //===----------------------------------------------------------------------===//
5316 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5317 MachineBasicBlock *BB,
5318 unsigned Size) const {
5319 unsigned dest = MI->getOperand(0).getReg();
5320 unsigned ptr = MI->getOperand(1).getReg();
5321 unsigned oldval = MI->getOperand(2).getReg();
5322 unsigned newval = MI->getOperand(3).getReg();
5323 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5324 DebugLoc dl = MI->getDebugLoc();
5325 bool isThumb2 = Subtarget->isThumb2();
5327 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5328 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5329 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5330 (const TargetRegisterClass*)&ARM::GPRRegClass);
5333 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5334 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5335 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5338 unsigned ldrOpc, strOpc;
5340 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5342 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5343 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5346 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5347 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5350 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5351 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5355 MachineFunction *MF = BB->getParent();
5356 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5357 MachineFunction::iterator It = BB;
5358 ++It; // insert the new blocks after the current block
5360 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5361 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5362 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5363 MF->insert(It, loop1MBB);
5364 MF->insert(It, loop2MBB);
5365 MF->insert(It, exitMBB);
5367 // Transfer the remainder of BB and its successor edges to exitMBB.
5368 exitMBB->splice(exitMBB->begin(), BB,
5369 llvm::next(MachineBasicBlock::iterator(MI)),
5371 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5375 // fallthrough --> loop1MBB
5376 BB->addSuccessor(loop1MBB);
5379 // ldrex dest, [ptr]
5383 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5384 if (ldrOpc == ARM::t2LDREX)
5386 AddDefaultPred(MIB);
5387 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5388 .addReg(dest).addReg(oldval));
5389 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5390 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5391 BB->addSuccessor(loop2MBB);
5392 BB->addSuccessor(exitMBB);
5395 // strex scratch, newval, [ptr]
5399 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5400 if (strOpc == ARM::t2STREX)
5402 AddDefaultPred(MIB);
5403 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5404 .addReg(scratch).addImm(0));
5405 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5406 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5407 BB->addSuccessor(loop1MBB);
5408 BB->addSuccessor(exitMBB);
5414 MI->eraseFromParent(); // The instruction is gone now.
5420 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5421 unsigned Size, unsigned BinOpcode) const {
5422 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5423 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5425 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5426 MachineFunction *MF = BB->getParent();
5427 MachineFunction::iterator It = BB;
5430 unsigned dest = MI->getOperand(0).getReg();
5431 unsigned ptr = MI->getOperand(1).getReg();
5432 unsigned incr = MI->getOperand(2).getReg();
5433 DebugLoc dl = MI->getDebugLoc();
5434 bool isThumb2 = Subtarget->isThumb2();
5436 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5438 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5439 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5442 unsigned ldrOpc, strOpc;
5444 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5446 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5447 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5450 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5451 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5454 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5455 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5459 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5460 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5461 MF->insert(It, loopMBB);
5462 MF->insert(It, exitMBB);
5464 // Transfer the remainder of BB and its successor edges to exitMBB.
5465 exitMBB->splice(exitMBB->begin(), BB,
5466 llvm::next(MachineBasicBlock::iterator(MI)),
5468 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5470 const TargetRegisterClass *TRC = isThumb2 ?
5471 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5472 (const TargetRegisterClass*)&ARM::GPRRegClass;
5473 unsigned scratch = MRI.createVirtualRegister(TRC);
5474 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5478 // fallthrough --> loopMBB
5479 BB->addSuccessor(loopMBB);
5483 // <binop> scratch2, dest, incr
5484 // strex scratch, scratch2, ptr
5487 // fallthrough --> exitMBB
5489 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5490 if (ldrOpc == ARM::t2LDREX)
5492 AddDefaultPred(MIB);
5494 // operand order needs to go the other way for NAND
5495 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5496 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5497 addReg(incr).addReg(dest)).addReg(0);
5499 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5500 addReg(dest).addReg(incr)).addReg(0);
5503 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5504 if (strOpc == ARM::t2STREX)
5506 AddDefaultPred(MIB);
5507 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5508 .addReg(scratch).addImm(0));
5509 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5510 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5512 BB->addSuccessor(loopMBB);
5513 BB->addSuccessor(exitMBB);
5519 MI->eraseFromParent(); // The instruction is gone now.
5525 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5526 MachineBasicBlock *BB,
5529 ARMCC::CondCodes Cond) const {
5530 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5532 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5533 MachineFunction *MF = BB->getParent();
5534 MachineFunction::iterator It = BB;
5537 unsigned dest = MI->getOperand(0).getReg();
5538 unsigned ptr = MI->getOperand(1).getReg();
5539 unsigned incr = MI->getOperand(2).getReg();
5540 unsigned oldval = dest;
5541 DebugLoc dl = MI->getDebugLoc();
5542 bool isThumb2 = Subtarget->isThumb2();
5544 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5546 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5547 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5550 unsigned ldrOpc, strOpc, extendOpc;
5552 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5554 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5555 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5556 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5559 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5560 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5561 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5564 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5565 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5570 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5571 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5572 MF->insert(It, loopMBB);
5573 MF->insert(It, exitMBB);
5575 // Transfer the remainder of BB and its successor edges to exitMBB.
5576 exitMBB->splice(exitMBB->begin(), BB,
5577 llvm::next(MachineBasicBlock::iterator(MI)),
5579 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5581 const TargetRegisterClass *TRC = isThumb2 ?
5582 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5583 (const TargetRegisterClass*)&ARM::GPRRegClass;
5584 unsigned scratch = MRI.createVirtualRegister(TRC);
5585 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5589 // fallthrough --> loopMBB
5590 BB->addSuccessor(loopMBB);
5594 // (sign extend dest, if required)
5596 // cmov.cond scratch2, dest, incr
5597 // strex scratch, scratch2, ptr
5600 // fallthrough --> exitMBB
5602 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5603 if (ldrOpc == ARM::t2LDREX)
5605 AddDefaultPred(MIB);
5607 // Sign extend the value, if necessary.
5608 if (signExtend && extendOpc) {
5609 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5610 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5615 // Build compare and cmov instructions.
5616 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5617 .addReg(oldval).addReg(incr));
5618 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5619 .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5621 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5622 if (strOpc == ARM::t2STREX)
5624 AddDefaultPred(MIB);
5625 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5626 .addReg(scratch).addImm(0));
5627 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5628 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5630 BB->addSuccessor(loopMBB);
5631 BB->addSuccessor(exitMBB);
5637 MI->eraseFromParent(); // The instruction is gone now.
5643 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5644 unsigned Op1, unsigned Op2,
5645 bool NeedsCarry, bool IsCmpxchg) const {
5646 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5647 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5649 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5650 MachineFunction *MF = BB->getParent();
5651 MachineFunction::iterator It = BB;
5654 unsigned destlo = MI->getOperand(0).getReg();
5655 unsigned desthi = MI->getOperand(1).getReg();
5656 unsigned ptr = MI->getOperand(2).getReg();
5657 unsigned vallo = MI->getOperand(3).getReg();
5658 unsigned valhi = MI->getOperand(4).getReg();
5659 DebugLoc dl = MI->getDebugLoc();
5660 bool isThumb2 = Subtarget->isThumb2();
5662 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5664 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5665 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5666 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5669 unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5670 unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5672 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5673 MachineBasicBlock *contBB = 0, *cont2BB = 0;
5675 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5676 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5678 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5679 MF->insert(It, loopMBB);
5681 MF->insert(It, contBB);
5682 MF->insert(It, cont2BB);
5684 MF->insert(It, exitMBB);
5686 // Transfer the remainder of BB and its successor edges to exitMBB.
5687 exitMBB->splice(exitMBB->begin(), BB,
5688 llvm::next(MachineBasicBlock::iterator(MI)),
5690 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5692 const TargetRegisterClass *TRC = isThumb2 ?
5693 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5694 (const TargetRegisterClass*)&ARM::GPRRegClass;
5695 unsigned storesuccess = MRI.createVirtualRegister(TRC);
5699 // fallthrough --> loopMBB
5700 BB->addSuccessor(loopMBB);
5703 // ldrexd r2, r3, ptr
5704 // <binopa> r0, r2, incr
5705 // <binopb> r1, r3, incr
5706 // strexd storesuccess, r0, r1, ptr
5707 // cmp storesuccess, #0
5709 // fallthrough --> exitMBB
5711 // Note that the registers are explicitly specified because there is not any
5712 // way to force the register allocator to allocate a register pair.
5714 // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5715 // need to properly enforce the restriction that the two output registers
5716 // for ldrexd must be different.
5719 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5720 .addReg(ARM::R2, RegState::Define)
5721 .addReg(ARM::R3, RegState::Define).addReg(ptr));
5722 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
5723 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5724 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5728 for (unsigned i = 0; i < 2; i++) {
5729 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5731 .addReg(i == 0 ? destlo : desthi)
5732 .addReg(i == 0 ? vallo : valhi));
5733 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5734 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5735 BB->addSuccessor(exitMBB);
5736 BB->addSuccessor(i == 0 ? contBB : cont2BB);
5737 BB = (i == 0 ? contBB : cont2BB);
5740 // Copy to physregs for strexd
5741 unsigned setlo = MI->getOperand(5).getReg();
5742 unsigned sethi = MI->getOperand(6).getReg();
5743 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5744 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5746 // Perform binary operation
5747 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5748 .addReg(destlo).addReg(vallo))
5749 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5750 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5751 .addReg(desthi).addReg(valhi)).addReg(0);
5753 // Copy to physregs for strexd
5754 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5755 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5759 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5760 .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5762 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5763 .addReg(storesuccess).addImm(0));
5764 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5765 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5767 BB->addSuccessor(loopMBB);
5768 BB->addSuccessor(exitMBB);
5774 MI->eraseFromParent(); // The instruction is gone now.
5779 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5780 /// registers the function context.
5781 void ARMTargetLowering::
5782 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5783 MachineBasicBlock *DispatchBB, int FI) const {
5784 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5785 DebugLoc dl = MI->getDebugLoc();
5786 MachineFunction *MF = MBB->getParent();
5787 MachineRegisterInfo *MRI = &MF->getRegInfo();
5788 MachineConstantPool *MCP = MF->getConstantPool();
5789 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5790 const Function *F = MF->getFunction();
5792 bool isThumb = Subtarget->isThumb();
5793 bool isThumb2 = Subtarget->isThumb2();
5795 unsigned PCLabelId = AFI->createPICLabelUId();
5796 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5797 ARMConstantPoolValue *CPV =
5798 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5799 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5801 const TargetRegisterClass *TRC = isThumb ?
5802 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5803 (const TargetRegisterClass*)&ARM::GPRRegClass;
5805 // Grab constant pool and fixed stack memory operands.
5806 MachineMemOperand *CPMMO =
5807 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5808 MachineMemOperand::MOLoad, 4, 4);
5810 MachineMemOperand *FIMMOSt =
5811 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5812 MachineMemOperand::MOStore, 4, 4);
5814 // Load the address of the dispatch MBB into the jump buffer.
5816 // Incoming value: jbuf
5817 // ldr.n r5, LCPI1_1
5820 // str r5, [$jbuf, #+4] ; &jbuf[1]
5821 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5822 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5823 .addConstantPoolIndex(CPI)
5824 .addMemOperand(CPMMO));
5825 // Set the low bit because of thumb mode.
5826 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5828 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5829 .addReg(NewVReg1, RegState::Kill)
5831 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5832 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5833 .addReg(NewVReg2, RegState::Kill)
5835 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5836 .addReg(NewVReg3, RegState::Kill)
5838 .addImm(36) // &jbuf[1] :: pc
5839 .addMemOperand(FIMMOSt));
5840 } else if (isThumb) {
5841 // Incoming value: jbuf
5842 // ldr.n r1, LCPI1_4
5846 // add r2, $jbuf, #+4 ; &jbuf[1]
5848 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5849 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5850 .addConstantPoolIndex(CPI)
5851 .addMemOperand(CPMMO));
5852 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5853 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5854 .addReg(NewVReg1, RegState::Kill)
5856 // Set the low bit because of thumb mode.
5857 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5858 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5859 .addReg(ARM::CPSR, RegState::Define)
5861 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5862 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5863 .addReg(ARM::CPSR, RegState::Define)
5864 .addReg(NewVReg2, RegState::Kill)
5865 .addReg(NewVReg3, RegState::Kill));
5866 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5867 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5869 .addImm(36)); // &jbuf[1] :: pc
5870 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5871 .addReg(NewVReg4, RegState::Kill)
5872 .addReg(NewVReg5, RegState::Kill)
5874 .addMemOperand(FIMMOSt));
5876 // Incoming value: jbuf
5879 // str r1, [$jbuf, #+4] ; &jbuf[1]
5880 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5881 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
5882 .addConstantPoolIndex(CPI)
5884 .addMemOperand(CPMMO));
5885 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5886 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5887 .addReg(NewVReg1, RegState::Kill)
5888 .addImm(PCLabelId));
5889 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5890 .addReg(NewVReg2, RegState::Kill)
5892 .addImm(36) // &jbuf[1] :: pc
5893 .addMemOperand(FIMMOSt));
5897 MachineBasicBlock *ARMTargetLowering::
5898 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5899 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5900 DebugLoc dl = MI->getDebugLoc();
5901 MachineFunction *MF = MBB->getParent();
5902 MachineRegisterInfo *MRI = &MF->getRegInfo();
5903 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5904 MachineFrameInfo *MFI = MF->getFrameInfo();
5905 int FI = MFI->getFunctionContextIndex();
5907 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5908 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5909 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5911 // Get a mapping of the call site numbers to all of the landing pads they're
5913 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5914 unsigned MaxCSNum = 0;
5915 MachineModuleInfo &MMI = MF->getMMI();
5916 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5918 if (!BB->isLandingPad()) continue;
5920 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5922 for (MachineBasicBlock::iterator
5923 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5924 if (!II->isEHLabel()) continue;
5926 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5927 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5929 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5930 for (SmallVectorImpl<unsigned>::iterator
5931 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5932 CSI != CSE; ++CSI) {
5933 CallSiteNumToLPad[*CSI].push_back(BB);
5934 MaxCSNum = std::max(MaxCSNum, *CSI);
5940 // Get an ordered list of the machine basic blocks for the jump table.
5941 std::vector<MachineBasicBlock*> LPadList;
5942 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5943 LPadList.reserve(CallSiteNumToLPad.size());
5944 for (unsigned I = 1; I <= MaxCSNum; ++I) {
5945 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5946 for (SmallVectorImpl<MachineBasicBlock*>::iterator
5947 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5948 LPadList.push_back(*II);
5949 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5953 assert(!LPadList.empty() &&
5954 "No landing pad destinations for the dispatch jump table!");
5956 // Create the jump table and associated information.
5957 MachineJumpTableInfo *JTI =
5958 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5959 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5960 unsigned UId = AFI->createJumpTableUId();
5962 // Create the MBBs for the dispatch code.
5964 // Shove the dispatch's address into the return slot in the function context.
5965 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5966 DispatchBB->setIsLandingPad();
5968 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5969 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5970 DispatchBB->addSuccessor(TrapBB);
5972 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5973 DispatchBB->addSuccessor(DispContBB);
5976 MF->insert(MF->end(), DispatchBB);
5977 MF->insert(MF->end(), DispContBB);
5978 MF->insert(MF->end(), TrapBB);
5980 // Insert code into the entry block that creates and registers the function
5982 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5984 MachineMemOperand *FIMMOLd =
5985 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5986 MachineMemOperand::MOLoad |
5987 MachineMemOperand::MOVolatile, 4, 4);
5989 if (AFI->isThumb1OnlyFunction())
5990 BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5991 else if (!Subtarget->hasVFP2())
5992 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5994 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5996 unsigned NumLPads = LPadList.size();
5997 if (Subtarget->isThumb2()) {
5998 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5999 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6002 .addMemOperand(FIMMOLd));
6004 if (NumLPads < 256) {
6005 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6007 .addImm(LPadList.size()));
6009 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6010 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6011 .addImm(NumLPads & 0xFFFF));
6013 unsigned VReg2 = VReg1;
6014 if ((NumLPads & 0xFFFF0000) != 0) {
6015 VReg2 = MRI->createVirtualRegister(TRC);
6016 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6018 .addImm(NumLPads >> 16));
6021 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6026 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6031 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6032 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6033 .addJumpTableIndex(MJTI)
6036 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6039 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6040 .addReg(NewVReg3, RegState::Kill)
6042 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6044 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6045 .addReg(NewVReg4, RegState::Kill)
6047 .addJumpTableIndex(MJTI)
6049 } else if (Subtarget->isThumb()) {
6050 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6051 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6054 .addMemOperand(FIMMOLd));
6056 if (NumLPads < 256) {
6057 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6061 MachineConstantPool *ConstantPool = MF->getConstantPool();
6062 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6063 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6065 // MachineConstantPool wants an explicit alignment.
6066 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6068 Align = getTargetData()->getTypeAllocSize(C->getType());
6069 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6071 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6072 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6073 .addReg(VReg1, RegState::Define)
6074 .addConstantPoolIndex(Idx));
6075 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6080 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6085 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6086 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6087 .addReg(ARM::CPSR, RegState::Define)
6091 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6092 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6093 .addJumpTableIndex(MJTI)
6096 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6097 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6098 .addReg(ARM::CPSR, RegState::Define)
6099 .addReg(NewVReg2, RegState::Kill)
6102 MachineMemOperand *JTMMOLd =
6103 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6104 MachineMemOperand::MOLoad, 4, 4);
6106 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6107 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6108 .addReg(NewVReg4, RegState::Kill)
6110 .addMemOperand(JTMMOLd));
6112 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6113 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6114 .addReg(ARM::CPSR, RegState::Define)
6115 .addReg(NewVReg5, RegState::Kill)
6118 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6119 .addReg(NewVReg6, RegState::Kill)
6120 .addJumpTableIndex(MJTI)
6123 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6124 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6127 .addMemOperand(FIMMOLd));
6129 if (NumLPads < 256) {
6130 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6133 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6134 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6135 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6136 .addImm(NumLPads & 0xFFFF));
6138 unsigned VReg2 = VReg1;
6139 if ((NumLPads & 0xFFFF0000) != 0) {
6140 VReg2 = MRI->createVirtualRegister(TRC);
6141 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6143 .addImm(NumLPads >> 16));
6146 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6150 MachineConstantPool *ConstantPool = MF->getConstantPool();
6151 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6152 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6154 // MachineConstantPool wants an explicit alignment.
6155 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6157 Align = getTargetData()->getTypeAllocSize(C->getType());
6158 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6160 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6161 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6162 .addReg(VReg1, RegState::Define)
6163 .addConstantPoolIndex(Idx)
6165 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6167 .addReg(VReg1, RegState::Kill));
6170 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6175 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6177 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6179 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6180 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6181 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6182 .addJumpTableIndex(MJTI)
6185 MachineMemOperand *JTMMOLd =
6186 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6187 MachineMemOperand::MOLoad, 4, 4);
6188 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6190 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6191 .addReg(NewVReg3, RegState::Kill)
6194 .addMemOperand(JTMMOLd));
6196 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6197 .addReg(NewVReg5, RegState::Kill)
6199 .addJumpTableIndex(MJTI)
6203 // Add the jump table entries as successors to the MBB.
6204 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6205 for (std::vector<MachineBasicBlock*>::iterator
6206 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6207 MachineBasicBlock *CurMBB = *I;
6208 if (SeenMBBs.insert(CurMBB))
6209 DispContBB->addSuccessor(CurMBB);
6212 // N.B. the order the invoke BBs are processed in doesn't matter here.
6213 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6214 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6215 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6216 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6217 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6218 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6219 MachineBasicBlock *BB = *I;
6221 // Remove the landing pad successor from the invoke block and replace it
6222 // with the new dispatch block.
6223 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6225 while (!Successors.empty()) {
6226 MachineBasicBlock *SMBB = Successors.pop_back_val();
6227 if (SMBB->isLandingPad()) {
6228 BB->removeSuccessor(SMBB);
6229 MBBLPads.push_back(SMBB);
6233 BB->addSuccessor(DispatchBB);
6235 // Find the invoke call and mark all of the callee-saved registers as
6236 // 'implicit defined' so that they're spilled. This prevents code from
6237 // moving instructions to before the EH block, where they will never be
6239 for (MachineBasicBlock::reverse_iterator
6240 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6241 if (!II->isCall()) continue;
6243 DenseMap<unsigned, bool> DefRegs;
6244 for (MachineInstr::mop_iterator
6245 OI = II->operands_begin(), OE = II->operands_end();
6247 if (!OI->isReg()) continue;
6248 DefRegs[OI->getReg()] = true;
6251 MachineInstrBuilder MIB(&*II);
6253 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6254 unsigned Reg = SavedRegs[i];
6255 if (Subtarget->isThumb2() &&
6256 !ARM::tGPRRegClass.contains(Reg) &&
6257 !ARM::hGPRRegClass.contains(Reg))
6259 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6261 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6264 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6271 // Mark all former landing pads as non-landing pads. The dispatch is the only
6273 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6274 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6275 (*I)->setIsLandingPad(false);
6277 // The instruction is gone now.
6278 MI->eraseFromParent();
6284 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6285 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6286 E = MBB->succ_end(); I != E; ++I)
6289 llvm_unreachable("Expecting a BB with two successors!");
6292 MachineBasicBlock *ARMTargetLowering::
6293 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6294 // This pseudo instruction has 3 operands: dst, src, size
6295 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6296 // Otherwise, we will generate unrolled scalar copies.
6297 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6298 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6299 MachineFunction::iterator It = BB;
6302 unsigned dest = MI->getOperand(0).getReg();
6303 unsigned src = MI->getOperand(1).getReg();
6304 unsigned SizeVal = MI->getOperand(2).getImm();
6305 unsigned Align = MI->getOperand(3).getImm();
6306 DebugLoc dl = MI->getDebugLoc();
6308 bool isThumb2 = Subtarget->isThumb2();
6309 MachineFunction *MF = BB->getParent();
6310 MachineRegisterInfo &MRI = MF->getRegInfo();
6311 unsigned ldrOpc, strOpc, UnitSize = 0;
6313 const TargetRegisterClass *TRC = isThumb2 ?
6314 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6315 (const TargetRegisterClass*)&ARM::GPRRegClass;
6316 const TargetRegisterClass *TRC_Vec = 0;
6319 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6320 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6322 } else if (Align & 2) {
6323 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6324 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6327 // Check whether we can use NEON instructions.
6328 if (!MF->getFunction()->hasFnAttr(Attribute::NoImplicitFloat) &&
6329 Subtarget->hasNEON()) {
6330 if ((Align % 16 == 0) && SizeVal >= 16) {
6331 ldrOpc = ARM::VLD1q32wb_fixed;
6332 strOpc = ARM::VST1q32wb_fixed;
6334 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6336 else if ((Align % 8 == 0) && SizeVal >= 8) {
6337 ldrOpc = ARM::VLD1d32wb_fixed;
6338 strOpc = ARM::VST1d32wb_fixed;
6340 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6343 // Can't use NEON instructions.
6344 if (UnitSize == 0) {
6345 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6346 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6351 unsigned BytesLeft = SizeVal % UnitSize;
6352 unsigned LoopSize = SizeVal - BytesLeft;
6354 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6355 // Use LDR and STR to copy.
6356 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6357 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6358 unsigned srcIn = src;
6359 unsigned destIn = dest;
6360 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6361 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6362 unsigned srcOut = MRI.createVirtualRegister(TRC);
6363 unsigned destOut = MRI.createVirtualRegister(TRC);
6364 if (UnitSize >= 8) {
6365 AddDefaultPred(BuildMI(*BB, MI, dl,
6366 TII->get(ldrOpc), scratch)
6367 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6369 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6370 .addReg(destIn).addImm(0).addReg(scratch));
6371 } else if (isThumb2) {
6372 AddDefaultPred(BuildMI(*BB, MI, dl,
6373 TII->get(ldrOpc), scratch)
6374 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6376 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6377 .addReg(scratch).addReg(destIn)
6380 AddDefaultPred(BuildMI(*BB, MI, dl,
6381 TII->get(ldrOpc), scratch)
6382 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6385 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6386 .addReg(scratch).addReg(destIn)
6387 .addReg(0).addImm(UnitSize));
6393 // Handle the leftover bytes with LDRB and STRB.
6394 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6395 // [destOut] = STRB_POST(scratch, destIn, 1)
6396 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6397 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6398 for (unsigned i = 0; i < BytesLeft; i++) {
6399 unsigned scratch = MRI.createVirtualRegister(TRC);
6400 unsigned srcOut = MRI.createVirtualRegister(TRC);
6401 unsigned destOut = MRI.createVirtualRegister(TRC);
6403 AddDefaultPred(BuildMI(*BB, MI, dl,
6404 TII->get(ldrOpc),scratch)
6405 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6407 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6408 .addReg(scratch).addReg(destIn)
6409 .addReg(0).addImm(1));
6411 AddDefaultPred(BuildMI(*BB, MI, dl,
6412 TII->get(ldrOpc),scratch)
6413 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6415 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6416 .addReg(scratch).addReg(destIn)
6417 .addReg(0).addImm(1));
6422 MI->eraseFromParent(); // The instruction is gone now.
6426 // Expand the pseudo op to a loop.
6429 // movw varEnd, # --> with thumb2
6431 // ldrcp varEnd, idx --> without thumb2
6432 // fallthrough --> loopMBB
6434 // PHI varPhi, varEnd, varLoop
6435 // PHI srcPhi, src, srcLoop
6436 // PHI destPhi, dst, destLoop
6437 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6438 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6439 // subs varLoop, varPhi, #UnitSize
6441 // fallthrough --> exitMBB
6443 // epilogue to handle left-over bytes
6444 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6445 // [destOut] = STRB_POST(scratch, destLoop, 1)
6446 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6447 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6448 MF->insert(It, loopMBB);
6449 MF->insert(It, exitMBB);
6451 // Transfer the remainder of BB and its successor edges to exitMBB.
6452 exitMBB->splice(exitMBB->begin(), BB,
6453 llvm::next(MachineBasicBlock::iterator(MI)),
6455 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6457 // Load an immediate to varEnd.
6458 unsigned varEnd = MRI.createVirtualRegister(TRC);
6460 unsigned VReg1 = varEnd;
6461 if ((LoopSize & 0xFFFF0000) != 0)
6462 VReg1 = MRI.createVirtualRegister(TRC);
6463 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6464 .addImm(LoopSize & 0xFFFF));
6466 if ((LoopSize & 0xFFFF0000) != 0)
6467 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6469 .addImm(LoopSize >> 16));
6471 MachineConstantPool *ConstantPool = MF->getConstantPool();
6472 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6473 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6475 // MachineConstantPool wants an explicit alignment.
6476 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6478 Align = getTargetData()->getTypeAllocSize(C->getType());
6479 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6481 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6482 .addReg(varEnd, RegState::Define)
6483 .addConstantPoolIndex(Idx)
6486 BB->addSuccessor(loopMBB);
6488 // Generate the loop body:
6489 // varPhi = PHI(varLoop, varEnd)
6490 // srcPhi = PHI(srcLoop, src)
6491 // destPhi = PHI(destLoop, dst)
6492 MachineBasicBlock *entryBB = BB;
6494 unsigned varLoop = MRI.createVirtualRegister(TRC);
6495 unsigned varPhi = MRI.createVirtualRegister(TRC);
6496 unsigned srcLoop = MRI.createVirtualRegister(TRC);
6497 unsigned srcPhi = MRI.createVirtualRegister(TRC);
6498 unsigned destLoop = MRI.createVirtualRegister(TRC);
6499 unsigned destPhi = MRI.createVirtualRegister(TRC);
6501 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6502 .addReg(varLoop).addMBB(loopMBB)
6503 .addReg(varEnd).addMBB(entryBB);
6504 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6505 .addReg(srcLoop).addMBB(loopMBB)
6506 .addReg(src).addMBB(entryBB);
6507 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6508 .addReg(destLoop).addMBB(loopMBB)
6509 .addReg(dest).addMBB(entryBB);
6511 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6512 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6513 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6514 if (UnitSize >= 8) {
6515 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6516 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6518 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6519 .addReg(destPhi).addImm(0).addReg(scratch));
6520 } else if (isThumb2) {
6521 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6522 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6524 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6525 .addReg(scratch).addReg(destPhi)
6528 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6529 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6532 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6533 .addReg(scratch).addReg(destPhi)
6534 .addReg(0).addImm(UnitSize));
6537 // Decrement loop variable by UnitSize.
6538 MachineInstrBuilder MIB = BuildMI(BB, dl,
6539 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6540 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6541 MIB->getOperand(5).setReg(ARM::CPSR);
6542 MIB->getOperand(5).setIsDef(true);
6544 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6545 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6547 // loopMBB can loop back to loopMBB or fall through to exitMBB.
6548 BB->addSuccessor(loopMBB);
6549 BB->addSuccessor(exitMBB);
6551 // Add epilogue to handle BytesLeft.
6553 MachineInstr *StartOfExit = exitMBB->begin();
6554 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6555 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6557 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6558 // [destOut] = STRB_POST(scratch, destLoop, 1)
6559 unsigned srcIn = srcLoop;
6560 unsigned destIn = destLoop;
6561 for (unsigned i = 0; i < BytesLeft; i++) {
6562 unsigned scratch = MRI.createVirtualRegister(TRC);
6563 unsigned srcOut = MRI.createVirtualRegister(TRC);
6564 unsigned destOut = MRI.createVirtualRegister(TRC);
6566 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6567 TII->get(ldrOpc),scratch)
6568 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6570 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6571 .addReg(scratch).addReg(destIn)
6574 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6575 TII->get(ldrOpc),scratch)
6576 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6578 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6579 .addReg(scratch).addReg(destIn)
6580 .addReg(0).addImm(1));
6586 MI->eraseFromParent(); // The instruction is gone now.
6591 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6592 MachineBasicBlock *BB) const {
6593 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6594 DebugLoc dl = MI->getDebugLoc();
6595 bool isThumb2 = Subtarget->isThumb2();
6596 switch (MI->getOpcode()) {
6599 llvm_unreachable("Unexpected instr type to insert");
6601 // The Thumb2 pre-indexed stores have the same MI operands, they just
6602 // define them differently in the .td files from the isel patterns, so
6603 // they need pseudos.
6604 case ARM::t2STR_preidx:
6605 MI->setDesc(TII->get(ARM::t2STR_PRE));
6607 case ARM::t2STRB_preidx:
6608 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6610 case ARM::t2STRH_preidx:
6611 MI->setDesc(TII->get(ARM::t2STRH_PRE));
6614 case ARM::STRi_preidx:
6615 case ARM::STRBi_preidx: {
6616 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6617 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6618 // Decode the offset.
6619 unsigned Offset = MI->getOperand(4).getImm();
6620 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6621 Offset = ARM_AM::getAM2Offset(Offset);
6625 MachineMemOperand *MMO = *MI->memoperands_begin();
6626 BuildMI(*BB, MI, dl, TII->get(NewOpc))
6627 .addOperand(MI->getOperand(0)) // Rn_wb
6628 .addOperand(MI->getOperand(1)) // Rt
6629 .addOperand(MI->getOperand(2)) // Rn
6630 .addImm(Offset) // offset (skip GPR==zero_reg)
6631 .addOperand(MI->getOperand(5)) // pred
6632 .addOperand(MI->getOperand(6))
6633 .addMemOperand(MMO);
6634 MI->eraseFromParent();
6637 case ARM::STRr_preidx:
6638 case ARM::STRBr_preidx:
6639 case ARM::STRH_preidx: {
6641 switch (MI->getOpcode()) {
6642 default: llvm_unreachable("unexpected opcode!");
6643 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6644 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6645 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6647 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6648 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6649 MIB.addOperand(MI->getOperand(i));
6650 MI->eraseFromParent();
6653 case ARM::ATOMIC_LOAD_ADD_I8:
6654 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6655 case ARM::ATOMIC_LOAD_ADD_I16:
6656 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6657 case ARM::ATOMIC_LOAD_ADD_I32:
6658 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6660 case ARM::ATOMIC_LOAD_AND_I8:
6661 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6662 case ARM::ATOMIC_LOAD_AND_I16:
6663 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6664 case ARM::ATOMIC_LOAD_AND_I32:
6665 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6667 case ARM::ATOMIC_LOAD_OR_I8:
6668 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6669 case ARM::ATOMIC_LOAD_OR_I16:
6670 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6671 case ARM::ATOMIC_LOAD_OR_I32:
6672 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6674 case ARM::ATOMIC_LOAD_XOR_I8:
6675 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6676 case ARM::ATOMIC_LOAD_XOR_I16:
6677 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6678 case ARM::ATOMIC_LOAD_XOR_I32:
6679 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6681 case ARM::ATOMIC_LOAD_NAND_I8:
6682 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6683 case ARM::ATOMIC_LOAD_NAND_I16:
6684 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6685 case ARM::ATOMIC_LOAD_NAND_I32:
6686 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6688 case ARM::ATOMIC_LOAD_SUB_I8:
6689 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6690 case ARM::ATOMIC_LOAD_SUB_I16:
6691 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6692 case ARM::ATOMIC_LOAD_SUB_I32:
6693 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6695 case ARM::ATOMIC_LOAD_MIN_I8:
6696 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6697 case ARM::ATOMIC_LOAD_MIN_I16:
6698 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6699 case ARM::ATOMIC_LOAD_MIN_I32:
6700 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6702 case ARM::ATOMIC_LOAD_MAX_I8:
6703 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6704 case ARM::ATOMIC_LOAD_MAX_I16:
6705 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6706 case ARM::ATOMIC_LOAD_MAX_I32:
6707 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6709 case ARM::ATOMIC_LOAD_UMIN_I8:
6710 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6711 case ARM::ATOMIC_LOAD_UMIN_I16:
6712 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6713 case ARM::ATOMIC_LOAD_UMIN_I32:
6714 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6716 case ARM::ATOMIC_LOAD_UMAX_I8:
6717 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6718 case ARM::ATOMIC_LOAD_UMAX_I16:
6719 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6720 case ARM::ATOMIC_LOAD_UMAX_I32:
6721 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6723 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
6724 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6725 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6727 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
6728 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6729 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6732 case ARM::ATOMADD6432:
6733 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6734 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6735 /*NeedsCarry*/ true);
6736 case ARM::ATOMSUB6432:
6737 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6738 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6739 /*NeedsCarry*/ true);
6740 case ARM::ATOMOR6432:
6741 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6742 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6743 case ARM::ATOMXOR6432:
6744 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6745 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6746 case ARM::ATOMAND6432:
6747 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6748 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6749 case ARM::ATOMSWAP6432:
6750 return EmitAtomicBinary64(MI, BB, 0, 0, false);
6751 case ARM::ATOMCMPXCHG6432:
6752 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6753 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6754 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6756 case ARM::tMOVCCr_pseudo: {
6757 // To "insert" a SELECT_CC instruction, we actually have to insert the
6758 // diamond control-flow pattern. The incoming instruction knows the
6759 // destination vreg to set, the condition code register to branch on, the
6760 // true/false values to select between, and a branch opcode to use.
6761 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6762 MachineFunction::iterator It = BB;
6768 // cmpTY ccX, r1, r2
6770 // fallthrough --> copy0MBB
6771 MachineBasicBlock *thisMBB = BB;
6772 MachineFunction *F = BB->getParent();
6773 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6774 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6775 F->insert(It, copy0MBB);
6776 F->insert(It, sinkMBB);
6778 // Transfer the remainder of BB and its successor edges to sinkMBB.
6779 sinkMBB->splice(sinkMBB->begin(), BB,
6780 llvm::next(MachineBasicBlock::iterator(MI)),
6782 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6784 BB->addSuccessor(copy0MBB);
6785 BB->addSuccessor(sinkMBB);
6787 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6788 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6791 // %FalseValue = ...
6792 // # fallthrough to sinkMBB
6795 // Update machine-CFG edges
6796 BB->addSuccessor(sinkMBB);
6799 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6802 BuildMI(*BB, BB->begin(), dl,
6803 TII->get(ARM::PHI), MI->getOperand(0).getReg())
6804 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6805 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6807 MI->eraseFromParent(); // The pseudo instruction is gone now.
6812 case ARM::BCCZi64: {
6813 // If there is an unconditional branch to the other successor, remove it.
6814 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6816 // Compare both parts that make up the double comparison separately for
6818 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6820 unsigned LHS1 = MI->getOperand(1).getReg();
6821 unsigned LHS2 = MI->getOperand(2).getReg();
6823 AddDefaultPred(BuildMI(BB, dl,
6824 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6825 .addReg(LHS1).addImm(0));
6826 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6827 .addReg(LHS2).addImm(0)
6828 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6830 unsigned RHS1 = MI->getOperand(3).getReg();
6831 unsigned RHS2 = MI->getOperand(4).getReg();
6832 AddDefaultPred(BuildMI(BB, dl,
6833 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6834 .addReg(LHS1).addReg(RHS1));
6835 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6836 .addReg(LHS2).addReg(RHS2)
6837 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6840 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6841 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6842 if (MI->getOperand(0).getImm() == ARMCC::NE)
6843 std::swap(destMBB, exitMBB);
6845 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6846 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6848 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6850 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6852 MI->eraseFromParent(); // The pseudo instruction is gone now.
6856 case ARM::Int_eh_sjlj_setjmp:
6857 case ARM::Int_eh_sjlj_setjmp_nofp:
6858 case ARM::tInt_eh_sjlj_setjmp:
6859 case ARM::t2Int_eh_sjlj_setjmp:
6860 case ARM::t2Int_eh_sjlj_setjmp_nofp:
6861 EmitSjLjDispatchBlock(MI, BB);
6866 // To insert an ABS instruction, we have to insert the
6867 // diamond control-flow pattern. The incoming instruction knows the
6868 // source vreg to test against 0, the destination vreg to set,
6869 // the condition code register to branch on, the
6870 // true/false values to select between, and a branch opcode to use.
6875 // BCC (branch to SinkBB if V0 >= 0)
6876 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
6877 // SinkBB: V1 = PHI(V2, V3)
6878 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6879 MachineFunction::iterator BBI = BB;
6881 MachineFunction *Fn = BB->getParent();
6882 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6883 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6884 Fn->insert(BBI, RSBBB);
6885 Fn->insert(BBI, SinkBB);
6887 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6888 unsigned int ABSDstReg = MI->getOperand(0).getReg();
6889 bool isThumb2 = Subtarget->isThumb2();
6890 MachineRegisterInfo &MRI = Fn->getRegInfo();
6891 // In Thumb mode S must not be specified if source register is the SP or
6892 // PC and if destination register is the SP, so restrict register class
6893 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6894 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6895 (const TargetRegisterClass*)&ARM::GPRRegClass);
6897 // Transfer the remainder of BB and its successor edges to sinkMBB.
6898 SinkBB->splice(SinkBB->begin(), BB,
6899 llvm::next(MachineBasicBlock::iterator(MI)),
6901 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6903 BB->addSuccessor(RSBBB);
6904 BB->addSuccessor(SinkBB);
6906 // fall through to SinkMBB
6907 RSBBB->addSuccessor(SinkBB);
6909 // insert a cmp at the end of BB
6910 AddDefaultPred(BuildMI(BB, dl,
6911 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6912 .addReg(ABSSrcReg).addImm(0));
6914 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6916 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6917 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6919 // insert rsbri in RSBBB
6920 // Note: BCC and rsbri will be converted into predicated rsbmi
6921 // by if-conversion pass
6922 BuildMI(*RSBBB, RSBBB->begin(), dl,
6923 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6924 .addReg(ABSSrcReg, RegState::Kill)
6925 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6927 // insert PHI in SinkBB,
6928 // reuse ABSDstReg to not change uses of ABS instruction
6929 BuildMI(*SinkBB, SinkBB->begin(), dl,
6930 TII->get(ARM::PHI), ABSDstReg)
6931 .addReg(NewRsbDstReg).addMBB(RSBBB)
6932 .addReg(ABSSrcReg).addMBB(BB);
6934 // remove ABS instruction
6935 MI->eraseFromParent();
6937 // return last added BB
6940 case ARM::COPY_STRUCT_BYVAL_I32:
6942 return EmitStructByval(MI, BB);
6946 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6947 SDNode *Node) const {
6948 if (!MI->hasPostISelHook()) {
6949 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6950 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6954 const MCInstrDesc *MCID = &MI->getDesc();
6955 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6956 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6957 // operand is still set to noreg. If needed, set the optional operand's
6958 // register to CPSR, and remove the redundant implicit def.
6960 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6962 // Rename pseudo opcodes.
6963 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6965 const ARMBaseInstrInfo *TII =
6966 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6967 MCID = &TII->get(NewOpc);
6969 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6970 "converted opcode should be the same except for cc_out");
6974 // Add the optional cc_out operand
6975 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6977 unsigned ccOutIdx = MCID->getNumOperands() - 1;
6979 // Any ARM instruction that sets the 's' bit should specify an optional
6980 // "cc_out" operand in the last operand position.
6981 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6982 assert(!NewOpc && "Optional cc_out operand required");
6985 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6986 // since we already have an optional CPSR def.
6987 bool definesCPSR = false;
6988 bool deadCPSR = false;
6989 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6991 const MachineOperand &MO = MI->getOperand(i);
6992 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6996 MI->RemoveOperand(i);
7001 assert(!NewOpc && "Optional cc_out operand required");
7004 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7006 assert(!MI->getOperand(ccOutIdx).getReg() &&
7007 "expect uninitialized optional cc_out operand");
7011 // If this instruction was defined with an optional CPSR def and its dag node
7012 // had a live implicit CPSR def, then activate the optional CPSR def.
7013 MachineOperand &MO = MI->getOperand(ccOutIdx);
7014 MO.setReg(ARM::CPSR);
7018 //===----------------------------------------------------------------------===//
7019 // ARM Optimization Hooks
7020 //===----------------------------------------------------------------------===//
7022 // Helper function that checks if N is a null or all ones constant.
7023 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7024 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7027 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7030 // Return true if N is conditionally 0 or all ones.
7031 // Detects these expressions where cc is an i1 value:
7033 // (select cc 0, y) [AllOnes=0]
7034 // (select cc y, 0) [AllOnes=0]
7035 // (zext cc) [AllOnes=0]
7036 // (sext cc) [AllOnes=0/1]
7037 // (select cc -1, y) [AllOnes=1]
7038 // (select cc y, -1) [AllOnes=1]
7040 // Invert is set when N is the null/all ones constant when CC is false.
7041 // OtherOp is set to the alternative value of N.
7042 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7043 SDValue &CC, bool &Invert,
7045 SelectionDAG &DAG) {
7046 switch (N->getOpcode()) {
7047 default: return false;
7049 CC = N->getOperand(0);
7050 SDValue N1 = N->getOperand(1);
7051 SDValue N2 = N->getOperand(2);
7052 if (isZeroOrAllOnes(N1, AllOnes)) {
7057 if (isZeroOrAllOnes(N2, AllOnes)) {
7064 case ISD::ZERO_EXTEND:
7065 // (zext cc) can never be the all ones value.
7069 case ISD::SIGN_EXTEND: {
7070 EVT VT = N->getValueType(0);
7071 CC = N->getOperand(0);
7072 if (CC.getValueType() != MVT::i1)
7076 // When looking for an AllOnes constant, N is an sext, and the 'other'
7078 OtherOp = DAG.getConstant(0, VT);
7079 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7080 // When looking for a 0 constant, N can be zext or sext.
7081 OtherOp = DAG.getConstant(1, VT);
7083 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7089 // Combine a constant select operand into its use:
7091 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7092 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7093 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7094 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7095 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7097 // The transform is rejected if the select doesn't have a constant operand that
7098 // is null, or all ones when AllOnes is set.
7100 // Also recognize sext/zext from i1:
7102 // (add (zext cc), x) -> (select cc (add x, 1), x)
7103 // (add (sext cc), x) -> (select cc (add x, -1), x)
7105 // These transformations eventually create predicated instructions.
7107 // @param N The node to transform.
7108 // @param Slct The N operand that is a select.
7109 // @param OtherOp The other N operand (x above).
7110 // @param DCI Context.
7111 // @param AllOnes Require the select constant to be all ones instead of null.
7112 // @returns The new node, or SDValue() on failure.
7114 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7115 TargetLowering::DAGCombinerInfo &DCI,
7116 bool AllOnes = false) {
7117 SelectionDAG &DAG = DCI.DAG;
7118 EVT VT = N->getValueType(0);
7119 SDValue NonConstantVal;
7122 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7123 NonConstantVal, DAG))
7126 // Slct is now know to be the desired identity constant when CC is true.
7127 SDValue TrueVal = OtherOp;
7128 SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7129 OtherOp, NonConstantVal);
7130 // Unless SwapSelectOps says CC should be false.
7132 std::swap(TrueVal, FalseVal);
7134 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7135 CCOp, TrueVal, FalseVal);
7138 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7140 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7141 TargetLowering::DAGCombinerInfo &DCI) {
7142 SDValue N0 = N->getOperand(0);
7143 SDValue N1 = N->getOperand(1);
7144 if (N0.getNode()->hasOneUse()) {
7145 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7146 if (Result.getNode())
7149 if (N1.getNode()->hasOneUse()) {
7150 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7151 if (Result.getNode())
7157 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7158 // (only after legalization).
7159 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7160 TargetLowering::DAGCombinerInfo &DCI,
7161 const ARMSubtarget *Subtarget) {
7163 // Only perform optimization if after legalize, and if NEON is available. We
7164 // also expected both operands to be BUILD_VECTORs.
7165 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7166 || N0.getOpcode() != ISD::BUILD_VECTOR
7167 || N1.getOpcode() != ISD::BUILD_VECTOR)
7170 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7171 EVT VT = N->getValueType(0);
7172 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7175 // Check that the vector operands are of the right form.
7176 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7177 // operands, where N is the size of the formed vector.
7178 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7179 // index such that we have a pair wise add pattern.
7181 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7182 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7184 SDValue Vec = N0->getOperand(0)->getOperand(0);
7185 SDNode *V = Vec.getNode();
7186 unsigned nextIndex = 0;
7188 // For each operands to the ADD which are BUILD_VECTORs,
7189 // check to see if each of their operands are an EXTRACT_VECTOR with
7190 // the same vector and appropriate index.
7191 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7192 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7193 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7195 SDValue ExtVec0 = N0->getOperand(i);
7196 SDValue ExtVec1 = N1->getOperand(i);
7198 // First operand is the vector, verify its the same.
7199 if (V != ExtVec0->getOperand(0).getNode() ||
7200 V != ExtVec1->getOperand(0).getNode())
7203 // Second is the constant, verify its correct.
7204 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7205 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7207 // For the constant, we want to see all the even or all the odd.
7208 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7209 || C1->getZExtValue() != nextIndex+1)
7218 // Create VPADDL node.
7219 SelectionDAG &DAG = DCI.DAG;
7220 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7222 // Build operand list.
7223 SmallVector<SDValue, 8> Ops;
7224 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7225 TLI.getPointerTy()));
7227 // Input is the vector.
7230 // Get widened type and narrowed type.
7232 unsigned numElem = VT.getVectorNumElements();
7233 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7234 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7235 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7236 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7238 llvm_unreachable("Invalid vector element type for padd optimization.");
7241 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7242 widenType, &Ops[0], Ops.size());
7243 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7246 static SDValue findMUL_LOHI(SDValue V) {
7247 if (V->getOpcode() == ISD::UMUL_LOHI ||
7248 V->getOpcode() == ISD::SMUL_LOHI)
7253 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7254 TargetLowering::DAGCombinerInfo &DCI,
7255 const ARMSubtarget *Subtarget) {
7257 if (Subtarget->isThumb1Only()) return SDValue();
7259 // Only perform the checks after legalize when the pattern is available.
7260 if (DCI.isBeforeLegalize()) return SDValue();
7262 // Look for multiply add opportunities.
7263 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7264 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7265 // a glue link from the first add to the second add.
7266 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7267 // a S/UMLAL instruction.
7270 // \ / \ [no multiline comment]
7276 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7277 SDValue AddcOp0 = AddcNode->getOperand(0);
7278 SDValue AddcOp1 = AddcNode->getOperand(1);
7280 // Check if the two operands are from the same mul_lohi node.
7281 if (AddcOp0.getNode() == AddcOp1.getNode())
7284 assert(AddcNode->getNumValues() == 2 &&
7285 AddcNode->getValueType(0) == MVT::i32 &&
7286 AddcNode->getValueType(1) == MVT::Glue &&
7287 "Expect ADDC with two result values: i32, glue");
7289 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7290 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7291 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7292 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7293 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7296 // Look for the glued ADDE.
7297 SDNode* AddeNode = AddcNode->getGluedUser();
7298 if (AddeNode == NULL)
7301 // Make sure it is really an ADDE.
7302 if (AddeNode->getOpcode() != ISD::ADDE)
7305 assert(AddeNode->getNumOperands() == 3 &&
7306 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7307 "ADDE node has the wrong inputs");
7309 // Check for the triangle shape.
7310 SDValue AddeOp0 = AddeNode->getOperand(0);
7311 SDValue AddeOp1 = AddeNode->getOperand(1);
7313 // Make sure that the ADDE operands are not coming from the same node.
7314 if (AddeOp0.getNode() == AddeOp1.getNode())
7317 // Find the MUL_LOHI node walking up ADDE's operands.
7318 bool IsLeftOperandMUL = false;
7319 SDValue MULOp = findMUL_LOHI(AddeOp0);
7320 if (MULOp == SDValue())
7321 MULOp = findMUL_LOHI(AddeOp1);
7323 IsLeftOperandMUL = true;
7324 if (MULOp == SDValue())
7327 // Figure out the right opcode.
7328 unsigned Opc = MULOp->getOpcode();
7329 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7331 // Figure out the high and low input values to the MLAL node.
7332 SDValue* HiMul = &MULOp;
7333 SDValue* HiAdd = NULL;
7334 SDValue* LoMul = NULL;
7335 SDValue* LowAdd = NULL;
7337 if (IsLeftOperandMUL)
7343 if (AddcOp0->getOpcode() == Opc) {
7347 if (AddcOp1->getOpcode() == Opc) {
7355 if (LoMul->getNode() != HiMul->getNode())
7358 // Create the merged node.
7359 SelectionDAG &DAG = DCI.DAG;
7361 // Build operand list.
7362 SmallVector<SDValue, 8> Ops;
7363 Ops.push_back(LoMul->getOperand(0));
7364 Ops.push_back(LoMul->getOperand(1));
7365 Ops.push_back(*LowAdd);
7366 Ops.push_back(*HiAdd);
7368 SDValue MLALNode = DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7369 DAG.getVTList(MVT::i32, MVT::i32),
7370 &Ops[0], Ops.size());
7372 // Replace the ADDs' nodes uses by the MLA node's values.
7373 SDValue HiMLALResult(MLALNode.getNode(), 1);
7374 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7376 SDValue LoMLALResult(MLALNode.getNode(), 0);
7377 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7379 // Return original node to notify the driver to stop replacing.
7380 SDValue resNode(AddcNode, 0);
7384 /// PerformADDCCombine - Target-specific dag combine transform from
7385 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7386 static SDValue PerformADDCCombine(SDNode *N,
7387 TargetLowering::DAGCombinerInfo &DCI,
7388 const ARMSubtarget *Subtarget) {
7390 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7394 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7395 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7396 /// called with the default operands, and if that fails, with commuted
7398 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7399 TargetLowering::DAGCombinerInfo &DCI,
7400 const ARMSubtarget *Subtarget){
7402 // Attempt to create vpaddl for this add.
7403 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7404 if (Result.getNode())
7407 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7408 if (N0.getNode()->hasOneUse()) {
7409 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7410 if (Result.getNode()) return Result;
7415 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7417 static SDValue PerformADDCombine(SDNode *N,
7418 TargetLowering::DAGCombinerInfo &DCI,
7419 const ARMSubtarget *Subtarget) {
7420 SDValue N0 = N->getOperand(0);
7421 SDValue N1 = N->getOperand(1);
7423 // First try with the default operand order.
7424 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7425 if (Result.getNode())
7428 // If that didn't work, try again with the operands commuted.
7429 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7432 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7434 static SDValue PerformSUBCombine(SDNode *N,
7435 TargetLowering::DAGCombinerInfo &DCI) {
7436 SDValue N0 = N->getOperand(0);
7437 SDValue N1 = N->getOperand(1);
7439 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7440 if (N1.getNode()->hasOneUse()) {
7441 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7442 if (Result.getNode()) return Result;
7448 /// PerformVMULCombine
7449 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7450 /// special multiplier accumulator forwarding.
7456 static SDValue PerformVMULCombine(SDNode *N,
7457 TargetLowering::DAGCombinerInfo &DCI,
7458 const ARMSubtarget *Subtarget) {
7459 if (!Subtarget->hasVMLxForwarding())
7462 SelectionDAG &DAG = DCI.DAG;
7463 SDValue N0 = N->getOperand(0);
7464 SDValue N1 = N->getOperand(1);
7465 unsigned Opcode = N0.getOpcode();
7466 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7467 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7468 Opcode = N1.getOpcode();
7469 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7470 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7475 EVT VT = N->getValueType(0);
7476 DebugLoc DL = N->getDebugLoc();
7477 SDValue N00 = N0->getOperand(0);
7478 SDValue N01 = N0->getOperand(1);
7479 return DAG.getNode(Opcode, DL, VT,
7480 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7481 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7484 static SDValue PerformMULCombine(SDNode *N,
7485 TargetLowering::DAGCombinerInfo &DCI,
7486 const ARMSubtarget *Subtarget) {
7487 SelectionDAG &DAG = DCI.DAG;
7489 if (Subtarget->isThumb1Only())
7492 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7495 EVT VT = N->getValueType(0);
7496 if (VT.is64BitVector() || VT.is128BitVector())
7497 return PerformVMULCombine(N, DCI, Subtarget);
7501 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7505 int64_t MulAmt = C->getSExtValue();
7506 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7508 ShiftAmt = ShiftAmt & (32 - 1);
7509 SDValue V = N->getOperand(0);
7510 DebugLoc DL = N->getDebugLoc();
7513 MulAmt >>= ShiftAmt;
7516 if (isPowerOf2_32(MulAmt - 1)) {
7517 // (mul x, 2^N + 1) => (add (shl x, N), x)
7518 Res = DAG.getNode(ISD::ADD, DL, VT,
7520 DAG.getNode(ISD::SHL, DL, VT,
7522 DAG.getConstant(Log2_32(MulAmt - 1),
7524 } else if (isPowerOf2_32(MulAmt + 1)) {
7525 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7526 Res = DAG.getNode(ISD::SUB, DL, VT,
7527 DAG.getNode(ISD::SHL, DL, VT,
7529 DAG.getConstant(Log2_32(MulAmt + 1),
7535 uint64_t MulAmtAbs = -MulAmt;
7536 if (isPowerOf2_32(MulAmtAbs + 1)) {
7537 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7538 Res = DAG.getNode(ISD::SUB, DL, VT,
7540 DAG.getNode(ISD::SHL, DL, VT,
7542 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7544 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7545 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7546 Res = DAG.getNode(ISD::ADD, DL, VT,
7548 DAG.getNode(ISD::SHL, DL, VT,
7550 DAG.getConstant(Log2_32(MulAmtAbs-1),
7552 Res = DAG.getNode(ISD::SUB, DL, VT,
7553 DAG.getConstant(0, MVT::i32),Res);
7560 Res = DAG.getNode(ISD::SHL, DL, VT,
7561 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7563 // Do not add new nodes to DAG combiner worklist.
7564 DCI.CombineTo(N, Res, false);
7568 static SDValue PerformANDCombine(SDNode *N,
7569 TargetLowering::DAGCombinerInfo &DCI,
7570 const ARMSubtarget *Subtarget) {
7572 // Attempt to use immediate-form VBIC
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;
7585 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7586 if (SplatBitSize <= 64) {
7588 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7589 SplatUndef.getZExtValue(), SplatBitSize,
7590 DAG, VbicVT, VT.is128BitVector(),
7592 if (Val.getNode()) {
7594 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7595 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7596 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7601 if (!Subtarget->isThumb1Only()) {
7602 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7603 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7604 if (Result.getNode())
7611 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7612 static SDValue PerformORCombine(SDNode *N,
7613 TargetLowering::DAGCombinerInfo &DCI,
7614 const ARMSubtarget *Subtarget) {
7615 // Attempt to use immediate-form VORR
7616 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7617 DebugLoc dl = N->getDebugLoc();
7618 EVT VT = N->getValueType(0);
7619 SelectionDAG &DAG = DCI.DAG;
7621 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7624 APInt SplatBits, SplatUndef;
7625 unsigned SplatBitSize;
7627 if (BVN && Subtarget->hasNEON() &&
7628 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7629 if (SplatBitSize <= 64) {
7631 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7632 SplatUndef.getZExtValue(), SplatBitSize,
7633 DAG, VorrVT, VT.is128BitVector(),
7635 if (Val.getNode()) {
7637 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7638 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7639 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7644 if (!Subtarget->isThumb1Only()) {
7645 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7646 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7647 if (Result.getNode())
7651 // The code below optimizes (or (and X, Y), Z).
7652 // The AND operand needs to have a single user to make these optimizations
7654 SDValue N0 = N->getOperand(0);
7655 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7657 SDValue N1 = N->getOperand(1);
7659 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7660 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7661 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7663 unsigned SplatBitSize;
7666 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7668 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7669 HasAnyUndefs) && !HasAnyUndefs) {
7670 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7672 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7673 HasAnyUndefs) && !HasAnyUndefs &&
7674 SplatBits0 == ~SplatBits1) {
7675 // Canonicalize the vector type to make instruction selection simpler.
7676 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7677 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7678 N0->getOperand(1), N0->getOperand(0),
7680 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7685 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7688 // BFI is only available on V6T2+
7689 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7692 DebugLoc DL = N->getDebugLoc();
7693 // 1) or (and A, mask), val => ARMbfi A, val, mask
7694 // iff (val & mask) == val
7696 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7697 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7698 // && mask == ~mask2
7699 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7700 // && ~mask == mask2
7701 // (i.e., copy a bitfield value into another bitfield of the same width)
7706 SDValue N00 = N0.getOperand(0);
7708 // The value and the mask need to be constants so we can verify this is
7709 // actually a bitfield set. If the mask is 0xffff, we can do better
7710 // via a movt instruction, so don't use BFI in that case.
7711 SDValue MaskOp = N0.getOperand(1);
7712 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7715 unsigned Mask = MaskC->getZExtValue();
7719 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7720 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7722 unsigned Val = N1C->getZExtValue();
7723 if ((Val & ~Mask) != Val)
7726 if (ARM::isBitFieldInvertedMask(Mask)) {
7727 Val >>= CountTrailingZeros_32(~Mask);
7729 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7730 DAG.getConstant(Val, MVT::i32),
7731 DAG.getConstant(Mask, MVT::i32));
7733 // Do not add new nodes to DAG combiner worklist.
7734 DCI.CombineTo(N, Res, false);
7737 } else if (N1.getOpcode() == ISD::AND) {
7738 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7739 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7742 unsigned Mask2 = N11C->getZExtValue();
7744 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7746 if (ARM::isBitFieldInvertedMask(Mask) &&
7748 // The pack halfword instruction works better for masks that fit it,
7749 // so use that when it's available.
7750 if (Subtarget->hasT2ExtractPack() &&
7751 (Mask == 0xffff || Mask == 0xffff0000))
7754 unsigned amt = CountTrailingZeros_32(Mask2);
7755 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7756 DAG.getConstant(amt, MVT::i32));
7757 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7758 DAG.getConstant(Mask, MVT::i32));
7759 // Do not add new nodes to DAG combiner worklist.
7760 DCI.CombineTo(N, Res, false);
7762 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7764 // The pack halfword instruction works better for masks that fit it,
7765 // so use that when it's available.
7766 if (Subtarget->hasT2ExtractPack() &&
7767 (Mask2 == 0xffff || Mask2 == 0xffff0000))
7770 unsigned lsb = CountTrailingZeros_32(Mask);
7771 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7772 DAG.getConstant(lsb, MVT::i32));
7773 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7774 DAG.getConstant(Mask2, MVT::i32));
7775 // Do not add new nodes to DAG combiner worklist.
7776 DCI.CombineTo(N, Res, false);
7781 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7782 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7783 ARM::isBitFieldInvertedMask(~Mask)) {
7784 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7785 // where lsb(mask) == #shamt and masked bits of B are known zero.
7786 SDValue ShAmt = N00.getOperand(1);
7787 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7788 unsigned LSB = CountTrailingZeros_32(Mask);
7792 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7793 DAG.getConstant(~Mask, MVT::i32));
7795 // Do not add new nodes to DAG combiner worklist.
7796 DCI.CombineTo(N, Res, false);
7802 static SDValue PerformXORCombine(SDNode *N,
7803 TargetLowering::DAGCombinerInfo &DCI,
7804 const ARMSubtarget *Subtarget) {
7805 EVT VT = N->getValueType(0);
7806 SelectionDAG &DAG = DCI.DAG;
7808 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7811 if (!Subtarget->isThumb1Only()) {
7812 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7813 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7814 if (Result.getNode())
7821 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7822 /// the bits being cleared by the AND are not demanded by the BFI.
7823 static SDValue PerformBFICombine(SDNode *N,
7824 TargetLowering::DAGCombinerInfo &DCI) {
7825 SDValue N1 = N->getOperand(1);
7826 if (N1.getOpcode() == ISD::AND) {
7827 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7830 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7831 unsigned LSB = CountTrailingZeros_32(~InvMask);
7832 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7833 unsigned Mask = (1 << Width)-1;
7834 unsigned Mask2 = N11C->getZExtValue();
7835 if ((Mask & (~Mask2)) == 0)
7836 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7837 N->getOperand(0), N1.getOperand(0),
7843 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7844 /// ARMISD::VMOVRRD.
7845 static SDValue PerformVMOVRRDCombine(SDNode *N,
7846 TargetLowering::DAGCombinerInfo &DCI) {
7847 // vmovrrd(vmovdrr x, y) -> x,y
7848 SDValue InDouble = N->getOperand(0);
7849 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7850 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7852 // vmovrrd(load f64) -> (load i32), (load i32)
7853 SDNode *InNode = InDouble.getNode();
7854 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7855 InNode->getValueType(0) == MVT::f64 &&
7856 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7857 !cast<LoadSDNode>(InNode)->isVolatile()) {
7858 // TODO: Should this be done for non-FrameIndex operands?
7859 LoadSDNode *LD = cast<LoadSDNode>(InNode);
7861 SelectionDAG &DAG = DCI.DAG;
7862 DebugLoc DL = LD->getDebugLoc();
7863 SDValue BasePtr = LD->getBasePtr();
7864 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7865 LD->getPointerInfo(), LD->isVolatile(),
7866 LD->isNonTemporal(), LD->isInvariant(),
7867 LD->getAlignment());
7869 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7870 DAG.getConstant(4, MVT::i32));
7871 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7872 LD->getPointerInfo(), LD->isVolatile(),
7873 LD->isNonTemporal(), LD->isInvariant(),
7874 std::min(4U, LD->getAlignment() / 2));
7876 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7877 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7878 DCI.RemoveFromWorklist(LD);
7886 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7887 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
7888 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7889 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7890 SDValue Op0 = N->getOperand(0);
7891 SDValue Op1 = N->getOperand(1);
7892 if (Op0.getOpcode() == ISD::BITCAST)
7893 Op0 = Op0.getOperand(0);
7894 if (Op1.getOpcode() == ISD::BITCAST)
7895 Op1 = Op1.getOperand(0);
7896 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7897 Op0.getNode() == Op1.getNode() &&
7898 Op0.getResNo() == 0 && Op1.getResNo() == 1)
7899 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7900 N->getValueType(0), Op0.getOperand(0));
7904 /// PerformSTORECombine - Target-specific dag combine xforms for
7906 static SDValue PerformSTORECombine(SDNode *N,
7907 TargetLowering::DAGCombinerInfo &DCI) {
7908 StoreSDNode *St = cast<StoreSDNode>(N);
7909 if (St->isVolatile())
7912 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
7913 // pack all of the elements in one place. Next, store to memory in fewer
7915 SDValue StVal = St->getValue();
7916 EVT VT = StVal.getValueType();
7917 if (St->isTruncatingStore() && VT.isVector()) {
7918 SelectionDAG &DAG = DCI.DAG;
7919 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7920 EVT StVT = St->getMemoryVT();
7921 unsigned NumElems = VT.getVectorNumElements();
7922 assert(StVT != VT && "Cannot truncate to the same type");
7923 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7924 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7926 // From, To sizes and ElemCount must be pow of two
7927 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7929 // We are going to use the original vector elt for storing.
7930 // Accumulated smaller vector elements must be a multiple of the store size.
7931 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7933 unsigned SizeRatio = FromEltSz / ToEltSz;
7934 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7936 // Create a type on which we perform the shuffle.
7937 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7938 NumElems*SizeRatio);
7939 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7941 DebugLoc DL = St->getDebugLoc();
7942 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7943 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7944 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7946 // Can't shuffle using an illegal type.
7947 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7949 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7950 DAG.getUNDEF(WideVec.getValueType()),
7952 // At this point all of the data is stored at the bottom of the
7953 // register. We now need to save it to mem.
7955 // Find the largest store unit
7956 MVT StoreType = MVT::i8;
7957 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7958 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7959 MVT Tp = (MVT::SimpleValueType)tp;
7960 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7963 // Didn't find a legal store type.
7964 if (!TLI.isTypeLegal(StoreType))
7967 // Bitcast the original vector into a vector of store-size units
7968 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7969 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7970 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7971 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7972 SmallVector<SDValue, 8> Chains;
7973 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7974 TLI.getPointerTy());
7975 SDValue BasePtr = St->getBasePtr();
7977 // Perform one or more big stores into memory.
7978 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7979 for (unsigned I = 0; I < E; I++) {
7980 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7981 StoreType, ShuffWide,
7982 DAG.getIntPtrConstant(I));
7983 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7984 St->getPointerInfo(), St->isVolatile(),
7985 St->isNonTemporal(), St->getAlignment());
7986 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7988 Chains.push_back(Ch);
7990 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7994 if (!ISD::isNormalStore(St))
7997 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7998 // ARM stores of arguments in the same cache line.
7999 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8000 StVal.getNode()->hasOneUse()) {
8001 SelectionDAG &DAG = DCI.DAG;
8002 DebugLoc DL = St->getDebugLoc();
8003 SDValue BasePtr = St->getBasePtr();
8004 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8005 StVal.getNode()->getOperand(0), BasePtr,
8006 St->getPointerInfo(), St->isVolatile(),
8007 St->isNonTemporal(), St->getAlignment());
8009 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8010 DAG.getConstant(4, MVT::i32));
8011 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8012 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8013 St->isNonTemporal(),
8014 std::min(4U, St->getAlignment() / 2));
8017 if (StVal.getValueType() != MVT::i64 ||
8018 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8021 // Bitcast an i64 store extracted from a vector to f64.
8022 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8023 SelectionDAG &DAG = DCI.DAG;
8024 DebugLoc dl = StVal.getDebugLoc();
8025 SDValue IntVec = StVal.getOperand(0);
8026 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8027 IntVec.getValueType().getVectorNumElements());
8028 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8029 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8030 Vec, StVal.getOperand(1));
8031 dl = N->getDebugLoc();
8032 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8033 // Make the DAGCombiner fold the bitcasts.
8034 DCI.AddToWorklist(Vec.getNode());
8035 DCI.AddToWorklist(ExtElt.getNode());
8036 DCI.AddToWorklist(V.getNode());
8037 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8038 St->getPointerInfo(), St->isVolatile(),
8039 St->isNonTemporal(), St->getAlignment(),
8043 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8044 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8045 /// i64 vector to have f64 elements, since the value can then be loaded
8046 /// directly into a VFP register.
8047 static bool hasNormalLoadOperand(SDNode *N) {
8048 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8049 for (unsigned i = 0; i < NumElts; ++i) {
8050 SDNode *Elt = N->getOperand(i).getNode();
8051 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8057 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8058 /// ISD::BUILD_VECTOR.
8059 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8060 TargetLowering::DAGCombinerInfo &DCI){
8061 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8062 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8063 // into a pair of GPRs, which is fine when the value is used as a scalar,
8064 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8065 SelectionDAG &DAG = DCI.DAG;
8066 if (N->getNumOperands() == 2) {
8067 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8072 // Load i64 elements as f64 values so that type legalization does not split
8073 // them up into i32 values.
8074 EVT VT = N->getValueType(0);
8075 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8077 DebugLoc dl = N->getDebugLoc();
8078 SmallVector<SDValue, 8> Ops;
8079 unsigned NumElts = VT.getVectorNumElements();
8080 for (unsigned i = 0; i < NumElts; ++i) {
8081 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8083 // Make the DAGCombiner fold the bitcast.
8084 DCI.AddToWorklist(V.getNode());
8086 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8087 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8088 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8091 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8092 /// ISD::INSERT_VECTOR_ELT.
8093 static SDValue PerformInsertEltCombine(SDNode *N,
8094 TargetLowering::DAGCombinerInfo &DCI) {
8095 // Bitcast an i64 load inserted into a vector to f64.
8096 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8097 EVT VT = N->getValueType(0);
8098 SDNode *Elt = N->getOperand(1).getNode();
8099 if (VT.getVectorElementType() != MVT::i64 ||
8100 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8103 SelectionDAG &DAG = DCI.DAG;
8104 DebugLoc dl = N->getDebugLoc();
8105 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8106 VT.getVectorNumElements());
8107 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8108 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8109 // Make the DAGCombiner fold the bitcasts.
8110 DCI.AddToWorklist(Vec.getNode());
8111 DCI.AddToWorklist(V.getNode());
8112 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8113 Vec, V, N->getOperand(2));
8114 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8117 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8118 /// ISD::VECTOR_SHUFFLE.
8119 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8120 // The LLVM shufflevector instruction does not require the shuffle mask
8121 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8122 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8123 // operands do not match the mask length, they are extended by concatenating
8124 // them with undef vectors. That is probably the right thing for other
8125 // targets, but for NEON it is better to concatenate two double-register
8126 // size vector operands into a single quad-register size vector. Do that
8127 // transformation here:
8128 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8129 // shuffle(concat(v1, v2), undef)
8130 SDValue Op0 = N->getOperand(0);
8131 SDValue Op1 = N->getOperand(1);
8132 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8133 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8134 Op0.getNumOperands() != 2 ||
8135 Op1.getNumOperands() != 2)
8137 SDValue Concat0Op1 = Op0.getOperand(1);
8138 SDValue Concat1Op1 = Op1.getOperand(1);
8139 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8140 Concat1Op1.getOpcode() != ISD::UNDEF)
8142 // Skip the transformation if any of the types are illegal.
8143 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8144 EVT VT = N->getValueType(0);
8145 if (!TLI.isTypeLegal(VT) ||
8146 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8147 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8150 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8151 Op0.getOperand(0), Op1.getOperand(0));
8152 // Translate the shuffle mask.
8153 SmallVector<int, 16> NewMask;
8154 unsigned NumElts = VT.getVectorNumElements();
8155 unsigned HalfElts = NumElts/2;
8156 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8157 for (unsigned n = 0; n < NumElts; ++n) {
8158 int MaskElt = SVN->getMaskElt(n);
8160 if (MaskElt < (int)HalfElts)
8162 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8163 NewElt = HalfElts + MaskElt - NumElts;
8164 NewMask.push_back(NewElt);
8166 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8167 DAG.getUNDEF(VT), NewMask.data());
8170 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8171 /// NEON load/store intrinsics to merge base address updates.
8172 static SDValue CombineBaseUpdate(SDNode *N,
8173 TargetLowering::DAGCombinerInfo &DCI) {
8174 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8177 SelectionDAG &DAG = DCI.DAG;
8178 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8179 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8180 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8181 SDValue Addr = N->getOperand(AddrOpIdx);
8183 // Search for a use of the address operand that is an increment.
8184 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8185 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8187 if (User->getOpcode() != ISD::ADD ||
8188 UI.getUse().getResNo() != Addr.getResNo())
8191 // Check that the add is independent of the load/store. Otherwise, folding
8192 // it would create a cycle.
8193 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8196 // Find the new opcode for the updating load/store.
8198 bool isLaneOp = false;
8199 unsigned NewOpc = 0;
8200 unsigned NumVecs = 0;
8202 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8204 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8205 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8207 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8209 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8211 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8213 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8214 NumVecs = 2; isLaneOp = true; break;
8215 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8216 NumVecs = 3; isLaneOp = true; break;
8217 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8218 NumVecs = 4; isLaneOp = true; break;
8219 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8220 NumVecs = 1; isLoad = false; break;
8221 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8222 NumVecs = 2; isLoad = false; break;
8223 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8224 NumVecs = 3; isLoad = false; break;
8225 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8226 NumVecs = 4; isLoad = false; break;
8227 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8228 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8229 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8230 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8231 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8232 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8236 switch (N->getOpcode()) {
8237 default: llvm_unreachable("unexpected opcode for Neon base update");
8238 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8239 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8240 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8244 // Find the size of memory referenced by the load/store.
8247 VecTy = N->getValueType(0);
8249 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8250 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8252 NumBytes /= VecTy.getVectorNumElements();
8254 // If the increment is a constant, it must match the memory ref size.
8255 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8256 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8257 uint64_t IncVal = CInc->getZExtValue();
8258 if (IncVal != NumBytes)
8260 } else if (NumBytes >= 3 * 16) {
8261 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8262 // separate instructions that make it harder to use a non-constant update.
8266 // Create the new updating load/store node.
8268 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8270 for (n = 0; n < NumResultVecs; ++n)
8272 Tys[n++] = MVT::i32;
8273 Tys[n] = MVT::Other;
8274 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8275 SmallVector<SDValue, 8> Ops;
8276 Ops.push_back(N->getOperand(0)); // incoming chain
8277 Ops.push_back(N->getOperand(AddrOpIdx));
8279 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8280 Ops.push_back(N->getOperand(i));
8282 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8283 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8284 Ops.data(), Ops.size(),
8285 MemInt->getMemoryVT(),
8286 MemInt->getMemOperand());
8289 std::vector<SDValue> NewResults;
8290 for (unsigned i = 0; i < NumResultVecs; ++i) {
8291 NewResults.push_back(SDValue(UpdN.getNode(), i));
8293 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8294 DCI.CombineTo(N, NewResults);
8295 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8302 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8303 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8304 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8306 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8307 SelectionDAG &DAG = DCI.DAG;
8308 EVT VT = N->getValueType(0);
8309 // vldN-dup instructions only support 64-bit vectors for N > 1.
8310 if (!VT.is64BitVector())
8313 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8314 SDNode *VLD = N->getOperand(0).getNode();
8315 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8317 unsigned NumVecs = 0;
8318 unsigned NewOpc = 0;
8319 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8320 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8322 NewOpc = ARMISD::VLD2DUP;
8323 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8325 NewOpc = ARMISD::VLD3DUP;
8326 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8328 NewOpc = ARMISD::VLD4DUP;
8333 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8334 // numbers match the load.
8335 unsigned VLDLaneNo =
8336 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8337 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8339 // Ignore uses of the chain result.
8340 if (UI.getUse().getResNo() == NumVecs)
8343 if (User->getOpcode() != ARMISD::VDUPLANE ||
8344 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8348 // Create the vldN-dup node.
8351 for (n = 0; n < NumVecs; ++n)
8353 Tys[n] = MVT::Other;
8354 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8355 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8356 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8357 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8358 Ops, 2, VLDMemInt->getMemoryVT(),
8359 VLDMemInt->getMemOperand());
8362 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8364 unsigned ResNo = UI.getUse().getResNo();
8365 // Ignore uses of the chain result.
8366 if (ResNo == NumVecs)
8369 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8372 // Now the vldN-lane intrinsic is dead except for its chain result.
8373 // Update uses of the chain.
8374 std::vector<SDValue> VLDDupResults;
8375 for (unsigned n = 0; n < NumVecs; ++n)
8376 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8377 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8378 DCI.CombineTo(VLD, VLDDupResults);
8383 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8384 /// ARMISD::VDUPLANE.
8385 static SDValue PerformVDUPLANECombine(SDNode *N,
8386 TargetLowering::DAGCombinerInfo &DCI) {
8387 SDValue Op = N->getOperand(0);
8389 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8390 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8391 if (CombineVLDDUP(N, DCI))
8392 return SDValue(N, 0);
8394 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8395 // redundant. Ignore bit_converts for now; element sizes are checked below.
8396 while (Op.getOpcode() == ISD::BITCAST)
8397 Op = Op.getOperand(0);
8398 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8401 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8402 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8403 // The canonical VMOV for a zero vector uses a 32-bit element size.
8404 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8406 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8408 EVT VT = N->getValueType(0);
8409 if (EltSize > VT.getVectorElementType().getSizeInBits())
8412 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8415 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8416 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8417 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8421 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8423 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8428 APFloat APF = C->getValueAPF();
8429 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8430 != APFloat::opOK || !isExact)
8433 c0 = (I == 0) ? cN : c0;
8434 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8441 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8442 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8443 /// when the VMUL has a constant operand that is a power of 2.
8445 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8446 /// vmul.f32 d16, d17, d16
8447 /// vcvt.s32.f32 d16, d16
8449 /// vcvt.s32.f32 d16, d16, #3
8450 static SDValue PerformVCVTCombine(SDNode *N,
8451 TargetLowering::DAGCombinerInfo &DCI,
8452 const ARMSubtarget *Subtarget) {
8453 SelectionDAG &DAG = DCI.DAG;
8454 SDValue Op = N->getOperand(0);
8456 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8457 Op.getOpcode() != ISD::FMUL)
8461 SDValue N0 = Op->getOperand(0);
8462 SDValue ConstVec = Op->getOperand(1);
8463 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8465 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8466 !isConstVecPow2(ConstVec, isSigned, C))
8469 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8470 Intrinsic::arm_neon_vcvtfp2fxu;
8471 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8473 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8474 DAG.getConstant(Log2_64(C), MVT::i32));
8477 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8478 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8479 /// when the VDIV has a constant operand that is a power of 2.
8481 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8482 /// vcvt.f32.s32 d16, d16
8483 /// vdiv.f32 d16, d17, d16
8485 /// vcvt.f32.s32 d16, d16, #3
8486 static SDValue PerformVDIVCombine(SDNode *N,
8487 TargetLowering::DAGCombinerInfo &DCI,
8488 const ARMSubtarget *Subtarget) {
8489 SelectionDAG &DAG = DCI.DAG;
8490 SDValue Op = N->getOperand(0);
8491 unsigned OpOpcode = Op.getNode()->getOpcode();
8493 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8494 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8498 SDValue ConstVec = N->getOperand(1);
8499 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8501 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8502 !isConstVecPow2(ConstVec, isSigned, C))
8505 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8506 Intrinsic::arm_neon_vcvtfxu2fp;
8507 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8509 DAG.getConstant(IntrinsicOpcode, MVT::i32),
8510 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8513 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8514 /// operand of a vector shift operation, where all the elements of the
8515 /// build_vector must have the same constant integer value.
8516 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8517 // Ignore bit_converts.
8518 while (Op.getOpcode() == ISD::BITCAST)
8519 Op = Op.getOperand(0);
8520 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8521 APInt SplatBits, SplatUndef;
8522 unsigned SplatBitSize;
8524 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8525 HasAnyUndefs, ElementBits) ||
8526 SplatBitSize > ElementBits)
8528 Cnt = SplatBits.getSExtValue();
8532 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8533 /// operand of a vector shift left operation. That value must be in the range:
8534 /// 0 <= Value < ElementBits for a left shift; or
8535 /// 0 <= Value <= ElementBits for a long left shift.
8536 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8537 assert(VT.isVector() && "vector shift count is not a vector type");
8538 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8539 if (! getVShiftImm(Op, ElementBits, Cnt))
8541 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8544 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8545 /// operand of a vector shift right operation. For a shift opcode, the value
8546 /// is positive, but for an intrinsic the value count must be negative. The
8547 /// absolute value must be in the range:
8548 /// 1 <= |Value| <= ElementBits for a right shift; or
8549 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8550 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8552 assert(VT.isVector() && "vector shift count is not a vector type");
8553 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8554 if (! getVShiftImm(Op, ElementBits, Cnt))
8558 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8561 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8562 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8563 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8566 // Don't do anything for most intrinsics.
8569 // Vector shifts: check for immediate versions and lower them.
8570 // Note: This is done during DAG combining instead of DAG legalizing because
8571 // the build_vectors for 64-bit vector element shift counts are generally
8572 // not legal, and it is hard to see their values after they get legalized to
8573 // loads from a constant pool.
8574 case Intrinsic::arm_neon_vshifts:
8575 case Intrinsic::arm_neon_vshiftu:
8576 case Intrinsic::arm_neon_vshiftls:
8577 case Intrinsic::arm_neon_vshiftlu:
8578 case Intrinsic::arm_neon_vshiftn:
8579 case Intrinsic::arm_neon_vrshifts:
8580 case Intrinsic::arm_neon_vrshiftu:
8581 case Intrinsic::arm_neon_vrshiftn:
8582 case Intrinsic::arm_neon_vqshifts:
8583 case Intrinsic::arm_neon_vqshiftu:
8584 case Intrinsic::arm_neon_vqshiftsu:
8585 case Intrinsic::arm_neon_vqshiftns:
8586 case Intrinsic::arm_neon_vqshiftnu:
8587 case Intrinsic::arm_neon_vqshiftnsu:
8588 case Intrinsic::arm_neon_vqrshiftns:
8589 case Intrinsic::arm_neon_vqrshiftnu:
8590 case Intrinsic::arm_neon_vqrshiftnsu: {
8591 EVT VT = N->getOperand(1).getValueType();
8593 unsigned VShiftOpc = 0;
8596 case Intrinsic::arm_neon_vshifts:
8597 case Intrinsic::arm_neon_vshiftu:
8598 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8599 VShiftOpc = ARMISD::VSHL;
8602 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8603 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8604 ARMISD::VSHRs : ARMISD::VSHRu);
8609 case Intrinsic::arm_neon_vshiftls:
8610 case Intrinsic::arm_neon_vshiftlu:
8611 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8613 llvm_unreachable("invalid shift count for vshll intrinsic");
8615 case Intrinsic::arm_neon_vrshifts:
8616 case Intrinsic::arm_neon_vrshiftu:
8617 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8621 case Intrinsic::arm_neon_vqshifts:
8622 case Intrinsic::arm_neon_vqshiftu:
8623 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8627 case Intrinsic::arm_neon_vqshiftsu:
8628 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8630 llvm_unreachable("invalid shift count for vqshlu intrinsic");
8632 case Intrinsic::arm_neon_vshiftn:
8633 case Intrinsic::arm_neon_vrshiftn:
8634 case Intrinsic::arm_neon_vqshiftns:
8635 case Intrinsic::arm_neon_vqshiftnu:
8636 case Intrinsic::arm_neon_vqshiftnsu:
8637 case Intrinsic::arm_neon_vqrshiftns:
8638 case Intrinsic::arm_neon_vqrshiftnu:
8639 case Intrinsic::arm_neon_vqrshiftnsu:
8640 // Narrowing shifts require an immediate right shift.
8641 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8643 llvm_unreachable("invalid shift count for narrowing vector shift "
8647 llvm_unreachable("unhandled vector shift");
8651 case Intrinsic::arm_neon_vshifts:
8652 case Intrinsic::arm_neon_vshiftu:
8653 // Opcode already set above.
8655 case Intrinsic::arm_neon_vshiftls:
8656 case Intrinsic::arm_neon_vshiftlu:
8657 if (Cnt == VT.getVectorElementType().getSizeInBits())
8658 VShiftOpc = ARMISD::VSHLLi;
8660 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8661 ARMISD::VSHLLs : ARMISD::VSHLLu);
8663 case Intrinsic::arm_neon_vshiftn:
8664 VShiftOpc = ARMISD::VSHRN; break;
8665 case Intrinsic::arm_neon_vrshifts:
8666 VShiftOpc = ARMISD::VRSHRs; break;
8667 case Intrinsic::arm_neon_vrshiftu:
8668 VShiftOpc = ARMISD::VRSHRu; break;
8669 case Intrinsic::arm_neon_vrshiftn:
8670 VShiftOpc = ARMISD::VRSHRN; break;
8671 case Intrinsic::arm_neon_vqshifts:
8672 VShiftOpc = ARMISD::VQSHLs; break;
8673 case Intrinsic::arm_neon_vqshiftu:
8674 VShiftOpc = ARMISD::VQSHLu; break;
8675 case Intrinsic::arm_neon_vqshiftsu:
8676 VShiftOpc = ARMISD::VQSHLsu; break;
8677 case Intrinsic::arm_neon_vqshiftns:
8678 VShiftOpc = ARMISD::VQSHRNs; break;
8679 case Intrinsic::arm_neon_vqshiftnu:
8680 VShiftOpc = ARMISD::VQSHRNu; break;
8681 case Intrinsic::arm_neon_vqshiftnsu:
8682 VShiftOpc = ARMISD::VQSHRNsu; break;
8683 case Intrinsic::arm_neon_vqrshiftns:
8684 VShiftOpc = ARMISD::VQRSHRNs; break;
8685 case Intrinsic::arm_neon_vqrshiftnu:
8686 VShiftOpc = ARMISD::VQRSHRNu; break;
8687 case Intrinsic::arm_neon_vqrshiftnsu:
8688 VShiftOpc = ARMISD::VQRSHRNsu; break;
8691 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8692 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8695 case Intrinsic::arm_neon_vshiftins: {
8696 EVT VT = N->getOperand(1).getValueType();
8698 unsigned VShiftOpc = 0;
8700 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8701 VShiftOpc = ARMISD::VSLI;
8702 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8703 VShiftOpc = ARMISD::VSRI;
8705 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8708 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8709 N->getOperand(1), N->getOperand(2),
8710 DAG.getConstant(Cnt, MVT::i32));
8713 case Intrinsic::arm_neon_vqrshifts:
8714 case Intrinsic::arm_neon_vqrshiftu:
8715 // No immediate versions of these to check for.
8722 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8723 /// lowers them. As with the vector shift intrinsics, this is done during DAG
8724 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8725 /// vector element shift counts are generally not legal, and it is hard to see
8726 /// their values after they get legalized to loads from a constant pool.
8727 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8728 const ARMSubtarget *ST) {
8729 EVT VT = N->getValueType(0);
8730 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8731 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8732 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8733 SDValue N1 = N->getOperand(1);
8734 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8735 SDValue N0 = N->getOperand(0);
8736 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8737 DAG.MaskedValueIsZero(N0.getOperand(0),
8738 APInt::getHighBitsSet(32, 16)))
8739 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8743 // Nothing to be done for scalar shifts.
8744 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8745 if (!VT.isVector() || !TLI.isTypeLegal(VT))
8748 assert(ST->hasNEON() && "unexpected vector shift");
8751 switch (N->getOpcode()) {
8752 default: llvm_unreachable("unexpected shift opcode");
8755 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8756 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8757 DAG.getConstant(Cnt, MVT::i32));
8762 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8763 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8764 ARMISD::VSHRs : ARMISD::VSHRu);
8765 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8766 DAG.getConstant(Cnt, MVT::i32));
8772 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8773 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8774 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8775 const ARMSubtarget *ST) {
8776 SDValue N0 = N->getOperand(0);
8778 // Check for sign- and zero-extensions of vector extract operations of 8-
8779 // and 16-bit vector elements. NEON supports these directly. They are
8780 // handled during DAG combining because type legalization will promote them
8781 // to 32-bit types and it is messy to recognize the operations after that.
8782 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8783 SDValue Vec = N0.getOperand(0);
8784 SDValue Lane = N0.getOperand(1);
8785 EVT VT = N->getValueType(0);
8786 EVT EltVT = N0.getValueType();
8787 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8789 if (VT == MVT::i32 &&
8790 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8791 TLI.isTypeLegal(Vec.getValueType()) &&
8792 isa<ConstantSDNode>(Lane)) {
8795 switch (N->getOpcode()) {
8796 default: llvm_unreachable("unexpected opcode");
8797 case ISD::SIGN_EXTEND:
8798 Opc = ARMISD::VGETLANEs;
8800 case ISD::ZERO_EXTEND:
8801 case ISD::ANY_EXTEND:
8802 Opc = ARMISD::VGETLANEu;
8805 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8812 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8813 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8814 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8815 const ARMSubtarget *ST) {
8816 // If the target supports NEON, try to use vmax/vmin instructions for f32
8817 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
8818 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
8819 // a NaN; only do the transformation when it matches that behavior.
8821 // For now only do this when using NEON for FP operations; if using VFP, it
8822 // is not obvious that the benefit outweighs the cost of switching to the
8824 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8825 N->getValueType(0) != MVT::f32)
8828 SDValue CondLHS = N->getOperand(0);
8829 SDValue CondRHS = N->getOperand(1);
8830 SDValue LHS = N->getOperand(2);
8831 SDValue RHS = N->getOperand(3);
8832 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8834 unsigned Opcode = 0;
8836 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8837 IsReversed = false; // x CC y ? x : y
8838 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8839 IsReversed = true ; // x CC y ? y : x
8853 // If LHS is NaN, an ordered comparison will be false and the result will
8854 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
8855 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8856 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8857 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8859 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8860 // will return -0, so vmin can only be used for unsafe math or if one of
8861 // the operands is known to be nonzero.
8862 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8863 !DAG.getTarget().Options.UnsafeFPMath &&
8864 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8866 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8875 // If LHS is NaN, an ordered comparison will be false and the result will
8876 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
8877 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8878 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8879 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8881 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8882 // will return +0, so vmax can only be used for unsafe math or if one of
8883 // the operands is known to be nonzero.
8884 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8885 !DAG.getTarget().Options.UnsafeFPMath &&
8886 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8888 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8894 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8897 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8899 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8900 SDValue Cmp = N->getOperand(4);
8901 if (Cmp.getOpcode() != ARMISD::CMPZ)
8902 // Only looking at EQ and NE cases.
8905 EVT VT = N->getValueType(0);
8906 DebugLoc dl = N->getDebugLoc();
8907 SDValue LHS = Cmp.getOperand(0);
8908 SDValue RHS = Cmp.getOperand(1);
8909 SDValue FalseVal = N->getOperand(0);
8910 SDValue TrueVal = N->getOperand(1);
8911 SDValue ARMcc = N->getOperand(2);
8912 ARMCC::CondCodes CC =
8913 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8931 /// FIXME: Turn this into a target neutral optimization?
8933 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8934 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8935 N->getOperand(3), Cmp);
8936 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8938 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8939 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8940 N->getOperand(3), NewCmp);
8943 if (Res.getNode()) {
8944 APInt KnownZero, KnownOne;
8945 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8946 // Capture demanded bits information that would be otherwise lost.
8947 if (KnownZero == 0xfffffffe)
8948 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8949 DAG.getValueType(MVT::i1));
8950 else if (KnownZero == 0xffffff00)
8951 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8952 DAG.getValueType(MVT::i8));
8953 else if (KnownZero == 0xffff0000)
8954 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8955 DAG.getValueType(MVT::i16));
8961 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8962 DAGCombinerInfo &DCI) const {
8963 switch (N->getOpcode()) {
8965 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
8966 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
8967 case ISD::SUB: return PerformSUBCombine(N, DCI);
8968 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
8969 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
8970 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
8971 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
8972 case ARMISD::BFI: return PerformBFICombine(N, DCI);
8973 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8974 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8975 case ISD::STORE: return PerformSTORECombine(N, DCI);
8976 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8977 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8978 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8979 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8980 case ISD::FP_TO_SINT:
8981 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8982 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
8983 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8986 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
8987 case ISD::SIGN_EXTEND:
8988 case ISD::ZERO_EXTEND:
8989 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8990 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8991 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8992 case ARMISD::VLD2DUP:
8993 case ARMISD::VLD3DUP:
8994 case ARMISD::VLD4DUP:
8995 return CombineBaseUpdate(N, DCI);
8996 case ISD::INTRINSIC_VOID:
8997 case ISD::INTRINSIC_W_CHAIN:
8998 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8999 case Intrinsic::arm_neon_vld1:
9000 case Intrinsic::arm_neon_vld2:
9001 case Intrinsic::arm_neon_vld3:
9002 case Intrinsic::arm_neon_vld4:
9003 case Intrinsic::arm_neon_vld2lane:
9004 case Intrinsic::arm_neon_vld3lane:
9005 case Intrinsic::arm_neon_vld4lane:
9006 case Intrinsic::arm_neon_vst1:
9007 case Intrinsic::arm_neon_vst2:
9008 case Intrinsic::arm_neon_vst3:
9009 case Intrinsic::arm_neon_vst4:
9010 case Intrinsic::arm_neon_vst2lane:
9011 case Intrinsic::arm_neon_vst3lane:
9012 case Intrinsic::arm_neon_vst4lane:
9013 return CombineBaseUpdate(N, DCI);
9021 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9023 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9026 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
9027 if (!Subtarget->allowsUnalignedMem())
9030 switch (VT.getSimpleVT().SimpleTy) {
9038 return Subtarget->hasNEON();
9039 // FIXME: VLD1 etc with standard alignment is legal.
9043 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9044 unsigned AlignCheck) {
9045 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9046 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9049 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9050 unsigned DstAlign, unsigned SrcAlign,
9053 MachineFunction &MF) const {
9054 const Function *F = MF.getFunction();
9056 // See if we can use NEON instructions for this...
9058 !F->hasFnAttr(Attribute::NoImplicitFloat) &&
9059 Subtarget->hasNEON()) {
9060 if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
9062 } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
9067 // Lowering to i32/i16 if the size permits.
9070 } else if (Size >= 2) {
9074 // Let the target-independent logic figure it out.
9078 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9083 switch (VT.getSimpleVT().SimpleTy) {
9084 default: return false;
9099 if ((V & (Scale - 1)) != 0)
9102 return V == (V & ((1LL << 5) - 1));
9105 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9106 const ARMSubtarget *Subtarget) {
9113 switch (VT.getSimpleVT().SimpleTy) {
9114 default: return false;
9119 // + imm12 or - imm8
9121 return V == (V & ((1LL << 8) - 1));
9122 return V == (V & ((1LL << 12) - 1));
9125 // Same as ARM mode. FIXME: NEON?
9126 if (!Subtarget->hasVFP2())
9131 return V == (V & ((1LL << 8) - 1));
9135 /// isLegalAddressImmediate - Return true if the integer value can be used
9136 /// as the offset of the target addressing mode for load / store of the
9138 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9139 const ARMSubtarget *Subtarget) {
9146 if (Subtarget->isThumb1Only())
9147 return isLegalT1AddressImmediate(V, VT);
9148 else if (Subtarget->isThumb2())
9149 return isLegalT2AddressImmediate(V, VT, Subtarget);
9154 switch (VT.getSimpleVT().SimpleTy) {
9155 default: return false;
9160 return V == (V & ((1LL << 12) - 1));
9163 return V == (V & ((1LL << 8) - 1));
9166 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9171 return V == (V & ((1LL << 8) - 1));
9175 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9177 int Scale = AM.Scale;
9181 switch (VT.getSimpleVT().SimpleTy) {
9182 default: return false;
9191 return Scale == 2 || Scale == 4 || Scale == 8;
9194 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9198 // Note, we allow "void" uses (basically, uses that aren't loads or
9199 // stores), because arm allows folding a scale into many arithmetic
9200 // operations. This should be made more precise and revisited later.
9202 // Allow r << imm, but the imm has to be a multiple of two.
9203 if (Scale & 1) return false;
9204 return isPowerOf2_32(Scale);
9208 /// isLegalAddressingMode - Return true if the addressing mode represented
9209 /// by AM is legal for this target, for a load/store of the specified type.
9210 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9212 EVT VT = getValueType(Ty, true);
9213 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9216 // Can never fold addr of global into load/store.
9221 case 0: // no scale reg, must be "r+i" or "r", or "i".
9224 if (Subtarget->isThumb1Only())
9228 // ARM doesn't support any R+R*scale+imm addr modes.
9235 if (Subtarget->isThumb2())
9236 return isLegalT2ScaledAddressingMode(AM, VT);
9238 int Scale = AM.Scale;
9239 switch (VT.getSimpleVT().SimpleTy) {
9240 default: return false;
9244 if (Scale < 0) Scale = -Scale;
9248 return isPowerOf2_32(Scale & ~1);
9252 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9257 // Note, we allow "void" uses (basically, uses that aren't loads or
9258 // stores), because arm allows folding a scale into many arithmetic
9259 // operations. This should be made more precise and revisited later.
9261 // Allow r << imm, but the imm has to be a multiple of two.
9262 if (Scale & 1) return false;
9263 return isPowerOf2_32(Scale);
9269 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9270 /// icmp immediate, that is the target has icmp instructions which can compare
9271 /// a register against the immediate without having to materialize the
9272 /// immediate into a register.
9273 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9274 // Thumb2 and ARM modes can use cmn for negative immediates.
9275 if (!Subtarget->isThumb())
9276 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9277 if (Subtarget->isThumb2())
9278 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9279 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9280 return Imm >= 0 && Imm <= 255;
9283 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9284 /// *or sub* immediate, that is the target has add or sub instructions which can
9285 /// add a register with the immediate without having to materialize the
9286 /// immediate into a register.
9287 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9288 // Same encoding for add/sub, just flip the sign.
9289 int64_t AbsImm = llvm::abs64(Imm);
9290 if (!Subtarget->isThumb())
9291 return ARM_AM::getSOImmVal(AbsImm) != -1;
9292 if (Subtarget->isThumb2())
9293 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9294 // Thumb1 only has 8-bit unsigned immediate.
9295 return AbsImm >= 0 && AbsImm <= 255;
9298 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9299 bool isSEXTLoad, SDValue &Base,
9300 SDValue &Offset, bool &isInc,
9301 SelectionDAG &DAG) {
9302 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9305 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9307 Base = Ptr->getOperand(0);
9308 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9309 int RHSC = (int)RHS->getZExtValue();
9310 if (RHSC < 0 && RHSC > -256) {
9311 assert(Ptr->getOpcode() == ISD::ADD);
9313 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9317 isInc = (Ptr->getOpcode() == ISD::ADD);
9318 Offset = Ptr->getOperand(1);
9320 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9322 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9323 int RHSC = (int)RHS->getZExtValue();
9324 if (RHSC < 0 && RHSC > -0x1000) {
9325 assert(Ptr->getOpcode() == ISD::ADD);
9327 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9328 Base = Ptr->getOperand(0);
9333 if (Ptr->getOpcode() == ISD::ADD) {
9335 ARM_AM::ShiftOpc ShOpcVal=
9336 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9337 if (ShOpcVal != ARM_AM::no_shift) {
9338 Base = Ptr->getOperand(1);
9339 Offset = Ptr->getOperand(0);
9341 Base = Ptr->getOperand(0);
9342 Offset = Ptr->getOperand(1);
9347 isInc = (Ptr->getOpcode() == ISD::ADD);
9348 Base = Ptr->getOperand(0);
9349 Offset = Ptr->getOperand(1);
9353 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9357 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9358 bool isSEXTLoad, SDValue &Base,
9359 SDValue &Offset, bool &isInc,
9360 SelectionDAG &DAG) {
9361 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9364 Base = Ptr->getOperand(0);
9365 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9366 int RHSC = (int)RHS->getZExtValue();
9367 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9368 assert(Ptr->getOpcode() == ISD::ADD);
9370 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9372 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9373 isInc = Ptr->getOpcode() == ISD::ADD;
9374 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9382 /// getPreIndexedAddressParts - returns true by value, base pointer and
9383 /// offset pointer and addressing mode by reference if the node's address
9384 /// can be legally represented as pre-indexed load / store address.
9386 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9388 ISD::MemIndexedMode &AM,
9389 SelectionDAG &DAG) const {
9390 if (Subtarget->isThumb1Only())
9395 bool isSEXTLoad = false;
9396 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9397 Ptr = LD->getBasePtr();
9398 VT = LD->getMemoryVT();
9399 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9400 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9401 Ptr = ST->getBasePtr();
9402 VT = ST->getMemoryVT();
9407 bool isLegal = false;
9408 if (Subtarget->isThumb2())
9409 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9410 Offset, isInc, DAG);
9412 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9413 Offset, isInc, DAG);
9417 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9421 /// getPostIndexedAddressParts - returns true by value, base pointer and
9422 /// offset pointer and addressing mode by reference if this node can be
9423 /// combined with a load / store to form a post-indexed load / store.
9424 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9427 ISD::MemIndexedMode &AM,
9428 SelectionDAG &DAG) const {
9429 if (Subtarget->isThumb1Only())
9434 bool isSEXTLoad = false;
9435 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9436 VT = LD->getMemoryVT();
9437 Ptr = LD->getBasePtr();
9438 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9439 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9440 VT = ST->getMemoryVT();
9441 Ptr = ST->getBasePtr();
9446 bool isLegal = false;
9447 if (Subtarget->isThumb2())
9448 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9451 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9457 // Swap base ptr and offset to catch more post-index load / store when
9458 // it's legal. In Thumb2 mode, offset must be an immediate.
9459 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9460 !Subtarget->isThumb2())
9461 std::swap(Base, Offset);
9463 // Post-indexed load / store update the base pointer.
9468 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9472 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9475 const SelectionDAG &DAG,
9476 unsigned Depth) const {
9477 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9478 switch (Op.getOpcode()) {
9480 case ARMISD::CMOV: {
9481 // Bits are known zero/one if known on the LHS and RHS.
9482 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9483 if (KnownZero == 0 && KnownOne == 0) return;
9485 APInt KnownZeroRHS, KnownOneRHS;
9486 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9487 KnownZero &= KnownZeroRHS;
9488 KnownOne &= KnownOneRHS;
9494 //===----------------------------------------------------------------------===//
9495 // ARM Inline Assembly Support
9496 //===----------------------------------------------------------------------===//
9498 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9499 // Looking for "rev" which is V6+.
9500 if (!Subtarget->hasV6Ops())
9503 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9504 std::string AsmStr = IA->getAsmString();
9505 SmallVector<StringRef, 4> AsmPieces;
9506 SplitString(AsmStr, AsmPieces, ";\n");
9508 switch (AsmPieces.size()) {
9509 default: return false;
9511 AsmStr = AsmPieces[0];
9513 SplitString(AsmStr, AsmPieces, " \t,");
9516 if (AsmPieces.size() == 3 &&
9517 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9518 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9519 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9520 if (Ty && Ty->getBitWidth() == 32)
9521 return IntrinsicLowering::LowerToByteSwap(CI);
9529 /// getConstraintType - Given a constraint letter, return the type of
9530 /// constraint it is for this target.
9531 ARMTargetLowering::ConstraintType
9532 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9533 if (Constraint.size() == 1) {
9534 switch (Constraint[0]) {
9536 case 'l': return C_RegisterClass;
9537 case 'w': return C_RegisterClass;
9538 case 'h': return C_RegisterClass;
9539 case 'x': return C_RegisterClass;
9540 case 't': return C_RegisterClass;
9541 case 'j': return C_Other; // Constant for movw.
9542 // An address with a single base register. Due to the way we
9543 // currently handle addresses it is the same as an 'r' memory constraint.
9544 case 'Q': return C_Memory;
9546 } else if (Constraint.size() == 2) {
9547 switch (Constraint[0]) {
9549 // All 'U+' constraints are addresses.
9550 case 'U': return C_Memory;
9553 return TargetLowering::getConstraintType(Constraint);
9556 /// Examine constraint type and operand type and determine a weight value.
9557 /// This object must already have been set up with the operand type
9558 /// and the current alternative constraint selected.
9559 TargetLowering::ConstraintWeight
9560 ARMTargetLowering::getSingleConstraintMatchWeight(
9561 AsmOperandInfo &info, const char *constraint) const {
9562 ConstraintWeight weight = CW_Invalid;
9563 Value *CallOperandVal = info.CallOperandVal;
9564 // If we don't have a value, we can't do a match,
9565 // but allow it at the lowest weight.
9566 if (CallOperandVal == NULL)
9568 Type *type = CallOperandVal->getType();
9569 // Look at the constraint type.
9570 switch (*constraint) {
9572 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9575 if (type->isIntegerTy()) {
9576 if (Subtarget->isThumb())
9577 weight = CW_SpecificReg;
9579 weight = CW_Register;
9583 if (type->isFloatingPointTy())
9584 weight = CW_Register;
9590 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9592 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9594 if (Constraint.size() == 1) {
9595 // GCC ARM Constraint Letters
9596 switch (Constraint[0]) {
9597 case 'l': // Low regs or general regs.
9598 if (Subtarget->isThumb())
9599 return RCPair(0U, &ARM::tGPRRegClass);
9600 return RCPair(0U, &ARM::GPRRegClass);
9601 case 'h': // High regs or no regs.
9602 if (Subtarget->isThumb())
9603 return RCPair(0U, &ARM::hGPRRegClass);
9606 return RCPair(0U, &ARM::GPRRegClass);
9609 return RCPair(0U, &ARM::SPRRegClass);
9610 if (VT.getSizeInBits() == 64)
9611 return RCPair(0U, &ARM::DPRRegClass);
9612 if (VT.getSizeInBits() == 128)
9613 return RCPair(0U, &ARM::QPRRegClass);
9617 return RCPair(0U, &ARM::SPR_8RegClass);
9618 if (VT.getSizeInBits() == 64)
9619 return RCPair(0U, &ARM::DPR_8RegClass);
9620 if (VT.getSizeInBits() == 128)
9621 return RCPair(0U, &ARM::QPR_8RegClass);
9625 return RCPair(0U, &ARM::SPRRegClass);
9629 if (StringRef("{cc}").equals_lower(Constraint))
9630 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9632 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9635 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9636 /// vector. If it is invalid, don't add anything to Ops.
9637 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9638 std::string &Constraint,
9639 std::vector<SDValue>&Ops,
9640 SelectionDAG &DAG) const {
9641 SDValue Result(0, 0);
9643 // Currently only support length 1 constraints.
9644 if (Constraint.length() != 1) return;
9646 char ConstraintLetter = Constraint[0];
9647 switch (ConstraintLetter) {
9650 case 'I': case 'J': case 'K': case 'L':
9651 case 'M': case 'N': case 'O':
9652 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9656 int64_t CVal64 = C->getSExtValue();
9657 int CVal = (int) CVal64;
9658 // None of these constraints allow values larger than 32 bits. Check
9659 // that the value fits in an int.
9663 switch (ConstraintLetter) {
9665 // Constant suitable for movw, must be between 0 and
9667 if (Subtarget->hasV6T2Ops())
9668 if (CVal >= 0 && CVal <= 65535)
9672 if (Subtarget->isThumb1Only()) {
9673 // This must be a constant between 0 and 255, for ADD
9675 if (CVal >= 0 && CVal <= 255)
9677 } else if (Subtarget->isThumb2()) {
9678 // A constant that can be used as an immediate value in a
9679 // data-processing instruction.
9680 if (ARM_AM::getT2SOImmVal(CVal) != -1)
9683 // A constant that can be used as an immediate value in a
9684 // data-processing instruction.
9685 if (ARM_AM::getSOImmVal(CVal) != -1)
9691 if (Subtarget->isThumb()) { // FIXME thumb2
9692 // This must be a constant between -255 and -1, for negated ADD
9693 // immediates. This can be used in GCC with an "n" modifier that
9694 // prints the negated value, for use with SUB instructions. It is
9695 // not useful otherwise but is implemented for compatibility.
9696 if (CVal >= -255 && CVal <= -1)
9699 // This must be a constant between -4095 and 4095. It is not clear
9700 // what this constraint is intended for. Implemented for
9701 // compatibility with GCC.
9702 if (CVal >= -4095 && CVal <= 4095)
9708 if (Subtarget->isThumb1Only()) {
9709 // A 32-bit value where only one byte has a nonzero value. Exclude
9710 // zero to match GCC. This constraint is used by GCC internally for
9711 // constants that can be loaded with a move/shift combination.
9712 // It is not useful otherwise but is implemented for compatibility.
9713 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9715 } else if (Subtarget->isThumb2()) {
9716 // A constant whose bitwise inverse can be used as an immediate
9717 // value in a data-processing instruction. This can be used in GCC
9718 // with a "B" modifier that prints the inverted value, for use with
9719 // BIC and MVN instructions. It is not useful otherwise but is
9720 // implemented for compatibility.
9721 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9724 // A constant whose bitwise inverse can be used as an immediate
9725 // value in a data-processing instruction. This can be used in GCC
9726 // with a "B" modifier that prints the inverted value, for use with
9727 // BIC and MVN instructions. It is not useful otherwise but is
9728 // implemented for compatibility.
9729 if (ARM_AM::getSOImmVal(~CVal) != -1)
9735 if (Subtarget->isThumb1Only()) {
9736 // This must be a constant between -7 and 7,
9737 // for 3-operand ADD/SUB immediate instructions.
9738 if (CVal >= -7 && CVal < 7)
9740 } else if (Subtarget->isThumb2()) {
9741 // A constant whose negation can be used as an immediate value in a
9742 // data-processing instruction. This can be used in GCC with an "n"
9743 // modifier that prints the negated value, for use with SUB
9744 // instructions. It is not useful otherwise but is implemented for
9746 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9749 // A constant whose negation can be used as an immediate value in a
9750 // data-processing instruction. This can be used in GCC with an "n"
9751 // modifier that prints the negated value, for use with SUB
9752 // instructions. It is not useful otherwise but is implemented for
9754 if (ARM_AM::getSOImmVal(-CVal) != -1)
9760 if (Subtarget->isThumb()) { // FIXME thumb2
9761 // This must be a multiple of 4 between 0 and 1020, for
9762 // ADD sp + immediate.
9763 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9766 // A power of two or a constant between 0 and 32. This is used in
9767 // GCC for the shift amount on shifted register operands, but it is
9768 // useful in general for any shift amounts.
9769 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9775 if (Subtarget->isThumb()) { // FIXME thumb2
9776 // This must be a constant between 0 and 31, for shift amounts.
9777 if (CVal >= 0 && CVal <= 31)
9783 if (Subtarget->isThumb()) { // FIXME thumb2
9784 // This must be a multiple of 4 between -508 and 508, for
9785 // ADD/SUB sp = sp + immediate.
9786 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9791 Result = DAG.getTargetConstant(CVal, Op.getValueType());
9795 if (Result.getNode()) {
9796 Ops.push_back(Result);
9799 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9803 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9804 // The ARM target isn't yet aware of offsets.
9808 bool ARM::isBitFieldInvertedMask(unsigned v) {
9809 if (v == 0xffffffff)
9811 // there can be 1's on either or both "outsides", all the "inside"
9813 unsigned int lsb = 0, msb = 31;
9814 while (v & (1 << msb)) --msb;
9815 while (v & (1 << lsb)) ++lsb;
9816 for (unsigned int i = lsb; i <= msb; ++i) {
9823 /// isFPImmLegal - Returns true if the target can instruction select the
9824 /// specified FP immediate natively. If false, the legalizer will
9825 /// materialize the FP immediate as a load from a constant pool.
9826 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9827 if (!Subtarget->hasVFP3())
9830 return ARM_AM::getFP32Imm(Imm) != -1;
9832 return ARM_AM::getFP64Imm(Imm) != -1;
9836 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9837 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
9838 /// specified in the intrinsic calls.
9839 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9841 unsigned Intrinsic) const {
9842 switch (Intrinsic) {
9843 case Intrinsic::arm_neon_vld1:
9844 case Intrinsic::arm_neon_vld2:
9845 case Intrinsic::arm_neon_vld3:
9846 case Intrinsic::arm_neon_vld4:
9847 case Intrinsic::arm_neon_vld2lane:
9848 case Intrinsic::arm_neon_vld3lane:
9849 case Intrinsic::arm_neon_vld4lane: {
9850 Info.opc = ISD::INTRINSIC_W_CHAIN;
9851 // Conservatively set memVT to the entire set of vectors loaded.
9852 uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9853 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9854 Info.ptrVal = I.getArgOperand(0);
9856 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9857 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9858 Info.vol = false; // volatile loads with NEON intrinsics not supported
9859 Info.readMem = true;
9860 Info.writeMem = false;
9863 case Intrinsic::arm_neon_vst1:
9864 case Intrinsic::arm_neon_vst2:
9865 case Intrinsic::arm_neon_vst3:
9866 case Intrinsic::arm_neon_vst4:
9867 case Intrinsic::arm_neon_vst2lane:
9868 case Intrinsic::arm_neon_vst3lane:
9869 case Intrinsic::arm_neon_vst4lane: {
9870 Info.opc = ISD::INTRINSIC_VOID;
9871 // Conservatively set memVT to the entire set of vectors stored.
9872 unsigned NumElts = 0;
9873 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9874 Type *ArgTy = I.getArgOperand(ArgI)->getType();
9875 if (!ArgTy->isVectorTy())
9877 NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9879 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9880 Info.ptrVal = I.getArgOperand(0);
9882 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9883 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9884 Info.vol = false; // volatile stores with NEON intrinsics not supported
9885 Info.readMem = false;
9886 Info.writeMem = true;
9889 case Intrinsic::arm_strexd: {
9890 Info.opc = ISD::INTRINSIC_W_CHAIN;
9891 Info.memVT = MVT::i64;
9892 Info.ptrVal = I.getArgOperand(2);
9896 Info.readMem = false;
9897 Info.writeMem = true;
9900 case Intrinsic::arm_ldrexd: {
9901 Info.opc = ISD::INTRINSIC_W_CHAIN;
9902 Info.memVT = MVT::i64;
9903 Info.ptrVal = I.getArgOperand(0);
9907 Info.readMem = true;
9908 Info.writeMem = false;