1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/Function.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/Instruction.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Type.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/IntrinsicLowering.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57 // This option should go away when tail calls fully work.
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65 cl::desc("Generate calls via indirect call instructions"),
69 ARMInterworking("arm-interworking", cl::Hidden,
70 cl::desc("Enable / disable ARM interworking (for debugging only)"),
74 class ARMCCState : public CCState {
76 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77 const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78 LLVMContext &C, ParmContext PC)
79 : CCState(CC, isVarArg, MF, TM, locs, C) {
80 assert(((PC == Call) || (PC == Prologue)) &&
81 "ARMCCState users must specify whether their context is call"
82 "or prologue generation.");
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90 ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94 MVT PromotedBitwiseVT) {
95 if (VT != PromotedLdStVT) {
96 setOperationAction(ISD::LOAD, VT, Promote);
97 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
99 setOperationAction(ISD::STORE, VT, Promote);
100 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
103 MVT ElemTy = VT.getVectorElementType();
104 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105 setOperationAction(ISD::SETCC, VT, Custom);
106 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108 if (ElemTy == MVT::i32) {
109 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
114 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
119 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
120 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
121 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
122 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123 setOperationAction(ISD::SELECT, VT, Expand);
124 setOperationAction(ISD::SELECT_CC, VT, Expand);
125 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
126 if (VT.isInteger()) {
127 setOperationAction(ISD::SHL, VT, Custom);
128 setOperationAction(ISD::SRA, VT, Custom);
129 setOperationAction(ISD::SRL, VT, Custom);
132 // Promote all bit-wise operations.
133 if (VT.isInteger() && VT != PromotedBitwiseVT) {
134 setOperationAction(ISD::AND, VT, Promote);
135 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
136 setOperationAction(ISD::OR, VT, Promote);
137 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
138 setOperationAction(ISD::XOR, VT, Promote);
139 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
142 // Neon does not support vector divide/remainder operations.
143 setOperationAction(ISD::SDIV, VT, Expand);
144 setOperationAction(ISD::UDIV, VT, Expand);
145 setOperationAction(ISD::FDIV, VT, Expand);
146 setOperationAction(ISD::SREM, VT, Expand);
147 setOperationAction(ISD::UREM, VT, Expand);
148 setOperationAction(ISD::FREM, VT, Expand);
151 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
152 addRegisterClass(VT, &ARM::DPRRegClass);
153 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
156 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
157 addRegisterClass(VT, &ARM::QPRRegClass);
158 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
161 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
162 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
163 return new TargetLoweringObjectFileMachO();
165 return new ARMElfTargetObjectFile();
168 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
169 : TargetLowering(TM, createTLOF(TM)) {
170 Subtarget = &TM.getSubtarget<ARMSubtarget>();
171 RegInfo = TM.getRegisterInfo();
172 Itins = TM.getInstrItineraryData();
174 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176 if (Subtarget->isTargetDarwin()) {
177 // Uses VFP for Thumb libfuncs if available.
178 if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
179 // Single-precision floating-point arithmetic.
180 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
181 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
182 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
183 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185 // Double-precision floating-point arithmetic.
186 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
187 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
188 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
189 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191 // Single-precision comparisons.
192 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
193 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
194 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
195 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
196 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
197 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
198 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
199 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
201 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
210 // Double-precision comparisons.
211 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
212 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
213 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
214 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
215 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
216 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
217 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
218 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
220 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
229 // Floating-point to integer conversions.
230 // i64 conversions are done via library routines even when generating VFP
231 // instructions, so use the same ones.
232 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
233 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
234 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
235 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237 // Conversions between floating types.
238 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
239 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
241 // Integer to floating-point conversions.
242 // i64 conversions are done via library routines even when generating VFP
243 // instructions, so use the same ones.
244 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
245 // e.g., __floatunsidf vs. __floatunssidfvfp.
246 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
247 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
248 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
249 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
253 // These libcalls are not available in 32-bit.
254 setLibcallName(RTLIB::SHL_I128, 0);
255 setLibcallName(RTLIB::SRL_I128, 0);
256 setLibcallName(RTLIB::SRA_I128, 0);
258 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
259 // Double-precision floating-point arithmetic helper functions
260 // RTABI chapter 4.1.2, Table 2
261 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
262 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
263 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
264 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
265 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
266 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
267 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
268 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270 // Double-precision floating-point comparison helper functions
271 // RTABI chapter 4.1.2, Table 3
272 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
273 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
274 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
275 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
276 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
277 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
278 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
279 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
280 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
281 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
282 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
283 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
284 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
285 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
286 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
287 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
288 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
289 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
290 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297 // Single-precision floating-point arithmetic helper functions
298 // RTABI chapter 4.1.2, Table 4
299 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
300 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
301 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
302 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
303 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
304 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
305 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
306 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308 // Single-precision floating-point comparison helper functions
309 // RTABI chapter 4.1.2, Table 5
310 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
311 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
312 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
313 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
314 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
315 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
316 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
317 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
318 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
319 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
320 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
321 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
322 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
323 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
324 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
325 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
326 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
327 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
328 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335 // Floating-point to integer conversions.
336 // RTABI chapter 4.1.2, Table 6
337 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
338 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
339 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
340 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
341 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
342 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
343 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
344 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
345 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
346 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
347 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354 // Conversions between floating types.
355 // RTABI chapter 4.1.2, Table 7
356 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
357 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
358 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
359 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361 // Integer to floating-point conversions.
362 // RTABI chapter 4.1.2, Table 8
363 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
364 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
365 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
366 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
367 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
368 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
369 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
370 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
371 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
372 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380 // Long long helper functions
381 // RTABI chapter 4.2, Table 9
382 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
383 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
384 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
385 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
386 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
387 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
388 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393 // Integer division functions
394 // RTABI chapter 4.3.1
395 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
396 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
397 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
398 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
399 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
400 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
401 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
402 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
403 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
404 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
405 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
413 // RTABI chapter 4.3.4
414 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
415 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
416 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
417 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
418 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
419 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
422 // Use divmod compiler-rt calls for iOS 5.0 and later.
423 if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
424 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
425 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
426 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
429 if (Subtarget->isThumb1Only())
430 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
433 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
434 !Subtarget->isThumb1Only()) {
435 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
436 if (!Subtarget->isFPOnlySP())
437 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
442 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
444 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
445 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
446 setTruncStoreAction((MVT::SimpleValueType)VT,
447 (MVT::SimpleValueType)InnerVT, Expand);
448 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
449 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
453 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455 if (Subtarget->hasNEON()) {
456 addDRTypeForNEON(MVT::v2f32);
457 addDRTypeForNEON(MVT::v8i8);
458 addDRTypeForNEON(MVT::v4i16);
459 addDRTypeForNEON(MVT::v2i32);
460 addDRTypeForNEON(MVT::v1i64);
462 addQRTypeForNEON(MVT::v4f32);
463 addQRTypeForNEON(MVT::v2f64);
464 addQRTypeForNEON(MVT::v16i8);
465 addQRTypeForNEON(MVT::v8i16);
466 addQRTypeForNEON(MVT::v4i32);
467 addQRTypeForNEON(MVT::v2i64);
469 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
470 // neither Neon nor VFP support any arithmetic operations on it.
471 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
472 // supported for v4f32.
473 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
474 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
475 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
476 // FIXME: Code duplication: FDIV and FREM are expanded always, see
477 // ARMTargetLowering::addTypeForNEON method for details.
478 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
479 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
480 // FIXME: Create unittest.
481 // In another words, find a way when "copysign" appears in DAG with vector
483 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
484 // FIXME: Code duplication: SETCC has custom operation action, see
485 // ARMTargetLowering::addTypeForNEON method for details.
486 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
487 // FIXME: Create unittest for FNEG and for FABS.
488 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
489 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
490 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
491 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
492 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
493 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
494 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
495 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
496 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
497 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
498 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
499 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
500 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
501 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
502 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
503 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
504 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
505 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
508 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
509 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
510 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
511 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
512 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
513 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
514 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
515 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
516 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
518 // Neon does not support some operations on v1i64 and v2i64 types.
519 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
520 // Custom handling for some quad-vector types to detect VMULL.
521 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
522 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
523 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
524 // Custom handling for some vector types to avoid expensive expansions
525 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
526 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
527 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
528 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
529 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
530 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
531 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
532 // a destination type that is wider than the source, and nor does
533 // it have a FP_TO_[SU]INT instruction with a narrower destination than
535 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
536 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
537 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
538 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
540 setTargetDAGCombine(ISD::INTRINSIC_VOID);
541 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
542 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
543 setTargetDAGCombine(ISD::SHL);
544 setTargetDAGCombine(ISD::SRL);
545 setTargetDAGCombine(ISD::SRA);
546 setTargetDAGCombine(ISD::SIGN_EXTEND);
547 setTargetDAGCombine(ISD::ZERO_EXTEND);
548 setTargetDAGCombine(ISD::ANY_EXTEND);
549 setTargetDAGCombine(ISD::SELECT_CC);
550 setTargetDAGCombine(ISD::BUILD_VECTOR);
551 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
552 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
553 setTargetDAGCombine(ISD::STORE);
554 setTargetDAGCombine(ISD::FP_TO_SINT);
555 setTargetDAGCombine(ISD::FP_TO_UINT);
556 setTargetDAGCombine(ISD::FDIV);
558 // It is legal to extload from v4i8 to v4i16 or v4i32.
559 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
560 MVT::v4i16, MVT::v2i16,
562 for (unsigned i = 0; i < 6; ++i) {
563 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
564 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
565 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
569 // ARM and Thumb2 support UMLAL/SMLAL.
570 if (!Subtarget->isThumb1Only())
571 setTargetDAGCombine(ISD::ADDC);
574 computeRegisterProperties();
576 // ARM does not have f32 extending load.
577 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
579 // ARM does not have i1 sign extending load.
580 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
582 // ARM supports all 4 flavors of integer indexed load / store.
583 if (!Subtarget->isThumb1Only()) {
584 for (unsigned im = (unsigned)ISD::PRE_INC;
585 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
586 setIndexedLoadAction(im, MVT::i1, Legal);
587 setIndexedLoadAction(im, MVT::i8, Legal);
588 setIndexedLoadAction(im, MVT::i16, Legal);
589 setIndexedLoadAction(im, MVT::i32, Legal);
590 setIndexedStoreAction(im, MVT::i1, Legal);
591 setIndexedStoreAction(im, MVT::i8, Legal);
592 setIndexedStoreAction(im, MVT::i16, Legal);
593 setIndexedStoreAction(im, MVT::i32, Legal);
597 // i64 operation support.
598 setOperationAction(ISD::MUL, MVT::i64, Expand);
599 setOperationAction(ISD::MULHU, MVT::i32, Expand);
600 if (Subtarget->isThumb1Only()) {
601 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
602 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
604 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
605 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
606 setOperationAction(ISD::MULHS, MVT::i32, Expand);
608 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
609 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
610 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
611 setOperationAction(ISD::SRL, MVT::i64, Custom);
612 setOperationAction(ISD::SRA, MVT::i64, Custom);
614 if (!Subtarget->isThumb1Only()) {
615 // FIXME: We should do this for Thumb1 as well.
616 setOperationAction(ISD::ADDC, MVT::i32, Custom);
617 setOperationAction(ISD::ADDE, MVT::i32, Custom);
618 setOperationAction(ISD::SUBC, MVT::i32, Custom);
619 setOperationAction(ISD::SUBE, MVT::i32, Custom);
622 // ARM does not have ROTL.
623 setOperationAction(ISD::ROTL, MVT::i32, Expand);
624 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
625 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
626 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
627 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
629 // These just redirect to CTTZ and CTLZ on ARM.
630 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
631 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
633 // Only ARMv6 has BSWAP.
634 if (!Subtarget->hasV6Ops())
635 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
637 // These are expanded into libcalls.
638 if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
639 // v7M has a hardware divider
640 setOperationAction(ISD::SDIV, MVT::i32, Expand);
641 setOperationAction(ISD::UDIV, MVT::i32, Expand);
643 setOperationAction(ISD::SREM, MVT::i32, Expand);
644 setOperationAction(ISD::UREM, MVT::i32, Expand);
645 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
646 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
648 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
649 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
650 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
651 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
652 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
654 setOperationAction(ISD::TRAP, MVT::Other, Legal);
656 // Use the default implementation.
657 setOperationAction(ISD::VASTART, MVT::Other, Custom);
658 setOperationAction(ISD::VAARG, MVT::Other, Expand);
659 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
660 setOperationAction(ISD::VAEND, MVT::Other, Expand);
661 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
662 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
664 if (!Subtarget->isTargetDarwin()) {
665 // Non-Darwin platforms may return values in these registers via the
666 // personality function.
667 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
668 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
669 setExceptionPointerRegister(ARM::R0);
670 setExceptionSelectorRegister(ARM::R1);
673 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
674 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
675 // the default expansion.
676 // FIXME: This should be checking for v6k, not just v6.
677 if (Subtarget->hasDataBarrier() ||
678 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
679 // membarrier needs custom lowering; the rest are legal and handled
681 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
682 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
683 // Custom lowering for 64-bit ops
684 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
685 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
686 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
687 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
688 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
689 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
690 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
691 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
692 setInsertFencesForAtomic(true);
694 // Set them all for expansion, which will force libcalls.
695 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
696 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
697 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
698 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
699 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
700 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
701 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
702 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
703 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
704 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
705 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
706 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
707 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
708 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
709 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
710 // Unordered/Monotonic case.
711 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
712 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
713 // Since the libcalls include locking, fold in the fences
714 setShouldFoldAtomicFences(true);
717 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
719 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
720 if (!Subtarget->hasV6Ops()) {
721 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
722 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
724 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
726 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
727 !Subtarget->isThumb1Only()) {
728 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
729 // iff target supports vfp2.
730 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
731 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
734 // We want to custom lower some of our intrinsics.
735 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
736 if (Subtarget->isTargetDarwin()) {
737 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
738 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
739 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
742 setOperationAction(ISD::SETCC, MVT::i32, Expand);
743 setOperationAction(ISD::SETCC, MVT::f32, Expand);
744 setOperationAction(ISD::SETCC, MVT::f64, Expand);
745 setOperationAction(ISD::SELECT, MVT::i32, Custom);
746 setOperationAction(ISD::SELECT, MVT::f32, Custom);
747 setOperationAction(ISD::SELECT, MVT::f64, Custom);
748 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
749 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
750 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
752 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
753 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
754 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
755 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
756 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
758 // We don't support sin/cos/fmod/copysign/pow
759 setOperationAction(ISD::FSIN, MVT::f64, Expand);
760 setOperationAction(ISD::FSIN, MVT::f32, Expand);
761 setOperationAction(ISD::FCOS, MVT::f32, Expand);
762 setOperationAction(ISD::FCOS, MVT::f64, Expand);
763 setOperationAction(ISD::FREM, MVT::f64, Expand);
764 setOperationAction(ISD::FREM, MVT::f32, Expand);
765 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
766 !Subtarget->isThumb1Only()) {
767 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
768 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
770 setOperationAction(ISD::FPOW, MVT::f64, Expand);
771 setOperationAction(ISD::FPOW, MVT::f32, Expand);
773 if (!Subtarget->hasVFP4()) {
774 setOperationAction(ISD::FMA, MVT::f64, Expand);
775 setOperationAction(ISD::FMA, MVT::f32, Expand);
778 // Various VFP goodness
779 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
780 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
781 if (Subtarget->hasVFP2()) {
782 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
783 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
784 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
785 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
787 // Special handling for half-precision FP.
788 if (!Subtarget->hasFP16()) {
789 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
790 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
794 // We have target-specific dag combine patterns for the following nodes:
795 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
796 setTargetDAGCombine(ISD::ADD);
797 setTargetDAGCombine(ISD::SUB);
798 setTargetDAGCombine(ISD::MUL);
800 if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
801 setTargetDAGCombine(ISD::AND);
802 setTargetDAGCombine(ISD::OR);
803 setTargetDAGCombine(ISD::XOR);
806 if (Subtarget->hasV6Ops())
807 setTargetDAGCombine(ISD::SRL);
809 setStackPointerRegisterToSaveRestore(ARM::SP);
811 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
812 !Subtarget->hasVFP2())
813 setSchedulingPreference(Sched::RegPressure);
815 setSchedulingPreference(Sched::Hybrid);
817 //// temporary - rewrite interface to use type
818 maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
819 maxStoresPerMemset = 16;
820 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
822 // On ARM arguments smaller than 4 bytes are extended, so all arguments
823 // are at least 4 bytes aligned.
824 setMinStackArgumentAlignment(4);
826 benefitFromCodePlacementOpt = true;
828 // Prefer likely predicted branches to selects on out-of-order cores.
829 predictableSelectIsExpensive = Subtarget->isCortexA9();
831 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
834 // FIXME: It might make sense to define the representative register class as the
835 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
836 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
837 // SPR's representative would be DPR_VFP2. This should work well if register
838 // pressure tracking were modified such that a register use would increment the
839 // pressure of the register class's representative and all of it's super
840 // classes' representatives transitively. We have not implemented this because
841 // of the difficulty prior to coalescing of modeling operand register classes
842 // due to the common occurrence of cross class copies and subregister insertions
844 std::pair<const TargetRegisterClass*, uint8_t>
845 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
846 const TargetRegisterClass *RRC = 0;
848 switch (VT.getSimpleVT().SimpleTy) {
850 return TargetLowering::findRepresentativeClass(VT);
851 // Use DPR as representative register class for all floating point
852 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
853 // the cost is 1 for both f32 and f64.
854 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
855 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
856 RRC = &ARM::DPRRegClass;
857 // When NEON is used for SP, only half of the register file is available
858 // because operations that define both SP and DP results will be constrained
859 // to the VFP2 class (D0-D15). We currently model this constraint prior to
860 // coalescing by double-counting the SP regs. See the FIXME above.
861 if (Subtarget->useNEONForSinglePrecisionFP())
864 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
865 case MVT::v4f32: case MVT::v2f64:
866 RRC = &ARM::DPRRegClass;
870 RRC = &ARM::DPRRegClass;
874 RRC = &ARM::DPRRegClass;
878 return std::make_pair(RRC, Cost);
881 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
884 case ARMISD::Wrapper: return "ARMISD::Wrapper";
885 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
886 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
887 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
888 case ARMISD::CALL: return "ARMISD::CALL";
889 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
890 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
891 case ARMISD::tCALL: return "ARMISD::tCALL";
892 case ARMISD::BRCOND: return "ARMISD::BRCOND";
893 case ARMISD::BR_JT: return "ARMISD::BR_JT";
894 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
895 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
896 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
897 case ARMISD::CMP: return "ARMISD::CMP";
898 case ARMISD::CMN: return "ARMISD::CMN";
899 case ARMISD::CMPZ: return "ARMISD::CMPZ";
900 case ARMISD::CMPFP: return "ARMISD::CMPFP";
901 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
902 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
903 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
905 case ARMISD::CMOV: return "ARMISD::CMOV";
906 case ARMISD::CAND: return "ARMISD::CAND";
907 case ARMISD::COR: return "ARMISD::COR";
908 case ARMISD::CXOR: return "ARMISD::CXOR";
910 case ARMISD::RBIT: return "ARMISD::RBIT";
912 case ARMISD::FTOSI: return "ARMISD::FTOSI";
913 case ARMISD::FTOUI: return "ARMISD::FTOUI";
914 case ARMISD::SITOF: return "ARMISD::SITOF";
915 case ARMISD::UITOF: return "ARMISD::UITOF";
917 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
918 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
919 case ARMISD::RRX: return "ARMISD::RRX";
921 case ARMISD::ADDC: return "ARMISD::ADDC";
922 case ARMISD::ADDE: return "ARMISD::ADDE";
923 case ARMISD::SUBC: return "ARMISD::SUBC";
924 case ARMISD::SUBE: return "ARMISD::SUBE";
926 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
927 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
929 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
930 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
932 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
934 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
936 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
938 case ARMISD::MEMBARRIER: return "ARMISD::MEMBARRIER";
939 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
941 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
943 case ARMISD::VCEQ: return "ARMISD::VCEQ";
944 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
945 case ARMISD::VCGE: return "ARMISD::VCGE";
946 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
947 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
948 case ARMISD::VCGEU: return "ARMISD::VCGEU";
949 case ARMISD::VCGT: return "ARMISD::VCGT";
950 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
951 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
952 case ARMISD::VCGTU: return "ARMISD::VCGTU";
953 case ARMISD::VTST: return "ARMISD::VTST";
955 case ARMISD::VSHL: return "ARMISD::VSHL";
956 case ARMISD::VSHRs: return "ARMISD::VSHRs";
957 case ARMISD::VSHRu: return "ARMISD::VSHRu";
958 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
959 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
960 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
961 case ARMISD::VSHRN: return "ARMISD::VSHRN";
962 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
963 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
964 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
965 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
966 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
967 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
968 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
969 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
970 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
971 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
972 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
973 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
974 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
975 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
976 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
977 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
978 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
979 case ARMISD::VDUP: return "ARMISD::VDUP";
980 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
981 case ARMISD::VEXT: return "ARMISD::VEXT";
982 case ARMISD::VREV64: return "ARMISD::VREV64";
983 case ARMISD::VREV32: return "ARMISD::VREV32";
984 case ARMISD::VREV16: return "ARMISD::VREV16";
985 case ARMISD::VZIP: return "ARMISD::VZIP";
986 case ARMISD::VUZP: return "ARMISD::VUZP";
987 case ARMISD::VTRN: return "ARMISD::VTRN";
988 case ARMISD::VTBL1: return "ARMISD::VTBL1";
989 case ARMISD::VTBL2: return "ARMISD::VTBL2";
990 case ARMISD::VMULLs: return "ARMISD::VMULLs";
991 case ARMISD::VMULLu: return "ARMISD::VMULLu";
992 case ARMISD::UMLAL: return "ARMISD::UMLAL";
993 case ARMISD::SMLAL: return "ARMISD::SMLAL";
994 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
995 case ARMISD::FMAX: return "ARMISD::FMAX";
996 case ARMISD::FMIN: return "ARMISD::FMIN";
997 case ARMISD::BFI: return "ARMISD::BFI";
998 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
999 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1000 case ARMISD::VBSL: return "ARMISD::VBSL";
1001 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1002 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1003 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1004 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1005 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1006 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1007 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1008 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1009 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1010 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1011 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1012 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1013 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1014 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1015 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1016 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1017 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1018 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1019 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1020 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1024 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1025 if (!VT.isVector()) return getPointerTy();
1026 return VT.changeVectorElementTypeToInteger();
1029 /// getRegClassFor - Return the register class that should be used for the
1030 /// specified value type.
1031 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1032 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1033 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1034 // load / store 4 to 8 consecutive D registers.
1035 if (Subtarget->hasNEON()) {
1036 if (VT == MVT::v4i64)
1037 return &ARM::QQPRRegClass;
1038 if (VT == MVT::v8i64)
1039 return &ARM::QQQQPRRegClass;
1041 return TargetLowering::getRegClassFor(VT);
1044 // Create a fast isel object.
1046 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1047 const TargetLibraryInfo *libInfo) const {
1048 return ARM::createFastISel(funcInfo, libInfo);
1051 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1052 /// be used for loads / stores from the global.
1053 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1054 return (Subtarget->isThumb1Only() ? 127 : 4095);
1057 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1058 unsigned NumVals = N->getNumValues();
1060 return Sched::RegPressure;
1062 for (unsigned i = 0; i != NumVals; ++i) {
1063 EVT VT = N->getValueType(i);
1064 if (VT == MVT::Glue || VT == MVT::Other)
1066 if (VT.isFloatingPoint() || VT.isVector())
1070 if (!N->isMachineOpcode())
1071 return Sched::RegPressure;
1073 // Load are scheduled for latency even if there instruction itinerary
1074 // is not available.
1075 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1076 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1078 if (MCID.getNumDefs() == 0)
1079 return Sched::RegPressure;
1080 if (!Itins->isEmpty() &&
1081 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1084 return Sched::RegPressure;
1087 //===----------------------------------------------------------------------===//
1089 //===----------------------------------------------------------------------===//
1091 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1092 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1094 default: llvm_unreachable("Unknown condition code!");
1095 case ISD::SETNE: return ARMCC::NE;
1096 case ISD::SETEQ: return ARMCC::EQ;
1097 case ISD::SETGT: return ARMCC::GT;
1098 case ISD::SETGE: return ARMCC::GE;
1099 case ISD::SETLT: return ARMCC::LT;
1100 case ISD::SETLE: return ARMCC::LE;
1101 case ISD::SETUGT: return ARMCC::HI;
1102 case ISD::SETUGE: return ARMCC::HS;
1103 case ISD::SETULT: return ARMCC::LO;
1104 case ISD::SETULE: return ARMCC::LS;
1108 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1109 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1110 ARMCC::CondCodes &CondCode2) {
1111 CondCode2 = ARMCC::AL;
1113 default: llvm_unreachable("Unknown FP condition!");
1115 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1117 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1119 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1120 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1121 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1122 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1123 case ISD::SETO: CondCode = ARMCC::VC; break;
1124 case ISD::SETUO: CondCode = ARMCC::VS; break;
1125 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1126 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1127 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1129 case ISD::SETULT: CondCode = ARMCC::LT; break;
1131 case ISD::SETULE: CondCode = ARMCC::LE; break;
1133 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1137 //===----------------------------------------------------------------------===//
1138 // Calling Convention Implementation
1139 //===----------------------------------------------------------------------===//
1141 #include "ARMGenCallingConv.inc"
1143 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1144 /// given CallingConvention value.
1145 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1147 bool isVarArg) const {
1150 llvm_unreachable("Unsupported calling convention");
1151 case CallingConv::Fast:
1152 if (Subtarget->hasVFP2() && !isVarArg) {
1153 if (!Subtarget->isAAPCS_ABI())
1154 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1155 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1156 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1159 case CallingConv::C: {
1160 // Use target triple & subtarget features to do actual dispatch.
1161 if (!Subtarget->isAAPCS_ABI())
1162 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1163 else if (Subtarget->hasVFP2() &&
1164 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1166 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1167 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1169 case CallingConv::ARM_AAPCS_VFP:
1171 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1173 case CallingConv::ARM_AAPCS:
1174 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1175 case CallingConv::ARM_APCS:
1176 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1177 case CallingConv::GHC:
1178 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1182 /// LowerCallResult - Lower the result values of a call into the
1183 /// appropriate copies out of appropriate physical registers.
1185 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1186 CallingConv::ID CallConv, bool isVarArg,
1187 const SmallVectorImpl<ISD::InputArg> &Ins,
1188 DebugLoc dl, SelectionDAG &DAG,
1189 SmallVectorImpl<SDValue> &InVals) const {
1191 // Assign locations to each value returned by this call.
1192 SmallVector<CCValAssign, 16> RVLocs;
1193 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1194 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1195 CCInfo.AnalyzeCallResult(Ins,
1196 CCAssignFnForNode(CallConv, /* Return*/ true,
1199 // Copy all of the result registers out of their specified physreg.
1200 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1201 CCValAssign VA = RVLocs[i];
1204 if (VA.needsCustom()) {
1205 // Handle f64 or half of a v2f64.
1206 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1208 Chain = Lo.getValue(1);
1209 InFlag = Lo.getValue(2);
1210 VA = RVLocs[++i]; // skip ahead to next loc
1211 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1213 Chain = Hi.getValue(1);
1214 InFlag = Hi.getValue(2);
1215 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1217 if (VA.getLocVT() == MVT::v2f64) {
1218 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1219 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1220 DAG.getConstant(0, MVT::i32));
1222 VA = RVLocs[++i]; // skip ahead to next loc
1223 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1224 Chain = Lo.getValue(1);
1225 InFlag = Lo.getValue(2);
1226 VA = RVLocs[++i]; // skip ahead to next loc
1227 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1228 Chain = Hi.getValue(1);
1229 InFlag = Hi.getValue(2);
1230 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1231 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1232 DAG.getConstant(1, MVT::i32));
1235 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1237 Chain = Val.getValue(1);
1238 InFlag = Val.getValue(2);
1241 switch (VA.getLocInfo()) {
1242 default: llvm_unreachable("Unknown loc info!");
1243 case CCValAssign::Full: break;
1244 case CCValAssign::BCvt:
1245 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1249 InVals.push_back(Val);
1255 /// LowerMemOpCallTo - Store the argument to the stack.
1257 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1258 SDValue StackPtr, SDValue Arg,
1259 DebugLoc dl, SelectionDAG &DAG,
1260 const CCValAssign &VA,
1261 ISD::ArgFlagsTy Flags) const {
1262 unsigned LocMemOffset = VA.getLocMemOffset();
1263 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1264 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1265 return DAG.getStore(Chain, dl, Arg, PtrOff,
1266 MachinePointerInfo::getStack(LocMemOffset),
1270 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1271 SDValue Chain, SDValue &Arg,
1272 RegsToPassVector &RegsToPass,
1273 CCValAssign &VA, CCValAssign &NextVA,
1275 SmallVector<SDValue, 8> &MemOpChains,
1276 ISD::ArgFlagsTy Flags) const {
1278 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1279 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1280 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1282 if (NextVA.isRegLoc())
1283 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1285 assert(NextVA.isMemLoc());
1286 if (StackPtr.getNode() == 0)
1287 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1289 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1295 /// LowerCall - Lowering a call into a callseq_start <-
1296 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1299 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1300 SmallVectorImpl<SDValue> &InVals) const {
1301 SelectionDAG &DAG = CLI.DAG;
1302 DebugLoc &dl = CLI.DL;
1303 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1304 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1305 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1306 SDValue Chain = CLI.Chain;
1307 SDValue Callee = CLI.Callee;
1308 bool &isTailCall = CLI.IsTailCall;
1309 CallingConv::ID CallConv = CLI.CallConv;
1310 bool doesNotRet = CLI.DoesNotReturn;
1311 bool isVarArg = CLI.IsVarArg;
1313 MachineFunction &MF = DAG.getMachineFunction();
1314 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1315 bool IsSibCall = false;
1316 // Disable tail calls if they're not supported.
1317 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1320 // Check if it's really possible to do a tail call.
1321 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1322 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1323 Outs, OutVals, Ins, DAG);
1324 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1325 // detected sibcalls.
1332 // Analyze operands of the call, assigning locations to each operand.
1333 SmallVector<CCValAssign, 16> ArgLocs;
1334 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1335 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1336 CCInfo.AnalyzeCallOperands(Outs,
1337 CCAssignFnForNode(CallConv, /* Return*/ false,
1340 // Get a count of how many bytes are to be pushed on the stack.
1341 unsigned NumBytes = CCInfo.getNextStackOffset();
1343 // For tail calls, memory operands are available in our caller's stack.
1347 // Adjust the stack pointer for the new arguments...
1348 // These operations are automatically eliminated by the prolog/epilog pass
1350 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1352 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1354 RegsToPassVector RegsToPass;
1355 SmallVector<SDValue, 8> MemOpChains;
1357 // Walk the register/memloc assignments, inserting copies/loads. In the case
1358 // of tail call optimization, arguments are handled later.
1359 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1361 ++i, ++realArgIdx) {
1362 CCValAssign &VA = ArgLocs[i];
1363 SDValue Arg = OutVals[realArgIdx];
1364 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1365 bool isByVal = Flags.isByVal();
1367 // Promote the value if needed.
1368 switch (VA.getLocInfo()) {
1369 default: llvm_unreachable("Unknown loc info!");
1370 case CCValAssign::Full: break;
1371 case CCValAssign::SExt:
1372 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1374 case CCValAssign::ZExt:
1375 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1377 case CCValAssign::AExt:
1378 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1380 case CCValAssign::BCvt:
1381 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1385 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1386 if (VA.needsCustom()) {
1387 if (VA.getLocVT() == MVT::v2f64) {
1388 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1389 DAG.getConstant(0, MVT::i32));
1390 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1391 DAG.getConstant(1, MVT::i32));
1393 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1394 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1396 VA = ArgLocs[++i]; // skip ahead to next loc
1397 if (VA.isRegLoc()) {
1398 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1399 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1401 assert(VA.isMemLoc());
1403 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1404 dl, DAG, VA, Flags));
1407 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1408 StackPtr, MemOpChains, Flags);
1410 } else if (VA.isRegLoc()) {
1411 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1412 } else if (isByVal) {
1413 assert(VA.isMemLoc());
1414 unsigned offset = 0;
1416 // True if this byval aggregate will be split between registers
1418 if (CCInfo.isFirstByValRegValid()) {
1419 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1421 for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1422 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1423 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1424 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1425 MachinePointerInfo(),
1426 false, false, false, 0);
1427 MemOpChains.push_back(Load.getValue(1));
1428 RegsToPass.push_back(std::make_pair(j, Load));
1430 offset = ARM::R4 - CCInfo.getFirstByValReg();
1431 CCInfo.clearFirstByValReg();
1434 if (Flags.getByValSize() - 4*offset > 0) {
1435 unsigned LocMemOffset = VA.getLocMemOffset();
1436 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1437 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1439 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1440 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1441 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1443 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1445 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1446 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1447 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1448 Ops, array_lengthof(Ops)));
1450 } else if (!IsSibCall) {
1451 assert(VA.isMemLoc());
1453 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1454 dl, DAG, VA, Flags));
1458 if (!MemOpChains.empty())
1459 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1460 &MemOpChains[0], MemOpChains.size());
1462 // Build a sequence of copy-to-reg nodes chained together with token chain
1463 // and flag operands which copy the outgoing args into the appropriate regs.
1465 // Tail call byval lowering might overwrite argument registers so in case of
1466 // tail call optimization the copies to registers are lowered later.
1468 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1469 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1470 RegsToPass[i].second, InFlag);
1471 InFlag = Chain.getValue(1);
1474 // For tail calls lower the arguments to the 'real' stack slot.
1476 // Force all the incoming stack arguments to be loaded from the stack
1477 // before any new outgoing arguments are stored to the stack, because the
1478 // outgoing stack slots may alias the incoming argument stack slots, and
1479 // the alias isn't otherwise explicit. This is slightly more conservative
1480 // than necessary, because it means that each store effectively depends
1481 // on every argument instead of just those arguments it would clobber.
1483 // Do not flag preceding copytoreg stuff together with the following stuff.
1485 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1486 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1487 RegsToPass[i].second, InFlag);
1488 InFlag = Chain.getValue(1);
1493 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1494 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1495 // node so that legalize doesn't hack it.
1496 bool isDirect = false;
1497 bool isARMFunc = false;
1498 bool isLocalARMFunc = false;
1499 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1501 if (EnableARMLongCalls) {
1502 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1503 && "long-calls with non-static relocation model!");
1504 // Handle a global address or an external symbol. If it's not one of
1505 // those, the target's already in a register, so we don't need to do
1507 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1508 const GlobalValue *GV = G->getGlobal();
1509 // Create a constant pool entry for the callee address
1510 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1511 ARMConstantPoolValue *CPV =
1512 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1514 // Get the address of the callee into a register
1515 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1516 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1517 Callee = DAG.getLoad(getPointerTy(), dl,
1518 DAG.getEntryNode(), CPAddr,
1519 MachinePointerInfo::getConstantPool(),
1520 false, false, false, 0);
1521 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1522 const char *Sym = S->getSymbol();
1524 // Create a constant pool entry for the callee address
1525 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1526 ARMConstantPoolValue *CPV =
1527 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1528 ARMPCLabelIndex, 0);
1529 // Get the address of the callee into a register
1530 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1531 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1532 Callee = DAG.getLoad(getPointerTy(), dl,
1533 DAG.getEntryNode(), CPAddr,
1534 MachinePointerInfo::getConstantPool(),
1535 false, false, false, 0);
1537 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1538 const GlobalValue *GV = G->getGlobal();
1540 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1541 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1542 getTargetMachine().getRelocationModel() != Reloc::Static;
1543 isARMFunc = !Subtarget->isThumb() || isStub;
1544 // ARM call to a local ARM function is predicable.
1545 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1546 // tBX takes a register source operand.
1547 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1548 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1549 ARMConstantPoolValue *CPV =
1550 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1551 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1552 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1553 Callee = DAG.getLoad(getPointerTy(), dl,
1554 DAG.getEntryNode(), CPAddr,
1555 MachinePointerInfo::getConstantPool(),
1556 false, false, false, 0);
1557 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1558 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1559 getPointerTy(), Callee, PICLabel);
1561 // On ELF targets for PIC code, direct calls should go through the PLT
1562 unsigned OpFlags = 0;
1563 if (Subtarget->isTargetELF() &&
1564 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1565 OpFlags = ARMII::MO_PLT;
1566 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1568 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1570 bool isStub = Subtarget->isTargetDarwin() &&
1571 getTargetMachine().getRelocationModel() != Reloc::Static;
1572 isARMFunc = !Subtarget->isThumb() || isStub;
1573 // tBX takes a register source operand.
1574 const char *Sym = S->getSymbol();
1575 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1576 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1577 ARMConstantPoolValue *CPV =
1578 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1579 ARMPCLabelIndex, 4);
1580 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1581 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1582 Callee = DAG.getLoad(getPointerTy(), dl,
1583 DAG.getEntryNode(), CPAddr,
1584 MachinePointerInfo::getConstantPool(),
1585 false, false, false, 0);
1586 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1587 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1588 getPointerTy(), Callee, PICLabel);
1590 unsigned OpFlags = 0;
1591 // On ELF targets for PIC code, direct calls should go through the PLT
1592 if (Subtarget->isTargetELF() &&
1593 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1594 OpFlags = ARMII::MO_PLT;
1595 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1599 // FIXME: handle tail calls differently.
1601 if (Subtarget->isThumb()) {
1602 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1603 CallOpc = ARMISD::CALL_NOLINK;
1604 else if (doesNotRet && isDirect && !isARMFunc &&
1605 Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1606 // "mov lr, pc; b _foo" to avoid confusing the RSP
1607 CallOpc = ARMISD::CALL_NOLINK;
1609 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1611 if (!isDirect && !Subtarget->hasV5TOps()) {
1612 CallOpc = ARMISD::CALL_NOLINK;
1613 } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1614 // "mov lr, pc; b _foo" to avoid confusing the RSP
1615 CallOpc = ARMISD::CALL_NOLINK;
1617 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1620 std::vector<SDValue> Ops;
1621 Ops.push_back(Chain);
1622 Ops.push_back(Callee);
1624 // Add argument registers to the end of the list so that they are known live
1626 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1627 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1628 RegsToPass[i].second.getValueType()));
1630 // Add a register mask operand representing the call-preserved registers.
1631 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1632 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1633 assert(Mask && "Missing call preserved mask for calling convention");
1634 Ops.push_back(DAG.getRegisterMask(Mask));
1636 if (InFlag.getNode())
1637 Ops.push_back(InFlag);
1639 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1641 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1643 // Returns a chain and a flag for retval copy to use.
1644 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1645 InFlag = Chain.getValue(1);
1647 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1648 DAG.getIntPtrConstant(0, true), InFlag);
1650 InFlag = Chain.getValue(1);
1652 // Handle result values, copying them out of physregs into vregs that we
1654 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1658 /// HandleByVal - Every parameter *after* a byval parameter is passed
1659 /// on the stack. Remember the next parameter register to allocate,
1660 /// and then confiscate the rest of the parameter registers to insure
1663 ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1664 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1665 assert((State->getCallOrPrologue() == Prologue ||
1666 State->getCallOrPrologue() == Call) &&
1667 "unhandled ParmContext");
1668 if ((!State->isFirstByValRegValid()) &&
1669 (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1670 State->setFirstByValReg(reg);
1671 // At a call site, a byval parameter that is split between
1672 // registers and memory needs its size truncated here. In a
1673 // function prologue, such byval parameters are reassembled in
1674 // memory, and are not truncated.
1675 if (State->getCallOrPrologue() == Call) {
1676 unsigned excess = 4 * (ARM::R4 - reg);
1677 assert(size >= excess && "expected larger existing stack allocation");
1681 // Confiscate any remaining parameter registers to preclude their
1682 // assignment to subsequent parameters.
1683 while (State->AllocateReg(GPRArgRegs, 4))
1687 /// MatchingStackOffset - Return true if the given stack call argument is
1688 /// already available in the same position (relatively) of the caller's
1689 /// incoming argument stack.
1691 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1692 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1693 const TargetInstrInfo *TII) {
1694 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1696 if (Arg.getOpcode() == ISD::CopyFromReg) {
1697 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1698 if (!TargetRegisterInfo::isVirtualRegister(VR))
1700 MachineInstr *Def = MRI->getVRegDef(VR);
1703 if (!Flags.isByVal()) {
1704 if (!TII->isLoadFromStackSlot(Def, FI))
1709 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1710 if (Flags.isByVal())
1711 // ByVal argument is passed in as a pointer but it's now being
1712 // dereferenced. e.g.
1713 // define @foo(%struct.X* %A) {
1714 // tail call @bar(%struct.X* byval %A)
1717 SDValue Ptr = Ld->getBasePtr();
1718 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1721 FI = FINode->getIndex();
1725 assert(FI != INT_MAX);
1726 if (!MFI->isFixedObjectIndex(FI))
1728 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1731 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1732 /// for tail call optimization. Targets which want to do tail call
1733 /// optimization should implement this function.
1735 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1736 CallingConv::ID CalleeCC,
1738 bool isCalleeStructRet,
1739 bool isCallerStructRet,
1740 const SmallVectorImpl<ISD::OutputArg> &Outs,
1741 const SmallVectorImpl<SDValue> &OutVals,
1742 const SmallVectorImpl<ISD::InputArg> &Ins,
1743 SelectionDAG& DAG) const {
1744 const Function *CallerF = DAG.getMachineFunction().getFunction();
1745 CallingConv::ID CallerCC = CallerF->getCallingConv();
1746 bool CCMatch = CallerCC == CalleeCC;
1748 // Look for obvious safe cases to perform tail call optimization that do not
1749 // require ABI changes. This is what gcc calls sibcall.
1751 // Do not sibcall optimize vararg calls unless the call site is not passing
1753 if (isVarArg && !Outs.empty())
1756 // Also avoid sibcall optimization if either caller or callee uses struct
1757 // return semantics.
1758 if (isCalleeStructRet || isCallerStructRet)
1761 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1762 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1763 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1764 // support in the assembler and linker to be used. This would need to be
1765 // fixed to fully support tail calls in Thumb1.
1767 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1768 // LR. This means if we need to reload LR, it takes an extra instructions,
1769 // which outweighs the value of the tail call; but here we don't know yet
1770 // whether LR is going to be used. Probably the right approach is to
1771 // generate the tail call here and turn it back into CALL/RET in
1772 // emitEpilogue if LR is used.
1774 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1775 // but we need to make sure there are enough registers; the only valid
1776 // registers are the 4 used for parameters. We don't currently do this
1778 if (Subtarget->isThumb1Only())
1781 // If the calling conventions do not match, then we'd better make sure the
1782 // results are returned in the same way as what the caller expects.
1784 SmallVector<CCValAssign, 16> RVLocs1;
1785 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1786 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1787 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1789 SmallVector<CCValAssign, 16> RVLocs2;
1790 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1791 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1792 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1794 if (RVLocs1.size() != RVLocs2.size())
1796 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1797 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1799 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1801 if (RVLocs1[i].isRegLoc()) {
1802 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1805 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1811 // If the callee takes no arguments then go on to check the results of the
1813 if (!Outs.empty()) {
1814 // Check if stack adjustment is needed. For now, do not do this if any
1815 // argument is passed on the stack.
1816 SmallVector<CCValAssign, 16> ArgLocs;
1817 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1818 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1819 CCInfo.AnalyzeCallOperands(Outs,
1820 CCAssignFnForNode(CalleeCC, false, isVarArg));
1821 if (CCInfo.getNextStackOffset()) {
1822 MachineFunction &MF = DAG.getMachineFunction();
1824 // Check if the arguments are already laid out in the right way as
1825 // the caller's fixed stack objects.
1826 MachineFrameInfo *MFI = MF.getFrameInfo();
1827 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1828 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1829 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1831 ++i, ++realArgIdx) {
1832 CCValAssign &VA = ArgLocs[i];
1833 EVT RegVT = VA.getLocVT();
1834 SDValue Arg = OutVals[realArgIdx];
1835 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1836 if (VA.getLocInfo() == CCValAssign::Indirect)
1838 if (VA.needsCustom()) {
1839 // f64 and vector types are split into multiple registers or
1840 // register/stack-slot combinations. The types will not match
1841 // the registers; give up on memory f64 refs until we figure
1842 // out what to do about this.
1845 if (!ArgLocs[++i].isRegLoc())
1847 if (RegVT == MVT::v2f64) {
1848 if (!ArgLocs[++i].isRegLoc())
1850 if (!ArgLocs[++i].isRegLoc())
1853 } else if (!VA.isRegLoc()) {
1854 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1866 ARMTargetLowering::LowerReturn(SDValue Chain,
1867 CallingConv::ID CallConv, bool isVarArg,
1868 const SmallVectorImpl<ISD::OutputArg> &Outs,
1869 const SmallVectorImpl<SDValue> &OutVals,
1870 DebugLoc dl, SelectionDAG &DAG) const {
1872 // CCValAssign - represent the assignment of the return value to a location.
1873 SmallVector<CCValAssign, 16> RVLocs;
1875 // CCState - Info about the registers and stack slots.
1876 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1877 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1879 // Analyze outgoing return values.
1880 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1883 // If this is the first return lowered for this function, add
1884 // the regs to the liveout set for the function.
1885 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1886 for (unsigned i = 0; i != RVLocs.size(); ++i)
1887 if (RVLocs[i].isRegLoc())
1888 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1893 // Copy the result values into the output registers.
1894 for (unsigned i = 0, realRVLocIdx = 0;
1896 ++i, ++realRVLocIdx) {
1897 CCValAssign &VA = RVLocs[i];
1898 assert(VA.isRegLoc() && "Can only return in registers!");
1900 SDValue Arg = OutVals[realRVLocIdx];
1902 switch (VA.getLocInfo()) {
1903 default: llvm_unreachable("Unknown loc info!");
1904 case CCValAssign::Full: break;
1905 case CCValAssign::BCvt:
1906 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1910 if (VA.needsCustom()) {
1911 if (VA.getLocVT() == MVT::v2f64) {
1912 // Extract the first half and return it in two registers.
1913 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1914 DAG.getConstant(0, MVT::i32));
1915 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1916 DAG.getVTList(MVT::i32, MVT::i32), Half);
1918 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1919 Flag = Chain.getValue(1);
1920 VA = RVLocs[++i]; // skip ahead to next loc
1921 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1922 HalfGPRs.getValue(1), Flag);
1923 Flag = Chain.getValue(1);
1924 VA = RVLocs[++i]; // skip ahead to next loc
1926 // Extract the 2nd half and fall through to handle it as an f64 value.
1927 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1928 DAG.getConstant(1, MVT::i32));
1930 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
1932 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1933 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1934 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1935 Flag = Chain.getValue(1);
1936 VA = RVLocs[++i]; // skip ahead to next loc
1937 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1940 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1942 // Guarantee that all emitted copies are
1943 // stuck together, avoiding something bad.
1944 Flag = Chain.getValue(1);
1949 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1951 result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1956 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1957 if (N->getNumValues() != 1)
1959 if (!N->hasNUsesOfValue(1, 0))
1962 SDValue TCChain = Chain;
1963 SDNode *Copy = *N->use_begin();
1964 if (Copy->getOpcode() == ISD::CopyToReg) {
1965 // If the copy has a glue operand, we conservatively assume it isn't safe to
1966 // perform a tail call.
1967 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1969 TCChain = Copy->getOperand(0);
1970 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
1971 SDNode *VMov = Copy;
1972 // f64 returned in a pair of GPRs.
1973 SmallPtrSet<SDNode*, 2> Copies;
1974 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1976 if (UI->getOpcode() != ISD::CopyToReg)
1980 if (Copies.size() > 2)
1983 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
1985 SDValue UseChain = UI->getOperand(0);
1986 if (Copies.count(UseChain.getNode()))
1993 } else if (Copy->getOpcode() == ISD::BITCAST) {
1994 // f32 returned in a single GPR.
1995 if (!Copy->hasOneUse())
1997 Copy = *Copy->use_begin();
1998 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2000 Chain = Copy->getOperand(0);
2005 bool HasRet = false;
2006 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2008 if (UI->getOpcode() != ARMISD::RET_FLAG)
2020 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2021 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2024 if (!CI->isTailCall())
2027 return !Subtarget->isThumb1Only();
2030 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2031 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2032 // one of the above mentioned nodes. It has to be wrapped because otherwise
2033 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2034 // be used to form addressing mode. These wrapped nodes will be selected
2036 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2037 EVT PtrVT = Op.getValueType();
2038 // FIXME there is no actual debug info here
2039 DebugLoc dl = Op.getDebugLoc();
2040 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2042 if (CP->isMachineConstantPoolEntry())
2043 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2044 CP->getAlignment());
2046 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2047 CP->getAlignment());
2048 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2051 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2052 return MachineJumpTableInfo::EK_Inline;
2055 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2056 SelectionDAG &DAG) const {
2057 MachineFunction &MF = DAG.getMachineFunction();
2058 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2059 unsigned ARMPCLabelIndex = 0;
2060 DebugLoc DL = Op.getDebugLoc();
2061 EVT PtrVT = getPointerTy();
2062 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2063 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2065 if (RelocM == Reloc::Static) {
2066 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2068 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2069 ARMPCLabelIndex = AFI->createPICLabelUId();
2070 ARMConstantPoolValue *CPV =
2071 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2072 ARMCP::CPBlockAddress, PCAdj);
2073 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2075 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2076 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2077 MachinePointerInfo::getConstantPool(),
2078 false, false, false, 0);
2079 if (RelocM == Reloc::Static)
2081 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2082 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2085 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2087 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2088 SelectionDAG &DAG) const {
2089 DebugLoc dl = GA->getDebugLoc();
2090 EVT PtrVT = getPointerTy();
2091 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2092 MachineFunction &MF = DAG.getMachineFunction();
2093 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2094 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2095 ARMConstantPoolValue *CPV =
2096 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2097 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2098 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2099 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2100 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2101 MachinePointerInfo::getConstantPool(),
2102 false, false, false, 0);
2103 SDValue Chain = Argument.getValue(1);
2105 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2106 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2108 // call __tls_get_addr.
2111 Entry.Node = Argument;
2112 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2113 Args.push_back(Entry);
2114 // FIXME: is there useful debug info available here?
2115 TargetLowering::CallLoweringInfo CLI(Chain,
2116 (Type *) Type::getInt32Ty(*DAG.getContext()),
2117 false, false, false, false,
2118 0, CallingConv::C, /*isTailCall=*/false,
2119 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2120 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2121 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2122 return CallResult.first;
2125 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2126 // "local exec" model.
2128 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2130 TLSModel::Model model) const {
2131 const GlobalValue *GV = GA->getGlobal();
2132 DebugLoc dl = GA->getDebugLoc();
2134 SDValue Chain = DAG.getEntryNode();
2135 EVT PtrVT = getPointerTy();
2136 // Get the Thread Pointer
2137 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2139 if (model == TLSModel::InitialExec) {
2140 MachineFunction &MF = DAG.getMachineFunction();
2141 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2142 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2143 // Initial exec model.
2144 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2145 ARMConstantPoolValue *CPV =
2146 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2147 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2149 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2150 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2151 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2152 MachinePointerInfo::getConstantPool(),
2153 false, false, false, 0);
2154 Chain = Offset.getValue(1);
2156 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2157 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2159 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2160 MachinePointerInfo::getConstantPool(),
2161 false, false, false, 0);
2164 assert(model == TLSModel::LocalExec);
2165 ARMConstantPoolValue *CPV =
2166 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2167 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2168 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2169 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2170 MachinePointerInfo::getConstantPool(),
2171 false, false, false, 0);
2174 // The address of the thread local variable is the add of the thread
2175 // pointer with the offset of the variable.
2176 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2180 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2181 // TODO: implement the "local dynamic" model
2182 assert(Subtarget->isTargetELF() &&
2183 "TLS not implemented for non-ELF targets");
2184 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2186 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2189 case TLSModel::GeneralDynamic:
2190 case TLSModel::LocalDynamic:
2191 return LowerToTLSGeneralDynamicModel(GA, DAG);
2192 case TLSModel::InitialExec:
2193 case TLSModel::LocalExec:
2194 return LowerToTLSExecModels(GA, DAG, model);
2196 llvm_unreachable("bogus TLS model");
2199 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2200 SelectionDAG &DAG) const {
2201 EVT PtrVT = getPointerTy();
2202 DebugLoc dl = Op.getDebugLoc();
2203 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2204 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2205 if (RelocM == Reloc::PIC_) {
2206 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2207 ARMConstantPoolValue *CPV =
2208 ARMConstantPoolConstant::Create(GV,
2209 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2210 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2211 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2212 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2214 MachinePointerInfo::getConstantPool(),
2215 false, false, false, 0);
2216 SDValue Chain = Result.getValue(1);
2217 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2218 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2220 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2221 MachinePointerInfo::getGOT(),
2222 false, false, false, 0);
2226 // If we have T2 ops, we can materialize the address directly via movt/movw
2227 // pair. This is always cheaper.
2228 if (Subtarget->useMovt()) {
2230 // FIXME: Once remat is capable of dealing with instructions with register
2231 // operands, expand this into two nodes.
2232 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2233 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2235 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2236 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2237 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2238 MachinePointerInfo::getConstantPool(),
2239 false, false, false, 0);
2243 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2244 SelectionDAG &DAG) const {
2245 EVT PtrVT = getPointerTy();
2246 DebugLoc dl = Op.getDebugLoc();
2247 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2248 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2249 MachineFunction &MF = DAG.getMachineFunction();
2250 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2252 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2253 // update ARMFastISel::ARMMaterializeGV.
2254 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2256 // FIXME: Once remat is capable of dealing with instructions with register
2257 // operands, expand this into two nodes.
2258 if (RelocM == Reloc::Static)
2259 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2260 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2262 unsigned Wrapper = (RelocM == Reloc::PIC_)
2263 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2264 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2265 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2266 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2267 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2268 MachinePointerInfo::getGOT(),
2269 false, false, false, 0);
2273 unsigned ARMPCLabelIndex = 0;
2275 if (RelocM == Reloc::Static) {
2276 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2278 ARMPCLabelIndex = AFI->createPICLabelUId();
2279 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2280 ARMConstantPoolValue *CPV =
2281 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2283 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2285 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2287 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2288 MachinePointerInfo::getConstantPool(),
2289 false, false, false, 0);
2290 SDValue Chain = Result.getValue(1);
2292 if (RelocM == Reloc::PIC_) {
2293 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2294 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2297 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2298 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2299 false, false, false, 0);
2304 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2305 SelectionDAG &DAG) const {
2306 assert(Subtarget->isTargetELF() &&
2307 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2308 MachineFunction &MF = DAG.getMachineFunction();
2309 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2310 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2311 EVT PtrVT = getPointerTy();
2312 DebugLoc dl = Op.getDebugLoc();
2313 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2314 ARMConstantPoolValue *CPV =
2315 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2316 ARMPCLabelIndex, PCAdj);
2317 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2318 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2319 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2320 MachinePointerInfo::getConstantPool(),
2321 false, false, false, 0);
2322 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2323 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2327 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2328 DebugLoc dl = Op.getDebugLoc();
2329 SDValue Val = DAG.getConstant(0, MVT::i32);
2330 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2331 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2332 Op.getOperand(1), Val);
2336 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2337 DebugLoc dl = Op.getDebugLoc();
2338 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2339 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2343 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2344 const ARMSubtarget *Subtarget) const {
2345 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2346 DebugLoc dl = Op.getDebugLoc();
2348 default: return SDValue(); // Don't custom lower most intrinsics.
2349 case Intrinsic::arm_thread_pointer: {
2350 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2351 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2353 case Intrinsic::eh_sjlj_lsda: {
2354 MachineFunction &MF = DAG.getMachineFunction();
2355 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2356 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2357 EVT PtrVT = getPointerTy();
2358 DebugLoc dl = Op.getDebugLoc();
2359 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2361 unsigned PCAdj = (RelocM != Reloc::PIC_)
2362 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2363 ARMConstantPoolValue *CPV =
2364 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2365 ARMCP::CPLSDA, PCAdj);
2366 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2367 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2369 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2370 MachinePointerInfo::getConstantPool(),
2371 false, false, false, 0);
2373 if (RelocM == Reloc::PIC_) {
2374 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2375 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2379 case Intrinsic::arm_neon_vmulls:
2380 case Intrinsic::arm_neon_vmullu: {
2381 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2382 ? ARMISD::VMULLs : ARMISD::VMULLu;
2383 return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2384 Op.getOperand(1), Op.getOperand(2));
2389 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2390 const ARMSubtarget *Subtarget) {
2391 DebugLoc dl = Op.getDebugLoc();
2392 if (!Subtarget->hasDataBarrier()) {
2393 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2394 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2396 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2397 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2398 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2399 DAG.getConstant(0, MVT::i32));
2402 SDValue Op5 = Op.getOperand(5);
2403 bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2404 unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2405 unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2406 bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2408 ARM_MB::MemBOpt DMBOpt;
2409 if (isDeviceBarrier)
2410 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2412 DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2413 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2414 DAG.getConstant(DMBOpt, MVT::i32));
2418 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2419 const ARMSubtarget *Subtarget) {
2420 // FIXME: handle "fence singlethread" more efficiently.
2421 DebugLoc dl = Op.getDebugLoc();
2422 if (!Subtarget->hasDataBarrier()) {
2423 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2424 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2426 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2427 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2428 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2429 DAG.getConstant(0, MVT::i32));
2432 return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2433 DAG.getConstant(ARM_MB::ISH, MVT::i32));
2436 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2437 const ARMSubtarget *Subtarget) {
2438 // ARM pre v5TE and Thumb1 does not have preload instructions.
2439 if (!(Subtarget->isThumb2() ||
2440 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2441 // Just preserve the chain.
2442 return Op.getOperand(0);
2444 DebugLoc dl = Op.getDebugLoc();
2445 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2447 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2448 // ARMv7 with MP extension has PLDW.
2449 return Op.getOperand(0);
2451 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2452 if (Subtarget->isThumb()) {
2454 isRead = ~isRead & 1;
2455 isData = ~isData & 1;
2458 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2459 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2460 DAG.getConstant(isData, MVT::i32));
2463 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2464 MachineFunction &MF = DAG.getMachineFunction();
2465 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2467 // vastart just stores the address of the VarArgsFrameIndex slot into the
2468 // memory location argument.
2469 DebugLoc dl = Op.getDebugLoc();
2470 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2471 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2472 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2473 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2474 MachinePointerInfo(SV), false, false, 0);
2478 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2479 SDValue &Root, SelectionDAG &DAG,
2480 DebugLoc dl) const {
2481 MachineFunction &MF = DAG.getMachineFunction();
2482 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2484 const TargetRegisterClass *RC;
2485 if (AFI->isThumb1OnlyFunction())
2486 RC = &ARM::tGPRRegClass;
2488 RC = &ARM::GPRRegClass;
2490 // Transform the arguments stored in physical registers into virtual ones.
2491 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2492 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2495 if (NextVA.isMemLoc()) {
2496 MachineFrameInfo *MFI = MF.getFrameInfo();
2497 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2499 // Create load node to retrieve arguments from the stack.
2500 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2501 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2502 MachinePointerInfo::getFixedStack(FI),
2503 false, false, false, 0);
2505 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2506 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2509 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2513 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2514 unsigned &VARegSize, unsigned &VARegSaveSize)
2517 if (CCInfo.isFirstByValRegValid())
2518 NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2520 unsigned int firstUnalloced;
2521 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2522 sizeof(GPRArgRegs) /
2523 sizeof(GPRArgRegs[0]));
2524 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2527 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2528 VARegSize = NumGPRs * 4;
2529 VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2532 // The remaining GPRs hold either the beginning of variable-argument
2533 // data, or the beginning of an aggregate passed by value (usuall
2534 // byval). Either way, we allocate stack slots adjacent to the data
2535 // provided by our caller, and store the unallocated registers there.
2536 // If this is a variadic function, the va_list pointer will begin with
2537 // these values; otherwise, this reassembles a (byval) structure that
2538 // was split between registers and memory.
2540 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2541 DebugLoc dl, SDValue &Chain,
2542 unsigned ArgOffset) const {
2543 MachineFunction &MF = DAG.getMachineFunction();
2544 MachineFrameInfo *MFI = MF.getFrameInfo();
2545 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2546 unsigned firstRegToSaveIndex;
2547 if (CCInfo.isFirstByValRegValid())
2548 firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2550 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2551 (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2554 unsigned VARegSize, VARegSaveSize;
2555 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2556 if (VARegSaveSize) {
2557 // If this function is vararg, store any remaining integer argument regs
2558 // to their spots on the stack so that they may be loaded by deferencing
2559 // the result of va_next.
2560 AFI->setVarArgsRegSaveSize(VARegSaveSize);
2561 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2562 ArgOffset + VARegSaveSize
2565 SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2568 SmallVector<SDValue, 4> MemOps;
2569 for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2570 const TargetRegisterClass *RC;
2571 if (AFI->isThumb1OnlyFunction())
2572 RC = &ARM::tGPRRegClass;
2574 RC = &ARM::GPRRegClass;
2576 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2577 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2579 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2580 MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2582 MemOps.push_back(Store);
2583 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2584 DAG.getConstant(4, getPointerTy()));
2586 if (!MemOps.empty())
2587 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2588 &MemOps[0], MemOps.size());
2590 // This will point to the next argument passed via stack.
2591 AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2595 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2596 CallingConv::ID CallConv, bool isVarArg,
2597 const SmallVectorImpl<ISD::InputArg>
2599 DebugLoc dl, SelectionDAG &DAG,
2600 SmallVectorImpl<SDValue> &InVals)
2602 MachineFunction &MF = DAG.getMachineFunction();
2603 MachineFrameInfo *MFI = MF.getFrameInfo();
2605 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2607 // Assign locations to all of the incoming arguments.
2608 SmallVector<CCValAssign, 16> ArgLocs;
2609 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2610 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2611 CCInfo.AnalyzeFormalArguments(Ins,
2612 CCAssignFnForNode(CallConv, /* Return*/ false,
2615 SmallVector<SDValue, 16> ArgValues;
2616 int lastInsIndex = -1;
2619 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2620 CCValAssign &VA = ArgLocs[i];
2622 // Arguments stored in registers.
2623 if (VA.isRegLoc()) {
2624 EVT RegVT = VA.getLocVT();
2626 if (VA.needsCustom()) {
2627 // f64 and vector types are split up into multiple registers or
2628 // combinations of registers and stack slots.
2629 if (VA.getLocVT() == MVT::v2f64) {
2630 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2632 VA = ArgLocs[++i]; // skip ahead to next loc
2634 if (VA.isMemLoc()) {
2635 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2636 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2637 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2638 MachinePointerInfo::getFixedStack(FI),
2639 false, false, false, 0);
2641 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2644 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2645 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2646 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2647 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2648 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2650 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2653 const TargetRegisterClass *RC;
2655 if (RegVT == MVT::f32)
2656 RC = &ARM::SPRRegClass;
2657 else if (RegVT == MVT::f64)
2658 RC = &ARM::DPRRegClass;
2659 else if (RegVT == MVT::v2f64)
2660 RC = &ARM::QPRRegClass;
2661 else if (RegVT == MVT::i32)
2662 RC = AFI->isThumb1OnlyFunction() ?
2663 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2664 (const TargetRegisterClass*)&ARM::GPRRegClass;
2666 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2668 // Transform the arguments in physical registers into virtual ones.
2669 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2670 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2673 // If this is an 8 or 16-bit value, it is really passed promoted
2674 // to 32 bits. Insert an assert[sz]ext to capture this, then
2675 // truncate to the right size.
2676 switch (VA.getLocInfo()) {
2677 default: llvm_unreachable("Unknown loc info!");
2678 case CCValAssign::Full: break;
2679 case CCValAssign::BCvt:
2680 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2682 case CCValAssign::SExt:
2683 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2684 DAG.getValueType(VA.getValVT()));
2685 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2687 case CCValAssign::ZExt:
2688 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2689 DAG.getValueType(VA.getValVT()));
2690 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2694 InVals.push_back(ArgValue);
2696 } else { // VA.isRegLoc()
2699 assert(VA.isMemLoc());
2700 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2702 int index = ArgLocs[i].getValNo();
2704 // Some Ins[] entries become multiple ArgLoc[] entries.
2705 // Process them only once.
2706 if (index != lastInsIndex)
2708 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2709 // FIXME: For now, all byval parameter objects are marked mutable.
2710 // This can be changed with more analysis.
2711 // In case of tail call optimization mark all arguments mutable.
2712 // Since they could be overwritten by lowering of arguments in case of
2714 if (Flags.isByVal()) {
2715 unsigned VARegSize, VARegSaveSize;
2716 computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2717 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2718 unsigned Bytes = Flags.getByValSize() - VARegSize;
2719 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2720 int FI = MFI->CreateFixedObject(Bytes,
2721 VA.getLocMemOffset(), false);
2722 InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2724 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2725 VA.getLocMemOffset(), true);
2727 // Create load nodes to retrieve arguments from the stack.
2728 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2729 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2730 MachinePointerInfo::getFixedStack(FI),
2731 false, false, false, 0));
2733 lastInsIndex = index;
2740 VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2745 /// isFloatingPointZero - Return true if this is +0.0.
2746 static bool isFloatingPointZero(SDValue Op) {
2747 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2748 return CFP->getValueAPF().isPosZero();
2749 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2750 // Maybe this has already been legalized into the constant pool?
2751 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2752 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2753 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2754 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2755 return CFP->getValueAPF().isPosZero();
2761 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2762 /// the given operands.
2764 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2765 SDValue &ARMcc, SelectionDAG &DAG,
2766 DebugLoc dl) const {
2767 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2768 unsigned C = RHSC->getZExtValue();
2769 if (!isLegalICmpImmediate(C)) {
2770 // Constant does not fit, try adjusting it by one?
2775 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2776 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2777 RHS = DAG.getConstant(C-1, MVT::i32);
2782 if (C != 0 && isLegalICmpImmediate(C-1)) {
2783 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2784 RHS = DAG.getConstant(C-1, MVT::i32);
2789 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2790 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2791 RHS = DAG.getConstant(C+1, MVT::i32);
2796 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2797 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2798 RHS = DAG.getConstant(C+1, MVT::i32);
2805 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2806 ARMISD::NodeType CompareType;
2809 CompareType = ARMISD::CMP;
2814 CompareType = ARMISD::CMPZ;
2817 ARMcc = DAG.getConstant(CondCode, MVT::i32);
2818 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2821 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2823 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2824 DebugLoc dl) const {
2826 if (!isFloatingPointZero(RHS))
2827 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2829 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2830 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2833 /// duplicateCmp - Glue values can have only one use, so this function
2834 /// duplicates a comparison node.
2836 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2837 unsigned Opc = Cmp.getOpcode();
2838 DebugLoc DL = Cmp.getDebugLoc();
2839 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2840 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2842 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2843 Cmp = Cmp.getOperand(0);
2844 Opc = Cmp.getOpcode();
2845 if (Opc == ARMISD::CMPFP)
2846 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2848 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2849 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2851 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2854 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2855 SDValue Cond = Op.getOperand(0);
2856 SDValue SelectTrue = Op.getOperand(1);
2857 SDValue SelectFalse = Op.getOperand(2);
2858 DebugLoc dl = Op.getDebugLoc();
2862 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2863 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2865 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2866 const ConstantSDNode *CMOVTrue =
2867 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2868 const ConstantSDNode *CMOVFalse =
2869 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2871 if (CMOVTrue && CMOVFalse) {
2872 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2873 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2877 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2879 False = SelectFalse;
2880 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2885 if (True.getNode() && False.getNode()) {
2886 EVT VT = Op.getValueType();
2887 SDValue ARMcc = Cond.getOperand(2);
2888 SDValue CCR = Cond.getOperand(3);
2889 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2890 assert(True.getValueType() == VT);
2891 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2896 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2897 // undefined bits before doing a full-word comparison with zero.
2898 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2899 DAG.getConstant(1, Cond.getValueType()));
2901 return DAG.getSelectCC(dl, Cond,
2902 DAG.getConstant(0, Cond.getValueType()),
2903 SelectTrue, SelectFalse, ISD::SETNE);
2906 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2907 EVT VT = Op.getValueType();
2908 SDValue LHS = Op.getOperand(0);
2909 SDValue RHS = Op.getOperand(1);
2910 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2911 SDValue TrueVal = Op.getOperand(2);
2912 SDValue FalseVal = Op.getOperand(3);
2913 DebugLoc dl = Op.getDebugLoc();
2915 if (LHS.getValueType() == MVT::i32) {
2917 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2918 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2919 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2922 ARMCC::CondCodes CondCode, CondCode2;
2923 FPCCToARMCC(CC, CondCode, CondCode2);
2925 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2926 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2927 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2928 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2930 if (CondCode2 != ARMCC::AL) {
2931 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2932 // FIXME: Needs another CMP because flag can have but one use.
2933 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2934 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2935 Result, TrueVal, ARMcc2, CCR, Cmp2);
2940 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2941 /// to morph to an integer compare sequence.
2942 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2943 const ARMSubtarget *Subtarget) {
2944 SDNode *N = Op.getNode();
2945 if (!N->hasOneUse())
2946 // Otherwise it requires moving the value from fp to integer registers.
2948 if (!N->getNumValues())
2950 EVT VT = Op.getValueType();
2951 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2952 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2953 // vmrs are very slow, e.g. cortex-a8.
2956 if (isFloatingPointZero(Op)) {
2960 return ISD::isNormalLoad(N);
2963 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2964 if (isFloatingPointZero(Op))
2965 return DAG.getConstant(0, MVT::i32);
2967 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2968 return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2969 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2970 Ld->isVolatile(), Ld->isNonTemporal(),
2971 Ld->isInvariant(), Ld->getAlignment());
2973 llvm_unreachable("Unknown VFP cmp argument!");
2976 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2977 SDValue &RetVal1, SDValue &RetVal2) {
2978 if (isFloatingPointZero(Op)) {
2979 RetVal1 = DAG.getConstant(0, MVT::i32);
2980 RetVal2 = DAG.getConstant(0, MVT::i32);
2984 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2985 SDValue Ptr = Ld->getBasePtr();
2986 RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2987 Ld->getChain(), Ptr,
2988 Ld->getPointerInfo(),
2989 Ld->isVolatile(), Ld->isNonTemporal(),
2990 Ld->isInvariant(), Ld->getAlignment());
2992 EVT PtrType = Ptr.getValueType();
2993 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2994 SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2995 PtrType, Ptr, DAG.getConstant(4, PtrType));
2996 RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2997 Ld->getChain(), NewPtr,
2998 Ld->getPointerInfo().getWithOffset(4),
2999 Ld->isVolatile(), Ld->isNonTemporal(),
3000 Ld->isInvariant(), NewAlign);
3004 llvm_unreachable("Unknown VFP cmp argument!");
3007 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3008 /// f32 and even f64 comparisons to integer ones.
3010 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3011 SDValue Chain = Op.getOperand(0);
3012 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3013 SDValue LHS = Op.getOperand(2);
3014 SDValue RHS = Op.getOperand(3);
3015 SDValue Dest = Op.getOperand(4);
3016 DebugLoc dl = Op.getDebugLoc();
3018 bool LHSSeenZero = false;
3019 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3020 bool RHSSeenZero = false;
3021 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3022 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3023 // If unsafe fp math optimization is enabled and there are no other uses of
3024 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3025 // to an integer comparison.
3026 if (CC == ISD::SETOEQ)
3028 else if (CC == ISD::SETUNE)
3031 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3033 if (LHS.getValueType() == MVT::f32) {
3034 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3035 bitcastf32Toi32(LHS, DAG), Mask);
3036 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3037 bitcastf32Toi32(RHS, DAG), Mask);
3038 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3039 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3040 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3041 Chain, Dest, ARMcc, CCR, Cmp);
3046 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3047 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3048 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3049 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3050 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3051 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3052 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3053 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3054 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3060 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3061 SDValue Chain = Op.getOperand(0);
3062 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3063 SDValue LHS = Op.getOperand(2);
3064 SDValue RHS = Op.getOperand(3);
3065 SDValue Dest = Op.getOperand(4);
3066 DebugLoc dl = Op.getDebugLoc();
3068 if (LHS.getValueType() == MVT::i32) {
3070 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3071 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3072 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3073 Chain, Dest, ARMcc, CCR, Cmp);
3076 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3078 if (getTargetMachine().Options.UnsafeFPMath &&
3079 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3080 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3081 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3082 if (Result.getNode())
3086 ARMCC::CondCodes CondCode, CondCode2;
3087 FPCCToARMCC(CC, CondCode, CondCode2);
3089 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3090 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3091 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3092 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3093 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3094 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3095 if (CondCode2 != ARMCC::AL) {
3096 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3097 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3098 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3103 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3104 SDValue Chain = Op.getOperand(0);
3105 SDValue Table = Op.getOperand(1);
3106 SDValue Index = Op.getOperand(2);
3107 DebugLoc dl = Op.getDebugLoc();
3109 EVT PTy = getPointerTy();
3110 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3111 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3112 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3113 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3114 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3115 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3116 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3117 if (Subtarget->isThumb2()) {
3118 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3119 // which does another jump to the destination. This also makes it easier
3120 // to translate it to TBB / TBH later.
3121 // FIXME: This might not work if the function is extremely large.
3122 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3123 Addr, Op.getOperand(2), JTI, UId);
3125 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3126 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3127 MachinePointerInfo::getJumpTable(),
3128 false, false, false, 0);
3129 Chain = Addr.getValue(1);
3130 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3131 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3133 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3134 MachinePointerInfo::getJumpTable(),
3135 false, false, false, 0);
3136 Chain = Addr.getValue(1);
3137 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3141 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3142 EVT VT = Op.getValueType();
3143 DebugLoc dl = Op.getDebugLoc();
3145 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3146 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3148 return DAG.UnrollVectorOp(Op.getNode());
3151 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3152 "Invalid type for custom lowering!");
3153 if (VT != MVT::v4i16)
3154 return DAG.UnrollVectorOp(Op.getNode());
3156 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3157 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3160 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3161 EVT VT = Op.getValueType();
3163 return LowerVectorFP_TO_INT(Op, DAG);
3165 DebugLoc dl = Op.getDebugLoc();
3168 switch (Op.getOpcode()) {
3169 default: llvm_unreachable("Invalid opcode!");
3170 case ISD::FP_TO_SINT:
3171 Opc = ARMISD::FTOSI;
3173 case ISD::FP_TO_UINT:
3174 Opc = ARMISD::FTOUI;
3177 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3178 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3181 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3182 EVT VT = Op.getValueType();
3183 DebugLoc dl = Op.getDebugLoc();
3185 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3186 if (VT.getVectorElementType() == MVT::f32)
3188 return DAG.UnrollVectorOp(Op.getNode());
3191 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3192 "Invalid type for custom lowering!");
3193 if (VT != MVT::v4f32)
3194 return DAG.UnrollVectorOp(Op.getNode());
3198 switch (Op.getOpcode()) {
3199 default: llvm_unreachable("Invalid opcode!");
3200 case ISD::SINT_TO_FP:
3201 CastOpc = ISD::SIGN_EXTEND;
3202 Opc = ISD::SINT_TO_FP;
3204 case ISD::UINT_TO_FP:
3205 CastOpc = ISD::ZERO_EXTEND;
3206 Opc = ISD::UINT_TO_FP;
3210 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3211 return DAG.getNode(Opc, dl, VT, Op);
3214 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3215 EVT VT = Op.getValueType();
3217 return LowerVectorINT_TO_FP(Op, DAG);
3219 DebugLoc dl = Op.getDebugLoc();
3222 switch (Op.getOpcode()) {
3223 default: llvm_unreachable("Invalid opcode!");
3224 case ISD::SINT_TO_FP:
3225 Opc = ARMISD::SITOF;
3227 case ISD::UINT_TO_FP:
3228 Opc = ARMISD::UITOF;
3232 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3233 return DAG.getNode(Opc, dl, VT, Op);
3236 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3237 // Implement fcopysign with a fabs and a conditional fneg.
3238 SDValue Tmp0 = Op.getOperand(0);
3239 SDValue Tmp1 = Op.getOperand(1);
3240 DebugLoc dl = Op.getDebugLoc();
3241 EVT VT = Op.getValueType();
3242 EVT SrcVT = Tmp1.getValueType();
3243 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3244 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3245 bool UseNEON = !InGPR && Subtarget->hasNEON();
3248 // Use VBSL to copy the sign bit.
3249 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3250 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3251 DAG.getTargetConstant(EncodedVal, MVT::i32));
3252 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3254 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3255 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3256 DAG.getConstant(32, MVT::i32));
3257 else /*if (VT == MVT::f32)*/
3258 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3259 if (SrcVT == MVT::f32) {
3260 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3262 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3263 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3264 DAG.getConstant(32, MVT::i32));
3265 } else if (VT == MVT::f32)
3266 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3267 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3268 DAG.getConstant(32, MVT::i32));
3269 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3270 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3272 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3274 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3275 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3276 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3278 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3279 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3280 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3281 if (VT == MVT::f32) {
3282 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3283 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3284 DAG.getConstant(0, MVT::i32));
3286 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3292 // Bitcast operand 1 to i32.
3293 if (SrcVT == MVT::f64)
3294 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3295 &Tmp1, 1).getValue(1);
3296 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3298 // Or in the signbit with integer operations.
3299 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3300 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3301 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3302 if (VT == MVT::f32) {
3303 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3304 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3305 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3306 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3309 // f64: Or the high part with signbit and then combine two parts.
3310 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3312 SDValue Lo = Tmp0.getValue(0);
3313 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3314 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3315 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3318 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3319 MachineFunction &MF = DAG.getMachineFunction();
3320 MachineFrameInfo *MFI = MF.getFrameInfo();
3321 MFI->setReturnAddressIsTaken(true);
3323 EVT VT = Op.getValueType();
3324 DebugLoc dl = Op.getDebugLoc();
3325 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3327 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3328 SDValue Offset = DAG.getConstant(4, MVT::i32);
3329 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3330 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3331 MachinePointerInfo(), false, false, false, 0);
3334 // Return LR, which contains the return address. Mark it an implicit live-in.
3335 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3336 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3339 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3340 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3341 MFI->setFrameAddressIsTaken(true);
3343 EVT VT = Op.getValueType();
3344 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
3345 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3346 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3347 ? ARM::R7 : ARM::R11;
3348 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3350 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3351 MachinePointerInfo(),
3352 false, false, false, 0);
3356 /// ExpandBITCAST - If the target supports VFP, this function is called to
3357 /// expand a bit convert where either the source or destination type is i64 to
3358 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3359 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3360 /// vectors), since the legalizer won't know what to do with that.
3361 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3362 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3363 DebugLoc dl = N->getDebugLoc();
3364 SDValue Op = N->getOperand(0);
3366 // This function is only supposed to be called for i64 types, either as the
3367 // source or destination of the bit convert.
3368 EVT SrcVT = Op.getValueType();
3369 EVT DstVT = N->getValueType(0);
3370 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3371 "ExpandBITCAST called for non-i64 type");
3373 // Turn i64->f64 into VMOVDRR.
3374 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3375 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3376 DAG.getConstant(0, MVT::i32));
3377 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3378 DAG.getConstant(1, MVT::i32));
3379 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3380 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3383 // Turn f64->i64 into VMOVRRD.
3384 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3385 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3386 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3387 // Merge the pieces into a single i64 value.
3388 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3394 /// getZeroVector - Returns a vector of specified type with all zero elements.
3395 /// Zero vectors are used to represent vector negation and in those cases
3396 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3397 /// not support i64 elements, so sometimes the zero vectors will need to be
3398 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3400 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3401 assert(VT.isVector() && "Expected a vector type");
3402 // The canonical modified immediate encoding of a zero vector is....0!
3403 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3404 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3405 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3406 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3409 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3410 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3411 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3412 SelectionDAG &DAG) const {
3413 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3414 EVT VT = Op.getValueType();
3415 unsigned VTBits = VT.getSizeInBits();
3416 DebugLoc dl = Op.getDebugLoc();
3417 SDValue ShOpLo = Op.getOperand(0);
3418 SDValue ShOpHi = Op.getOperand(1);
3419 SDValue ShAmt = Op.getOperand(2);
3421 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3423 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3425 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3426 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3427 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3428 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3429 DAG.getConstant(VTBits, MVT::i32));
3430 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3431 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3432 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3434 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3435 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3437 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3438 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3441 SDValue Ops[2] = { Lo, Hi };
3442 return DAG.getMergeValues(Ops, 2, dl);
3445 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3446 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3447 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3448 SelectionDAG &DAG) const {
3449 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3450 EVT VT = Op.getValueType();
3451 unsigned VTBits = VT.getSizeInBits();
3452 DebugLoc dl = Op.getDebugLoc();
3453 SDValue ShOpLo = Op.getOperand(0);
3454 SDValue ShOpHi = Op.getOperand(1);
3455 SDValue ShAmt = Op.getOperand(2);
3458 assert(Op.getOpcode() == ISD::SHL_PARTS);
3459 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3460 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3461 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3462 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3463 DAG.getConstant(VTBits, MVT::i32));
3464 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3465 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3467 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3468 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3469 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3471 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3472 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3475 SDValue Ops[2] = { Lo, Hi };
3476 return DAG.getMergeValues(Ops, 2, dl);
3479 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3480 SelectionDAG &DAG) const {
3481 // The rounding mode is in bits 23:22 of the FPSCR.
3482 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3483 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3484 // so that the shift + and get folded into a bitfield extract.
3485 DebugLoc dl = Op.getDebugLoc();
3486 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3487 DAG.getConstant(Intrinsic::arm_get_fpscr,
3489 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3490 DAG.getConstant(1U << 22, MVT::i32));
3491 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3492 DAG.getConstant(22, MVT::i32));
3493 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3494 DAG.getConstant(3, MVT::i32));
3497 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3498 const ARMSubtarget *ST) {
3499 EVT VT = N->getValueType(0);
3500 DebugLoc dl = N->getDebugLoc();
3502 if (!ST->hasV6T2Ops())
3505 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3506 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3509 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3510 const ARMSubtarget *ST) {
3511 EVT VT = N->getValueType(0);
3512 DebugLoc dl = N->getDebugLoc();
3517 // Lower vector shifts on NEON to use VSHL.
3518 assert(ST->hasNEON() && "unexpected vector shift");
3520 // Left shifts translate directly to the vshiftu intrinsic.
3521 if (N->getOpcode() == ISD::SHL)
3522 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3523 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3524 N->getOperand(0), N->getOperand(1));
3526 assert((N->getOpcode() == ISD::SRA ||
3527 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3529 // NEON uses the same intrinsics for both left and right shifts. For
3530 // right shifts, the shift amounts are negative, so negate the vector of
3532 EVT ShiftVT = N->getOperand(1).getValueType();
3533 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3534 getZeroVector(ShiftVT, DAG, dl),
3536 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3537 Intrinsic::arm_neon_vshifts :
3538 Intrinsic::arm_neon_vshiftu);
3539 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3540 DAG.getConstant(vshiftInt, MVT::i32),
3541 N->getOperand(0), NegatedCount);
3544 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3545 const ARMSubtarget *ST) {
3546 EVT VT = N->getValueType(0);
3547 DebugLoc dl = N->getDebugLoc();
3549 // We can get here for a node like i32 = ISD::SHL i32, i64
3553 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3554 "Unknown shift to lower!");
3556 // We only lower SRA, SRL of 1 here, all others use generic lowering.
3557 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3558 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3561 // If we are in thumb mode, we don't have RRX.
3562 if (ST->isThumb1Only()) return SDValue();
3564 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
3565 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3566 DAG.getConstant(0, MVT::i32));
3567 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3568 DAG.getConstant(1, MVT::i32));
3570 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3571 // captures the result into a carry flag.
3572 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3573 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3575 // The low part is an ARMISD::RRX operand, which shifts the carry in.
3576 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3578 // Merge the pieces into a single i64 value.
3579 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3582 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3583 SDValue TmpOp0, TmpOp1;
3584 bool Invert = false;
3588 SDValue Op0 = Op.getOperand(0);
3589 SDValue Op1 = Op.getOperand(1);
3590 SDValue CC = Op.getOperand(2);
3591 EVT VT = Op.getValueType();
3592 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3593 DebugLoc dl = Op.getDebugLoc();
3595 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3596 switch (SetCCOpcode) {
3597 default: llvm_unreachable("Illegal FP comparison");
3599 case ISD::SETNE: Invert = true; // Fallthrough
3601 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3603 case ISD::SETLT: Swap = true; // Fallthrough
3605 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3607 case ISD::SETLE: Swap = true; // Fallthrough
3609 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3610 case ISD::SETUGE: Swap = true; // Fallthrough
3611 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3612 case ISD::SETUGT: Swap = true; // Fallthrough
3613 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3614 case ISD::SETUEQ: Invert = true; // Fallthrough
3616 // Expand this to (OLT | OGT).
3620 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3621 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3623 case ISD::SETUO: Invert = true; // Fallthrough
3625 // Expand this to (OLT | OGE).
3629 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3630 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3634 // Integer comparisons.
3635 switch (SetCCOpcode) {
3636 default: llvm_unreachable("Illegal integer comparison");
3637 case ISD::SETNE: Invert = true;
3638 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
3639 case ISD::SETLT: Swap = true;
3640 case ISD::SETGT: Opc = ARMISD::VCGT; break;
3641 case ISD::SETLE: Swap = true;
3642 case ISD::SETGE: Opc = ARMISD::VCGE; break;
3643 case ISD::SETULT: Swap = true;
3644 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3645 case ISD::SETULE: Swap = true;
3646 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3649 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3650 if (Opc == ARMISD::VCEQ) {
3653 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3655 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3658 // Ignore bitconvert.
3659 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3660 AndOp = AndOp.getOperand(0);
3662 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3664 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3665 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3672 std::swap(Op0, Op1);
3674 // If one of the operands is a constant vector zero, attempt to fold the
3675 // comparison to a specialized compare-against-zero form.
3677 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3679 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3680 if (Opc == ARMISD::VCGE)
3681 Opc = ARMISD::VCLEZ;
3682 else if (Opc == ARMISD::VCGT)
3683 Opc = ARMISD::VCLTZ;
3688 if (SingleOp.getNode()) {
3691 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3693 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3695 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3697 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3699 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3701 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3704 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3708 Result = DAG.getNOT(dl, Result, VT);
3713 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3714 /// valid vector constant for a NEON instruction with a "modified immediate"
3715 /// operand (e.g., VMOV). If so, return the encoded value.
3716 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3717 unsigned SplatBitSize, SelectionDAG &DAG,
3718 EVT &VT, bool is128Bits, NEONModImmType type) {
3719 unsigned OpCmode, Imm;
3721 // SplatBitSize is set to the smallest size that splats the vector, so a
3722 // zero vector will always have SplatBitSize == 8. However, NEON modified
3723 // immediate instructions others than VMOV do not support the 8-bit encoding
3724 // of a zero vector, and the default encoding of zero is supposed to be the
3729 switch (SplatBitSize) {
3731 if (type != VMOVModImm)
3733 // Any 1-byte value is OK. Op=0, Cmode=1110.
3734 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3737 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3741 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3742 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3743 if ((SplatBits & ~0xff) == 0) {
3744 // Value = 0x00nn: Op=x, Cmode=100x.
3749 if ((SplatBits & ~0xff00) == 0) {
3750 // Value = 0xnn00: Op=x, Cmode=101x.
3752 Imm = SplatBits >> 8;
3758 // NEON's 32-bit VMOV supports splat values where:
3759 // * only one byte is nonzero, or
3760 // * the least significant byte is 0xff and the second byte is nonzero, or
3761 // * the least significant 2 bytes are 0xff and the third is nonzero.
3762 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3763 if ((SplatBits & ~0xff) == 0) {
3764 // Value = 0x000000nn: Op=x, Cmode=000x.
3769 if ((SplatBits & ~0xff00) == 0) {
3770 // Value = 0x0000nn00: Op=x, Cmode=001x.
3772 Imm = SplatBits >> 8;
3775 if ((SplatBits & ~0xff0000) == 0) {
3776 // Value = 0x00nn0000: Op=x, Cmode=010x.
3778 Imm = SplatBits >> 16;
3781 if ((SplatBits & ~0xff000000) == 0) {
3782 // Value = 0xnn000000: Op=x, Cmode=011x.
3784 Imm = SplatBits >> 24;
3788 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3789 if (type == OtherModImm) return SDValue();
3791 if ((SplatBits & ~0xffff) == 0 &&
3792 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3793 // Value = 0x0000nnff: Op=x, Cmode=1100.
3795 Imm = SplatBits >> 8;
3800 if ((SplatBits & ~0xffffff) == 0 &&
3801 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3802 // Value = 0x00nnffff: Op=x, Cmode=1101.
3804 Imm = SplatBits >> 16;
3805 SplatBits |= 0xffff;
3809 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3810 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3811 // VMOV.I32. A (very) minor optimization would be to replicate the value
3812 // and fall through here to test for a valid 64-bit splat. But, then the
3813 // caller would also need to check and handle the change in size.
3817 if (type != VMOVModImm)
3819 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3820 uint64_t BitMask = 0xff;
3822 unsigned ImmMask = 1;
3824 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3825 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3828 } else if ((SplatBits & BitMask) != 0) {
3834 // Op=1, Cmode=1110.
3837 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3842 llvm_unreachable("unexpected size for isNEONModifiedImm");
3845 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3846 return DAG.getTargetConstant(EncodedVal, MVT::i32);
3849 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
3850 const ARMSubtarget *ST) const {
3851 if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
3854 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
3855 assert(Op.getValueType() == MVT::f32 &&
3856 "ConstantFP custom lowering should only occur for f32.");
3858 // Try splatting with a VMOV.f32...
3859 APFloat FPVal = CFP->getValueAPF();
3860 int ImmVal = ARM_AM::getFP32Imm(FPVal);
3862 DebugLoc DL = Op.getDebugLoc();
3863 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
3864 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
3866 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
3867 DAG.getConstant(0, MVT::i32));
3870 // If that fails, try a VMOV.i32
3872 unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
3873 SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
3875 if (NewVal != SDValue()) {
3876 DebugLoc DL = Op.getDebugLoc();
3877 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
3879 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3881 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3882 DAG.getConstant(0, MVT::i32));
3885 // Finally, try a VMVN.i32
3886 NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
3888 if (NewVal != SDValue()) {
3889 DebugLoc DL = Op.getDebugLoc();
3890 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
3891 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
3893 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
3894 DAG.getConstant(0, MVT::i32));
3901 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3902 bool &ReverseVEXT, unsigned &Imm) {
3903 unsigned NumElts = VT.getVectorNumElements();
3904 ReverseVEXT = false;
3906 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3912 // If this is a VEXT shuffle, the immediate value is the index of the first
3913 // element. The other shuffle indices must be the successive elements after
3915 unsigned ExpectedElt = Imm;
3916 for (unsigned i = 1; i < NumElts; ++i) {
3917 // Increment the expected index. If it wraps around, it may still be
3918 // a VEXT but the source vectors must be swapped.
3920 if (ExpectedElt == NumElts * 2) {
3925 if (M[i] < 0) continue; // ignore UNDEF indices
3926 if (ExpectedElt != static_cast<unsigned>(M[i]))
3930 // Adjust the index value if the source operands will be swapped.
3937 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3938 /// instruction with the specified blocksize. (The order of the elements
3939 /// within each block of the vector is reversed.)
3940 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3941 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3942 "Only possible block sizes for VREV are: 16, 32, 64");
3944 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3948 unsigned NumElts = VT.getVectorNumElements();
3949 unsigned BlockElts = M[0] + 1;
3950 // If the first shuffle index is UNDEF, be optimistic.
3952 BlockElts = BlockSize / EltSz;
3954 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3957 for (unsigned i = 0; i < NumElts; ++i) {
3958 if (M[i] < 0) continue; // ignore UNDEF indices
3959 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3966 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3967 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3968 // range, then 0 is placed into the resulting vector. So pretty much any mask
3969 // of 8 elements can work here.
3970 return VT == MVT::v8i8 && M.size() == 8;
3973 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3974 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3978 unsigned NumElts = VT.getVectorNumElements();
3979 WhichResult = (M[0] == 0 ? 0 : 1);
3980 for (unsigned i = 0; i < NumElts; i += 2) {
3981 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3982 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3988 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3989 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3990 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3991 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3992 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3996 unsigned NumElts = VT.getVectorNumElements();
3997 WhichResult = (M[0] == 0 ? 0 : 1);
3998 for (unsigned i = 0; i < NumElts; i += 2) {
3999 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4000 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4006 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4007 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4011 unsigned NumElts = VT.getVectorNumElements();
4012 WhichResult = (M[0] == 0 ? 0 : 1);
4013 for (unsigned i = 0; i != NumElts; ++i) {
4014 if (M[i] < 0) continue; // ignore UNDEF indices
4015 if ((unsigned) M[i] != 2 * i + WhichResult)
4019 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4020 if (VT.is64BitVector() && EltSz == 32)
4026 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4027 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4028 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4029 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4030 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4034 unsigned Half = VT.getVectorNumElements() / 2;
4035 WhichResult = (M[0] == 0 ? 0 : 1);
4036 for (unsigned j = 0; j != 2; ++j) {
4037 unsigned Idx = WhichResult;
4038 for (unsigned i = 0; i != Half; ++i) {
4039 int MIdx = M[i + j * Half];
4040 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4046 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4047 if (VT.is64BitVector() && EltSz == 32)
4053 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4054 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4058 unsigned NumElts = VT.getVectorNumElements();
4059 WhichResult = (M[0] == 0 ? 0 : 1);
4060 unsigned Idx = WhichResult * NumElts / 2;
4061 for (unsigned i = 0; i != NumElts; i += 2) {
4062 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4063 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4068 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4069 if (VT.is64BitVector() && EltSz == 32)
4075 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4076 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4077 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4078 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4079 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4083 unsigned NumElts = VT.getVectorNumElements();
4084 WhichResult = (M[0] == 0 ? 0 : 1);
4085 unsigned Idx = WhichResult * NumElts / 2;
4086 for (unsigned i = 0; i != NumElts; i += 2) {
4087 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4088 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4093 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4094 if (VT.is64BitVector() && EltSz == 32)
4100 // If N is an integer constant that can be moved into a register in one
4101 // instruction, return an SDValue of such a constant (will become a MOV
4102 // instruction). Otherwise return null.
4103 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4104 const ARMSubtarget *ST, DebugLoc dl) {
4106 if (!isa<ConstantSDNode>(N))
4108 Val = cast<ConstantSDNode>(N)->getZExtValue();
4110 if (ST->isThumb1Only()) {
4111 if (Val <= 255 || ~Val <= 255)
4112 return DAG.getConstant(Val, MVT::i32);
4114 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4115 return DAG.getConstant(Val, MVT::i32);
4120 // If this is a case we can't handle, return null and let the default
4121 // expansion code take care of it.
4122 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4123 const ARMSubtarget *ST) const {
4124 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4125 DebugLoc dl = Op.getDebugLoc();
4126 EVT VT = Op.getValueType();
4128 APInt SplatBits, SplatUndef;
4129 unsigned SplatBitSize;
4131 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4132 if (SplatBitSize <= 64) {
4133 // Check if an immediate VMOV works.
4135 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4136 SplatUndef.getZExtValue(), SplatBitSize,
4137 DAG, VmovVT, VT.is128BitVector(),
4139 if (Val.getNode()) {
4140 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4141 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4144 // Try an immediate VMVN.
4145 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4146 Val = isNEONModifiedImm(NegatedImm,
4147 SplatUndef.getZExtValue(), SplatBitSize,
4148 DAG, VmovVT, VT.is128BitVector(),
4150 if (Val.getNode()) {
4151 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4152 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4155 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4156 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4157 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4159 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4160 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4166 // Scan through the operands to see if only one value is used.
4167 unsigned NumElts = VT.getVectorNumElements();
4168 bool isOnlyLowElement = true;
4169 bool usesOnlyOneValue = true;
4170 bool isConstant = true;
4172 for (unsigned i = 0; i < NumElts; ++i) {
4173 SDValue V = Op.getOperand(i);
4174 if (V.getOpcode() == ISD::UNDEF)
4177 isOnlyLowElement = false;
4178 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4181 if (!Value.getNode())
4183 else if (V != Value)
4184 usesOnlyOneValue = false;
4187 if (!Value.getNode())
4188 return DAG.getUNDEF(VT);
4190 if (isOnlyLowElement)
4191 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4193 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4195 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4196 // i32 and try again.
4197 if (usesOnlyOneValue && EltSize <= 32) {
4199 return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4200 if (VT.getVectorElementType().isFloatingPoint()) {
4201 SmallVector<SDValue, 8> Ops;
4202 for (unsigned i = 0; i < NumElts; ++i)
4203 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4205 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4206 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4207 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4209 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4211 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4213 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4216 // If all elements are constants and the case above didn't get hit, fall back
4217 // to the default expansion, which will generate a load from the constant
4222 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4224 SDValue shuffle = ReconstructShuffle(Op, DAG);
4225 if (shuffle != SDValue())
4229 // Vectors with 32- or 64-bit elements can be built by directly assigning
4230 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4231 // will be legalized.
4232 if (EltSize >= 32) {
4233 // Do the expansion with floating-point types, since that is what the VFP
4234 // registers are defined to use, and since i64 is not legal.
4235 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4236 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4237 SmallVector<SDValue, 8> Ops;
4238 for (unsigned i = 0; i < NumElts; ++i)
4239 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4240 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4241 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4247 // Gather data to see if the operation can be modelled as a
4248 // shuffle in combination with VEXTs.
4249 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4250 SelectionDAG &DAG) const {
4251 DebugLoc dl = Op.getDebugLoc();
4252 EVT VT = Op.getValueType();
4253 unsigned NumElts = VT.getVectorNumElements();
4255 SmallVector<SDValue, 2> SourceVecs;
4256 SmallVector<unsigned, 2> MinElts;
4257 SmallVector<unsigned, 2> MaxElts;
4259 for (unsigned i = 0; i < NumElts; ++i) {
4260 SDValue V = Op.getOperand(i);
4261 if (V.getOpcode() == ISD::UNDEF)
4263 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4264 // A shuffle can only come from building a vector from various
4265 // elements of other vectors.
4267 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4268 VT.getVectorElementType()) {
4269 // This code doesn't know how to handle shuffles where the vector
4270 // element types do not match (this happens because type legalization
4271 // promotes the return type of EXTRACT_VECTOR_ELT).
4272 // FIXME: It might be appropriate to extend this code to handle
4273 // mismatched types.
4277 // Record this extraction against the appropriate vector if possible...
4278 SDValue SourceVec = V.getOperand(0);
4279 // If the element number isn't a constant, we can't effectively
4280 // analyze what's going on.
4281 if (!isa<ConstantSDNode>(V.getOperand(1)))
4283 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4284 bool FoundSource = false;
4285 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4286 if (SourceVecs[j] == SourceVec) {
4287 if (MinElts[j] > EltNo)
4289 if (MaxElts[j] < EltNo)
4296 // Or record a new source if not...
4298 SourceVecs.push_back(SourceVec);
4299 MinElts.push_back(EltNo);
4300 MaxElts.push_back(EltNo);
4304 // Currently only do something sane when at most two source vectors
4306 if (SourceVecs.size() > 2)
4309 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4310 int VEXTOffsets[2] = {0, 0};
4312 // This loop extracts the usage patterns of the source vectors
4313 // and prepares appropriate SDValues for a shuffle if possible.
4314 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4315 if (SourceVecs[i].getValueType() == VT) {
4316 // No VEXT necessary
4317 ShuffleSrcs[i] = SourceVecs[i];
4320 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4321 // It probably isn't worth padding out a smaller vector just to
4322 // break it down again in a shuffle.
4326 // Since only 64-bit and 128-bit vectors are legal on ARM and
4327 // we've eliminated the other cases...
4328 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4329 "unexpected vector sizes in ReconstructShuffle");
4331 if (MaxElts[i] - MinElts[i] >= NumElts) {
4332 // Span too large for a VEXT to cope
4336 if (MinElts[i] >= NumElts) {
4337 // The extraction can just take the second half
4338 VEXTOffsets[i] = NumElts;
4339 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4341 DAG.getIntPtrConstant(NumElts));
4342 } else if (MaxElts[i] < NumElts) {
4343 // The extraction can just take the first half
4345 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4347 DAG.getIntPtrConstant(0));
4349 // An actual VEXT is needed
4350 VEXTOffsets[i] = MinElts[i];
4351 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4353 DAG.getIntPtrConstant(0));
4354 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4356 DAG.getIntPtrConstant(NumElts));
4357 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4358 DAG.getConstant(VEXTOffsets[i], MVT::i32));
4362 SmallVector<int, 8> Mask;
4364 for (unsigned i = 0; i < NumElts; ++i) {
4365 SDValue Entry = Op.getOperand(i);
4366 if (Entry.getOpcode() == ISD::UNDEF) {
4371 SDValue ExtractVec = Entry.getOperand(0);
4372 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4373 .getOperand(1))->getSExtValue();
4374 if (ExtractVec == SourceVecs[0]) {
4375 Mask.push_back(ExtractElt - VEXTOffsets[0]);
4377 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4381 // Final check before we try to produce nonsense...
4382 if (isShuffleMaskLegal(Mask, VT))
4383 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4389 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4390 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4391 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4392 /// are assumed to be legal.
4394 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4396 if (VT.getVectorNumElements() == 4 &&
4397 (VT.is128BitVector() || VT.is64BitVector())) {
4398 unsigned PFIndexes[4];
4399 for (unsigned i = 0; i != 4; ++i) {
4403 PFIndexes[i] = M[i];
4406 // Compute the index in the perfect shuffle table.
4407 unsigned PFTableIndex =
4408 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4409 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4410 unsigned Cost = (PFEntry >> 30);
4417 unsigned Imm, WhichResult;
4419 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4420 return (EltSize >= 32 ||
4421 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4422 isVREVMask(M, VT, 64) ||
4423 isVREVMask(M, VT, 32) ||
4424 isVREVMask(M, VT, 16) ||
4425 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4426 isVTBLMask(M, VT) ||
4427 isVTRNMask(M, VT, WhichResult) ||
4428 isVUZPMask(M, VT, WhichResult) ||
4429 isVZIPMask(M, VT, WhichResult) ||
4430 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4431 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4432 isVZIP_v_undef_Mask(M, VT, WhichResult));
4435 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4436 /// the specified operations to build the shuffle.
4437 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4438 SDValue RHS, SelectionDAG &DAG,
4440 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4441 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4442 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4445 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4454 OP_VUZPL, // VUZP, left result
4455 OP_VUZPR, // VUZP, right result
4456 OP_VZIPL, // VZIP, left result
4457 OP_VZIPR, // VZIP, right result
4458 OP_VTRNL, // VTRN, left result
4459 OP_VTRNR // VTRN, right result
4462 if (OpNum == OP_COPY) {
4463 if (LHSID == (1*9+2)*9+3) return LHS;
4464 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4468 SDValue OpLHS, OpRHS;
4469 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4470 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4471 EVT VT = OpLHS.getValueType();
4474 default: llvm_unreachable("Unknown shuffle opcode!");
4476 // VREV divides the vector in half and swaps within the half.
4477 if (VT.getVectorElementType() == MVT::i32 ||
4478 VT.getVectorElementType() == MVT::f32)
4479 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4480 // vrev <4 x i16> -> VREV32
4481 if (VT.getVectorElementType() == MVT::i16)
4482 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4483 // vrev <4 x i8> -> VREV16
4484 assert(VT.getVectorElementType() == MVT::i8);
4485 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4490 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4491 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4495 return DAG.getNode(ARMISD::VEXT, dl, VT,
4497 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4500 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4501 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4504 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4505 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4508 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4509 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4513 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4514 ArrayRef<int> ShuffleMask,
4515 SelectionDAG &DAG) {
4516 // Check to see if we can use the VTBL instruction.
4517 SDValue V1 = Op.getOperand(0);
4518 SDValue V2 = Op.getOperand(1);
4519 DebugLoc DL = Op.getDebugLoc();
4521 SmallVector<SDValue, 8> VTBLMask;
4522 for (ArrayRef<int>::iterator
4523 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4524 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4526 if (V2.getNode()->getOpcode() == ISD::UNDEF)
4527 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4528 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4531 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4532 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4536 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4537 SDValue V1 = Op.getOperand(0);
4538 SDValue V2 = Op.getOperand(1);
4539 DebugLoc dl = Op.getDebugLoc();
4540 EVT VT = Op.getValueType();
4541 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4543 // Convert shuffles that are directly supported on NEON to target-specific
4544 // DAG nodes, instead of keeping them as shuffles and matching them again
4545 // during code selection. This is more efficient and avoids the possibility
4546 // of inconsistencies between legalization and selection.
4547 // FIXME: floating-point vectors should be canonicalized to integer vectors
4548 // of the same time so that they get CSEd properly.
4549 ArrayRef<int> ShuffleMask = SVN->getMask();
4551 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4552 if (EltSize <= 32) {
4553 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4554 int Lane = SVN->getSplatIndex();
4555 // If this is undef splat, generate it via "just" vdup, if possible.
4556 if (Lane == -1) Lane = 0;
4558 // Test if V1 is a SCALAR_TO_VECTOR.
4559 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4560 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4562 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4563 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4565 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4566 !isa<ConstantSDNode>(V1.getOperand(0))) {
4567 bool IsScalarToVector = true;
4568 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4569 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4570 IsScalarToVector = false;
4573 if (IsScalarToVector)
4574 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4576 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4577 DAG.getConstant(Lane, MVT::i32));
4582 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4585 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4586 DAG.getConstant(Imm, MVT::i32));
4589 if (isVREVMask(ShuffleMask, VT, 64))
4590 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4591 if (isVREVMask(ShuffleMask, VT, 32))
4592 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4593 if (isVREVMask(ShuffleMask, VT, 16))
4594 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4596 // Check for Neon shuffles that modify both input vectors in place.
4597 // If both results are used, i.e., if there are two shuffles with the same
4598 // source operands and with masks corresponding to both results of one of
4599 // these operations, DAG memoization will ensure that a single node is
4600 // used for both shuffles.
4601 unsigned WhichResult;
4602 if (isVTRNMask(ShuffleMask, VT, WhichResult))
4603 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4604 V1, V2).getValue(WhichResult);
4605 if (isVUZPMask(ShuffleMask, VT, WhichResult))
4606 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4607 V1, V2).getValue(WhichResult);
4608 if (isVZIPMask(ShuffleMask, VT, WhichResult))
4609 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4610 V1, V2).getValue(WhichResult);
4612 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4613 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4614 V1, V1).getValue(WhichResult);
4615 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4616 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4617 V1, V1).getValue(WhichResult);
4618 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4619 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4620 V1, V1).getValue(WhichResult);
4623 // If the shuffle is not directly supported and it has 4 elements, use
4624 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4625 unsigned NumElts = VT.getVectorNumElements();
4627 unsigned PFIndexes[4];
4628 for (unsigned i = 0; i != 4; ++i) {
4629 if (ShuffleMask[i] < 0)
4632 PFIndexes[i] = ShuffleMask[i];
4635 // Compute the index in the perfect shuffle table.
4636 unsigned PFTableIndex =
4637 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4638 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4639 unsigned Cost = (PFEntry >> 30);
4642 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4645 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4646 if (EltSize >= 32) {
4647 // Do the expansion with floating-point types, since that is what the VFP
4648 // registers are defined to use, and since i64 is not legal.
4649 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4650 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4651 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4652 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4653 SmallVector<SDValue, 8> Ops;
4654 for (unsigned i = 0; i < NumElts; ++i) {
4655 if (ShuffleMask[i] < 0)
4656 Ops.push_back(DAG.getUNDEF(EltVT));
4658 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4659 ShuffleMask[i] < (int)NumElts ? V1 : V2,
4660 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4663 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4664 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4667 if (VT == MVT::v8i8) {
4668 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4669 if (NewOp.getNode())
4676 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4677 // INSERT_VECTOR_ELT is legal only for immediate indexes.
4678 SDValue Lane = Op.getOperand(2);
4679 if (!isa<ConstantSDNode>(Lane))
4685 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4686 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4687 SDValue Lane = Op.getOperand(1);
4688 if (!isa<ConstantSDNode>(Lane))
4691 SDValue Vec = Op.getOperand(0);
4692 if (Op.getValueType() == MVT::i32 &&
4693 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4694 DebugLoc dl = Op.getDebugLoc();
4695 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4701 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4702 // The only time a CONCAT_VECTORS operation can have legal types is when
4703 // two 64-bit vectors are concatenated to a 128-bit vector.
4704 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4705 "unexpected CONCAT_VECTORS");
4706 DebugLoc dl = Op.getDebugLoc();
4707 SDValue Val = DAG.getUNDEF(MVT::v2f64);
4708 SDValue Op0 = Op.getOperand(0);
4709 SDValue Op1 = Op.getOperand(1);
4710 if (Op0.getOpcode() != ISD::UNDEF)
4711 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4712 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4713 DAG.getIntPtrConstant(0));
4714 if (Op1.getOpcode() != ISD::UNDEF)
4715 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4716 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4717 DAG.getIntPtrConstant(1));
4718 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4721 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4722 /// element has been zero/sign-extended, depending on the isSigned parameter,
4723 /// from an integer type half its size.
4724 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4726 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4727 EVT VT = N->getValueType(0);
4728 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4729 SDNode *BVN = N->getOperand(0).getNode();
4730 if (BVN->getValueType(0) != MVT::v4i32 ||
4731 BVN->getOpcode() != ISD::BUILD_VECTOR)
4733 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4734 unsigned HiElt = 1 - LoElt;
4735 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4736 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4737 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4738 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4739 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4742 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4743 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4746 if (Hi0->isNullValue() && Hi1->isNullValue())
4752 if (N->getOpcode() != ISD::BUILD_VECTOR)
4755 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4756 SDNode *Elt = N->getOperand(i).getNode();
4757 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4758 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4759 unsigned HalfSize = EltSize / 2;
4761 if (!isIntN(HalfSize, C->getSExtValue()))
4764 if (!isUIntN(HalfSize, C->getZExtValue()))
4775 /// isSignExtended - Check if a node is a vector value that is sign-extended
4776 /// or a constant BUILD_VECTOR with sign-extended elements.
4777 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4778 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4780 if (isExtendedBUILD_VECTOR(N, DAG, true))
4785 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4786 /// or a constant BUILD_VECTOR with zero-extended elements.
4787 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4788 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4790 if (isExtendedBUILD_VECTOR(N, DAG, false))
4795 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4796 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4797 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4798 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4799 return N->getOperand(0);
4800 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4801 return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4802 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4803 LD->isNonTemporal(), LD->isInvariant(),
4804 LD->getAlignment());
4805 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
4806 // have been legalized as a BITCAST from v4i32.
4807 if (N->getOpcode() == ISD::BITCAST) {
4808 SDNode *BVN = N->getOperand(0).getNode();
4809 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4810 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4811 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4812 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4813 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4815 // Construct a new BUILD_VECTOR with elements truncated to half the size.
4816 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4817 EVT VT = N->getValueType(0);
4818 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4819 unsigned NumElts = VT.getVectorNumElements();
4820 MVT TruncVT = MVT::getIntegerVT(EltSize);
4821 SmallVector<SDValue, 8> Ops;
4822 for (unsigned i = 0; i != NumElts; ++i) {
4823 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4824 const APInt &CInt = C->getAPIntValue();
4825 // Element types smaller than 32 bits are not legal, so use i32 elements.
4826 // The values are implicitly truncated so sext vs. zext doesn't matter.
4827 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
4829 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4830 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4833 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4834 unsigned Opcode = N->getOpcode();
4835 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4836 SDNode *N0 = N->getOperand(0).getNode();
4837 SDNode *N1 = N->getOperand(1).getNode();
4838 return N0->hasOneUse() && N1->hasOneUse() &&
4839 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4844 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4845 unsigned Opcode = N->getOpcode();
4846 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4847 SDNode *N0 = N->getOperand(0).getNode();
4848 SDNode *N1 = N->getOperand(1).getNode();
4849 return N0->hasOneUse() && N1->hasOneUse() &&
4850 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4855 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4856 // Multiplications are only custom-lowered for 128-bit vectors so that
4857 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
4858 EVT VT = Op.getValueType();
4859 assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4860 SDNode *N0 = Op.getOperand(0).getNode();
4861 SDNode *N1 = Op.getOperand(1).getNode();
4862 unsigned NewOpc = 0;
4864 bool isN0SExt = isSignExtended(N0, DAG);
4865 bool isN1SExt = isSignExtended(N1, DAG);
4866 if (isN0SExt && isN1SExt)
4867 NewOpc = ARMISD::VMULLs;
4869 bool isN0ZExt = isZeroExtended(N0, DAG);
4870 bool isN1ZExt = isZeroExtended(N1, DAG);
4871 if (isN0ZExt && isN1ZExt)
4872 NewOpc = ARMISD::VMULLu;
4873 else if (isN1SExt || isN1ZExt) {
4874 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4875 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4876 if (isN1SExt && isAddSubSExt(N0, DAG)) {
4877 NewOpc = ARMISD::VMULLs;
4879 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4880 NewOpc = ARMISD::VMULLu;
4882 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4884 NewOpc = ARMISD::VMULLu;
4890 if (VT == MVT::v2i64)
4891 // Fall through to expand this. It is not legal.
4894 // Other vector multiplications are legal.
4899 // Legalize to a VMULL instruction.
4900 DebugLoc DL = Op.getDebugLoc();
4902 SDValue Op1 = SkipExtension(N1, DAG);
4904 Op0 = SkipExtension(N0, DAG);
4905 assert(Op0.getValueType().is64BitVector() &&
4906 Op1.getValueType().is64BitVector() &&
4907 "unexpected types for extended operands to VMULL");
4908 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4911 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4912 // isel lowering to take advantage of no-stall back to back vmul + vmla.
4919 SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4920 SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4921 EVT Op1VT = Op1.getValueType();
4922 return DAG.getNode(N0->getOpcode(), DL, VT,
4923 DAG.getNode(NewOpc, DL, VT,
4924 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4925 DAG.getNode(NewOpc, DL, VT,
4926 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4930 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4932 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4933 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4934 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4935 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4936 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4937 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4938 // Get reciprocal estimate.
4939 // float4 recip = vrecpeq_f32(yf);
4940 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4941 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4942 // Because char has a smaller range than uchar, we can actually get away
4943 // without any newton steps. This requires that we use a weird bias
4944 // of 0xb000, however (again, this has been exhaustively tested).
4945 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4946 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4947 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4948 Y = DAG.getConstant(0xb000, MVT::i32);
4949 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4950 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4951 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4952 // Convert back to short.
4953 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4954 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4959 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4961 // Convert to float.
4962 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4963 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4964 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4965 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4966 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4967 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4969 // Use reciprocal estimate and one refinement step.
4970 // float4 recip = vrecpeq_f32(yf);
4971 // recip *= vrecpsq_f32(yf, recip);
4972 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4973 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4974 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4975 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4977 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4978 // Because short has a smaller range than ushort, we can actually get away
4979 // with only a single newton step. This requires that we use a weird bias
4980 // of 89, however (again, this has been exhaustively tested).
4981 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4982 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4983 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4984 N1 = DAG.getConstant(0x89, MVT::i32);
4985 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4986 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4987 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4988 // Convert back to integer and return.
4989 // return vmovn_s32(vcvt_s32_f32(result));
4990 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4991 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4995 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4996 EVT VT = Op.getValueType();
4997 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4998 "unexpected type for custom-lowering ISD::SDIV");
5000 DebugLoc dl = Op.getDebugLoc();
5001 SDValue N0 = Op.getOperand(0);
5002 SDValue N1 = Op.getOperand(1);
5005 if (VT == MVT::v8i8) {
5006 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5007 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5009 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5010 DAG.getIntPtrConstant(4));
5011 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5012 DAG.getIntPtrConstant(4));
5013 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5014 DAG.getIntPtrConstant(0));
5015 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5016 DAG.getIntPtrConstant(0));
5018 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5019 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5021 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5022 N0 = LowerCONCAT_VECTORS(N0, DAG);
5024 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5027 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5030 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5031 EVT VT = Op.getValueType();
5032 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5033 "unexpected type for custom-lowering ISD::UDIV");
5035 DebugLoc dl = Op.getDebugLoc();
5036 SDValue N0 = Op.getOperand(0);
5037 SDValue N1 = Op.getOperand(1);
5040 if (VT == MVT::v8i8) {
5041 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5042 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5044 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5045 DAG.getIntPtrConstant(4));
5046 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5047 DAG.getIntPtrConstant(4));
5048 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5049 DAG.getIntPtrConstant(0));
5050 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5051 DAG.getIntPtrConstant(0));
5053 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5054 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5056 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5057 N0 = LowerCONCAT_VECTORS(N0, DAG);
5059 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5060 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5065 // v4i16 sdiv ... Convert to float.
5066 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5067 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5068 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5069 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5070 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5071 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5073 // Use reciprocal estimate and two refinement steps.
5074 // float4 recip = vrecpeq_f32(yf);
5075 // recip *= vrecpsq_f32(yf, recip);
5076 // recip *= vrecpsq_f32(yf, recip);
5077 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5078 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5079 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5080 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5082 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5083 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5084 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5086 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5087 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5088 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5089 // and that it will never cause us to return an answer too large).
5090 // float4 result = as_float4(as_int4(xf*recip) + 2);
5091 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5092 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5093 N1 = DAG.getConstant(2, MVT::i32);
5094 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5095 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5096 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5097 // Convert back to integer and return.
5098 // return vmovn_u32(vcvt_s32_f32(result));
5099 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5100 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5104 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5105 EVT VT = Op.getNode()->getValueType(0);
5106 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5109 bool ExtraOp = false;
5110 switch (Op.getOpcode()) {
5111 default: llvm_unreachable("Invalid code");
5112 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5113 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5114 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5115 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5119 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5121 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5122 Op.getOperand(1), Op.getOperand(2));
5125 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5126 // Monotonic load/store is legal for all targets
5127 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5130 // Aquire/Release load/store is not legal for targets without a
5131 // dmb or equivalent available.
5137 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5138 SelectionDAG &DAG, unsigned NewOp) {
5139 DebugLoc dl = Node->getDebugLoc();
5140 assert (Node->getValueType(0) == MVT::i64 &&
5141 "Only know how to expand i64 atomics");
5143 SmallVector<SDValue, 6> Ops;
5144 Ops.push_back(Node->getOperand(0)); // Chain
5145 Ops.push_back(Node->getOperand(1)); // Ptr
5147 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5148 Node->getOperand(2), DAG.getIntPtrConstant(0)));
5149 // High part of Val1
5150 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5151 Node->getOperand(2), DAG.getIntPtrConstant(1)));
5152 if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5153 // High part of Val1
5154 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5155 Node->getOperand(3), DAG.getIntPtrConstant(0)));
5156 // High part of Val2
5157 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5158 Node->getOperand(3), DAG.getIntPtrConstant(1)));
5160 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5162 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5163 cast<MemSDNode>(Node)->getMemOperand());
5164 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5165 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5166 Results.push_back(Result.getValue(2));
5169 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5170 switch (Op.getOpcode()) {
5171 default: llvm_unreachable("Don't know how to custom lower this!");
5172 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5173 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5174 case ISD::GlobalAddress:
5175 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5176 LowerGlobalAddressELF(Op, DAG);
5177 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5178 case ISD::SELECT: return LowerSELECT(Op, DAG);
5179 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5180 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
5181 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
5182 case ISD::VASTART: return LowerVASTART(Op, DAG);
5183 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG, Subtarget);
5184 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5185 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
5186 case ISD::SINT_TO_FP:
5187 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5188 case ISD::FP_TO_SINT:
5189 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
5190 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5191 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5192 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5193 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5194 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5195 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5196 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5198 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
5201 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
5202 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
5203 case ISD::SRL_PARTS:
5204 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
5205 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5206 case ISD::SETCC: return LowerVSETCC(Op, DAG);
5207 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
5208 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5209 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5210 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5211 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5212 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5213 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5214 case ISD::MUL: return LowerMUL(Op, DAG);
5215 case ISD::SDIV: return LowerSDIV(Op, DAG);
5216 case ISD::UDIV: return LowerUDIV(Op, DAG);
5220 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5221 case ISD::ATOMIC_LOAD:
5222 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
5226 /// ReplaceNodeResults - Replace the results of node with an illegal result
5227 /// type with new values built out of custom code.
5228 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5229 SmallVectorImpl<SDValue>&Results,
5230 SelectionDAG &DAG) const {
5232 switch (N->getOpcode()) {
5234 llvm_unreachable("Don't know how to custom expand this!");
5236 Res = ExpandBITCAST(N, DAG);
5240 Res = Expand64BitShift(N, DAG, Subtarget);
5242 case ISD::ATOMIC_LOAD_ADD:
5243 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5245 case ISD::ATOMIC_LOAD_AND:
5246 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5248 case ISD::ATOMIC_LOAD_NAND:
5249 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5251 case ISD::ATOMIC_LOAD_OR:
5252 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5254 case ISD::ATOMIC_LOAD_SUB:
5255 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5257 case ISD::ATOMIC_LOAD_XOR:
5258 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5260 case ISD::ATOMIC_SWAP:
5261 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5263 case ISD::ATOMIC_CMP_SWAP:
5264 ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5268 Results.push_back(Res);
5271 //===----------------------------------------------------------------------===//
5272 // ARM Scheduler Hooks
5273 //===----------------------------------------------------------------------===//
5276 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5277 MachineBasicBlock *BB,
5278 unsigned Size) const {
5279 unsigned dest = MI->getOperand(0).getReg();
5280 unsigned ptr = MI->getOperand(1).getReg();
5281 unsigned oldval = MI->getOperand(2).getReg();
5282 unsigned newval = MI->getOperand(3).getReg();
5283 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5284 DebugLoc dl = MI->getDebugLoc();
5285 bool isThumb2 = Subtarget->isThumb2();
5287 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5288 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5289 (const TargetRegisterClass*)&ARM::rGPRRegClass :
5290 (const TargetRegisterClass*)&ARM::GPRRegClass);
5293 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5294 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5295 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5298 unsigned ldrOpc, strOpc;
5300 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5302 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5303 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5306 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5307 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5310 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5311 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5315 MachineFunction *MF = BB->getParent();
5316 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5317 MachineFunction::iterator It = BB;
5318 ++It; // insert the new blocks after the current block
5320 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5321 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5322 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5323 MF->insert(It, loop1MBB);
5324 MF->insert(It, loop2MBB);
5325 MF->insert(It, exitMBB);
5327 // Transfer the remainder of BB and its successor edges to exitMBB.
5328 exitMBB->splice(exitMBB->begin(), BB,
5329 llvm::next(MachineBasicBlock::iterator(MI)),
5331 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5335 // fallthrough --> loop1MBB
5336 BB->addSuccessor(loop1MBB);
5339 // ldrex dest, [ptr]
5343 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5344 if (ldrOpc == ARM::t2LDREX)
5346 AddDefaultPred(MIB);
5347 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5348 .addReg(dest).addReg(oldval));
5349 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5350 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5351 BB->addSuccessor(loop2MBB);
5352 BB->addSuccessor(exitMBB);
5355 // strex scratch, newval, [ptr]
5359 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5360 if (strOpc == ARM::t2STREX)
5362 AddDefaultPred(MIB);
5363 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5364 .addReg(scratch).addImm(0));
5365 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5366 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5367 BB->addSuccessor(loop1MBB);
5368 BB->addSuccessor(exitMBB);
5374 MI->eraseFromParent(); // The instruction is gone now.
5380 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5381 unsigned Size, unsigned BinOpcode) const {
5382 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5383 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5385 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5386 MachineFunction *MF = BB->getParent();
5387 MachineFunction::iterator It = BB;
5390 unsigned dest = MI->getOperand(0).getReg();
5391 unsigned ptr = MI->getOperand(1).getReg();
5392 unsigned incr = MI->getOperand(2).getReg();
5393 DebugLoc dl = MI->getDebugLoc();
5394 bool isThumb2 = Subtarget->isThumb2();
5396 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5398 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5399 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5402 unsigned ldrOpc, strOpc;
5404 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5406 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5407 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5410 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5411 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5414 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5415 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5419 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5420 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5421 MF->insert(It, loopMBB);
5422 MF->insert(It, exitMBB);
5424 // Transfer the remainder of BB and its successor edges to exitMBB.
5425 exitMBB->splice(exitMBB->begin(), BB,
5426 llvm::next(MachineBasicBlock::iterator(MI)),
5428 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5430 const TargetRegisterClass *TRC = isThumb2 ?
5431 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5432 (const TargetRegisterClass*)&ARM::GPRRegClass;
5433 unsigned scratch = MRI.createVirtualRegister(TRC);
5434 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5438 // fallthrough --> loopMBB
5439 BB->addSuccessor(loopMBB);
5443 // <binop> scratch2, dest, incr
5444 // strex scratch, scratch2, ptr
5447 // fallthrough --> exitMBB
5449 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5450 if (ldrOpc == ARM::t2LDREX)
5452 AddDefaultPred(MIB);
5454 // operand order needs to go the other way for NAND
5455 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5456 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5457 addReg(incr).addReg(dest)).addReg(0);
5459 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5460 addReg(dest).addReg(incr)).addReg(0);
5463 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5464 if (strOpc == ARM::t2STREX)
5466 AddDefaultPred(MIB);
5467 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5468 .addReg(scratch).addImm(0));
5469 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5470 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5472 BB->addSuccessor(loopMBB);
5473 BB->addSuccessor(exitMBB);
5479 MI->eraseFromParent(); // The instruction is gone now.
5485 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5486 MachineBasicBlock *BB,
5489 ARMCC::CondCodes Cond) const {
5490 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5492 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5493 MachineFunction *MF = BB->getParent();
5494 MachineFunction::iterator It = BB;
5497 unsigned dest = MI->getOperand(0).getReg();
5498 unsigned ptr = MI->getOperand(1).getReg();
5499 unsigned incr = MI->getOperand(2).getReg();
5500 unsigned oldval = dest;
5501 DebugLoc dl = MI->getDebugLoc();
5502 bool isThumb2 = Subtarget->isThumb2();
5504 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5506 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5507 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5510 unsigned ldrOpc, strOpc, extendOpc;
5512 default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5514 ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5515 strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5516 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5519 ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5520 strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5521 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5524 ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5525 strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5530 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5531 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5532 MF->insert(It, loopMBB);
5533 MF->insert(It, exitMBB);
5535 // Transfer the remainder of BB and its successor edges to exitMBB.
5536 exitMBB->splice(exitMBB->begin(), BB,
5537 llvm::next(MachineBasicBlock::iterator(MI)),
5539 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5541 const TargetRegisterClass *TRC = isThumb2 ?
5542 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5543 (const TargetRegisterClass*)&ARM::GPRRegClass;
5544 unsigned scratch = MRI.createVirtualRegister(TRC);
5545 unsigned scratch2 = MRI.createVirtualRegister(TRC);
5549 // fallthrough --> loopMBB
5550 BB->addSuccessor(loopMBB);
5554 // (sign extend dest, if required)
5556 // cmov.cond scratch2, dest, incr
5557 // strex scratch, scratch2, ptr
5560 // fallthrough --> exitMBB
5562 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5563 if (ldrOpc == ARM::t2LDREX)
5565 AddDefaultPred(MIB);
5567 // Sign extend the value, if necessary.
5568 if (signExtend && extendOpc) {
5569 oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5570 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5575 // Build compare and cmov instructions.
5576 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5577 .addReg(oldval).addReg(incr));
5578 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5579 .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5581 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5582 if (strOpc == ARM::t2STREX)
5584 AddDefaultPred(MIB);
5585 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5586 .addReg(scratch).addImm(0));
5587 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5588 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5590 BB->addSuccessor(loopMBB);
5591 BB->addSuccessor(exitMBB);
5597 MI->eraseFromParent(); // The instruction is gone now.
5603 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5604 unsigned Op1, unsigned Op2,
5605 bool NeedsCarry, bool IsCmpxchg) const {
5606 // This also handles ATOMIC_SWAP, indicated by Op1==0.
5607 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5609 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5610 MachineFunction *MF = BB->getParent();
5611 MachineFunction::iterator It = BB;
5614 unsigned destlo = MI->getOperand(0).getReg();
5615 unsigned desthi = MI->getOperand(1).getReg();
5616 unsigned ptr = MI->getOperand(2).getReg();
5617 unsigned vallo = MI->getOperand(3).getReg();
5618 unsigned valhi = MI->getOperand(4).getReg();
5619 DebugLoc dl = MI->getDebugLoc();
5620 bool isThumb2 = Subtarget->isThumb2();
5622 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5624 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5625 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5626 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5629 unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5630 unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5632 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5633 MachineBasicBlock *contBB = 0, *cont2BB = 0;
5635 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5636 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5638 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5639 MF->insert(It, loopMBB);
5641 MF->insert(It, contBB);
5642 MF->insert(It, cont2BB);
5644 MF->insert(It, exitMBB);
5646 // Transfer the remainder of BB and its successor edges to exitMBB.
5647 exitMBB->splice(exitMBB->begin(), BB,
5648 llvm::next(MachineBasicBlock::iterator(MI)),
5650 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5652 const TargetRegisterClass *TRC = isThumb2 ?
5653 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5654 (const TargetRegisterClass*)&ARM::GPRRegClass;
5655 unsigned storesuccess = MRI.createVirtualRegister(TRC);
5659 // fallthrough --> loopMBB
5660 BB->addSuccessor(loopMBB);
5663 // ldrexd r2, r3, ptr
5664 // <binopa> r0, r2, incr
5665 // <binopb> r1, r3, incr
5666 // strexd storesuccess, r0, r1, ptr
5667 // cmp storesuccess, #0
5669 // fallthrough --> exitMBB
5671 // Note that the registers are explicitly specified because there is not any
5672 // way to force the register allocator to allocate a register pair.
5674 // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5675 // need to properly enforce the restriction that the two output registers
5676 // for ldrexd must be different.
5679 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5680 .addReg(ARM::R2, RegState::Define)
5681 .addReg(ARM::R3, RegState::Define).addReg(ptr));
5682 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
5683 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5684 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5688 for (unsigned i = 0; i < 2; i++) {
5689 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5691 .addReg(i == 0 ? destlo : desthi)
5692 .addReg(i == 0 ? vallo : valhi));
5693 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5694 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5695 BB->addSuccessor(exitMBB);
5696 BB->addSuccessor(i == 0 ? contBB : cont2BB);
5697 BB = (i == 0 ? contBB : cont2BB);
5700 // Copy to physregs for strexd
5701 unsigned setlo = MI->getOperand(5).getReg();
5702 unsigned sethi = MI->getOperand(6).getReg();
5703 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5704 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5706 // Perform binary operation
5707 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5708 .addReg(destlo).addReg(vallo))
5709 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5710 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5711 .addReg(desthi).addReg(valhi)).addReg(0);
5713 // Copy to physregs for strexd
5714 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5715 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5719 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5720 .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5722 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5723 .addReg(storesuccess).addImm(0));
5724 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5725 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5727 BB->addSuccessor(loopMBB);
5728 BB->addSuccessor(exitMBB);
5734 MI->eraseFromParent(); // The instruction is gone now.
5739 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5740 /// registers the function context.
5741 void ARMTargetLowering::
5742 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5743 MachineBasicBlock *DispatchBB, int FI) const {
5744 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5745 DebugLoc dl = MI->getDebugLoc();
5746 MachineFunction *MF = MBB->getParent();
5747 MachineRegisterInfo *MRI = &MF->getRegInfo();
5748 MachineConstantPool *MCP = MF->getConstantPool();
5749 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5750 const Function *F = MF->getFunction();
5752 bool isThumb = Subtarget->isThumb();
5753 bool isThumb2 = Subtarget->isThumb2();
5755 unsigned PCLabelId = AFI->createPICLabelUId();
5756 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5757 ARMConstantPoolValue *CPV =
5758 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5759 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5761 const TargetRegisterClass *TRC = isThumb ?
5762 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5763 (const TargetRegisterClass*)&ARM::GPRRegClass;
5765 // Grab constant pool and fixed stack memory operands.
5766 MachineMemOperand *CPMMO =
5767 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5768 MachineMemOperand::MOLoad, 4, 4);
5770 MachineMemOperand *FIMMOSt =
5771 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5772 MachineMemOperand::MOStore, 4, 4);
5774 // Load the address of the dispatch MBB into the jump buffer.
5776 // Incoming value: jbuf
5777 // ldr.n r5, LCPI1_1
5780 // str r5, [$jbuf, #+4] ; &jbuf[1]
5781 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5782 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5783 .addConstantPoolIndex(CPI)
5784 .addMemOperand(CPMMO));
5785 // Set the low bit because of thumb mode.
5786 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5788 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5789 .addReg(NewVReg1, RegState::Kill)
5791 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5792 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5793 .addReg(NewVReg2, RegState::Kill)
5795 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5796 .addReg(NewVReg3, RegState::Kill)
5798 .addImm(36) // &jbuf[1] :: pc
5799 .addMemOperand(FIMMOSt));
5800 } else if (isThumb) {
5801 // Incoming value: jbuf
5802 // ldr.n r1, LCPI1_4
5806 // add r2, $jbuf, #+4 ; &jbuf[1]
5808 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5809 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5810 .addConstantPoolIndex(CPI)
5811 .addMemOperand(CPMMO));
5812 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5813 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5814 .addReg(NewVReg1, RegState::Kill)
5816 // Set the low bit because of thumb mode.
5817 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5818 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5819 .addReg(ARM::CPSR, RegState::Define)
5821 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5822 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5823 .addReg(ARM::CPSR, RegState::Define)
5824 .addReg(NewVReg2, RegState::Kill)
5825 .addReg(NewVReg3, RegState::Kill));
5826 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5827 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5829 .addImm(36)); // &jbuf[1] :: pc
5830 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5831 .addReg(NewVReg4, RegState::Kill)
5832 .addReg(NewVReg5, RegState::Kill)
5834 .addMemOperand(FIMMOSt));
5836 // Incoming value: jbuf
5839 // str r1, [$jbuf, #+4] ; &jbuf[1]
5840 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5841 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
5842 .addConstantPoolIndex(CPI)
5844 .addMemOperand(CPMMO));
5845 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5846 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5847 .addReg(NewVReg1, RegState::Kill)
5848 .addImm(PCLabelId));
5849 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5850 .addReg(NewVReg2, RegState::Kill)
5852 .addImm(36) // &jbuf[1] :: pc
5853 .addMemOperand(FIMMOSt));
5857 MachineBasicBlock *ARMTargetLowering::
5858 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5859 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5860 DebugLoc dl = MI->getDebugLoc();
5861 MachineFunction *MF = MBB->getParent();
5862 MachineRegisterInfo *MRI = &MF->getRegInfo();
5863 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5864 MachineFrameInfo *MFI = MF->getFrameInfo();
5865 int FI = MFI->getFunctionContextIndex();
5867 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
5868 (const TargetRegisterClass*)&ARM::tGPRRegClass :
5869 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
5871 // Get a mapping of the call site numbers to all of the landing pads they're
5873 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5874 unsigned MaxCSNum = 0;
5875 MachineModuleInfo &MMI = MF->getMMI();
5876 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
5878 if (!BB->isLandingPad()) continue;
5880 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5882 for (MachineBasicBlock::iterator
5883 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5884 if (!II->isEHLabel()) continue;
5886 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5887 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5889 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5890 for (SmallVectorImpl<unsigned>::iterator
5891 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5892 CSI != CSE; ++CSI) {
5893 CallSiteNumToLPad[*CSI].push_back(BB);
5894 MaxCSNum = std::max(MaxCSNum, *CSI);
5900 // Get an ordered list of the machine basic blocks for the jump table.
5901 std::vector<MachineBasicBlock*> LPadList;
5902 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5903 LPadList.reserve(CallSiteNumToLPad.size());
5904 for (unsigned I = 1; I <= MaxCSNum; ++I) {
5905 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5906 for (SmallVectorImpl<MachineBasicBlock*>::iterator
5907 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5908 LPadList.push_back(*II);
5909 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5913 assert(!LPadList.empty() &&
5914 "No landing pad destinations for the dispatch jump table!");
5916 // Create the jump table and associated information.
5917 MachineJumpTableInfo *JTI =
5918 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5919 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5920 unsigned UId = AFI->createJumpTableUId();
5922 // Create the MBBs for the dispatch code.
5924 // Shove the dispatch's address into the return slot in the function context.
5925 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5926 DispatchBB->setIsLandingPad();
5928 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5929 BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5930 DispatchBB->addSuccessor(TrapBB);
5932 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5933 DispatchBB->addSuccessor(DispContBB);
5936 MF->insert(MF->end(), DispatchBB);
5937 MF->insert(MF->end(), DispContBB);
5938 MF->insert(MF->end(), TrapBB);
5940 // Insert code into the entry block that creates and registers the function
5942 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5944 MachineMemOperand *FIMMOLd =
5945 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5946 MachineMemOperand::MOLoad |
5947 MachineMemOperand::MOVolatile, 4, 4);
5949 if (AFI->isThumb1OnlyFunction())
5950 BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5951 else if (!Subtarget->hasVFP2())
5952 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5954 BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5956 unsigned NumLPads = LPadList.size();
5957 if (Subtarget->isThumb2()) {
5958 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5959 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5962 .addMemOperand(FIMMOLd));
5964 if (NumLPads < 256) {
5965 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5967 .addImm(LPadList.size()));
5969 unsigned VReg1 = MRI->createVirtualRegister(TRC);
5970 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5971 .addImm(NumLPads & 0xFFFF));
5973 unsigned VReg2 = VReg1;
5974 if ((NumLPads & 0xFFFF0000) != 0) {
5975 VReg2 = MRI->createVirtualRegister(TRC);
5976 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5978 .addImm(NumLPads >> 16));
5981 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5986 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5991 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5992 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5993 .addJumpTableIndex(MJTI)
5996 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5999 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6000 .addReg(NewVReg3, RegState::Kill)
6002 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6004 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6005 .addReg(NewVReg4, RegState::Kill)
6007 .addJumpTableIndex(MJTI)
6009 } else if (Subtarget->isThumb()) {
6010 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6011 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6014 .addMemOperand(FIMMOLd));
6016 if (NumLPads < 256) {
6017 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6021 MachineConstantPool *ConstantPool = MF->getConstantPool();
6022 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6023 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6025 // MachineConstantPool wants an explicit alignment.
6026 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6028 Align = getTargetData()->getTypeAllocSize(C->getType());
6029 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6031 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6032 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6033 .addReg(VReg1, RegState::Define)
6034 .addConstantPoolIndex(Idx));
6035 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6040 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6045 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6046 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6047 .addReg(ARM::CPSR, RegState::Define)
6051 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6052 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6053 .addJumpTableIndex(MJTI)
6056 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6057 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6058 .addReg(ARM::CPSR, RegState::Define)
6059 .addReg(NewVReg2, RegState::Kill)
6062 MachineMemOperand *JTMMOLd =
6063 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6064 MachineMemOperand::MOLoad, 4, 4);
6066 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6067 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6068 .addReg(NewVReg4, RegState::Kill)
6070 .addMemOperand(JTMMOLd));
6072 unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6073 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6074 .addReg(ARM::CPSR, RegState::Define)
6075 .addReg(NewVReg5, RegState::Kill)
6078 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6079 .addReg(NewVReg6, RegState::Kill)
6080 .addJumpTableIndex(MJTI)
6083 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6084 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6087 .addMemOperand(FIMMOLd));
6089 if (NumLPads < 256) {
6090 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6093 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6094 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6095 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6096 .addImm(NumLPads & 0xFFFF));
6098 unsigned VReg2 = VReg1;
6099 if ((NumLPads & 0xFFFF0000) != 0) {
6100 VReg2 = MRI->createVirtualRegister(TRC);
6101 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6103 .addImm(NumLPads >> 16));
6106 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6110 MachineConstantPool *ConstantPool = MF->getConstantPool();
6111 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6112 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6114 // MachineConstantPool wants an explicit alignment.
6115 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6117 Align = getTargetData()->getTypeAllocSize(C->getType());
6118 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6120 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6121 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6122 .addReg(VReg1, RegState::Define)
6123 .addConstantPoolIndex(Idx)
6125 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6127 .addReg(VReg1, RegState::Kill));
6130 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6135 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6137 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6139 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6140 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6141 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6142 .addJumpTableIndex(MJTI)
6145 MachineMemOperand *JTMMOLd =
6146 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6147 MachineMemOperand::MOLoad, 4, 4);
6148 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6150 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6151 .addReg(NewVReg3, RegState::Kill)
6154 .addMemOperand(JTMMOLd));
6156 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6157 .addReg(NewVReg5, RegState::Kill)
6159 .addJumpTableIndex(MJTI)
6163 // Add the jump table entries as successors to the MBB.
6164 MachineBasicBlock *PrevMBB = 0;
6165 for (std::vector<MachineBasicBlock*>::iterator
6166 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6167 MachineBasicBlock *CurMBB = *I;
6168 if (PrevMBB != CurMBB)
6169 DispContBB->addSuccessor(CurMBB);
6173 // N.B. the order the invoke BBs are processed in doesn't matter here.
6174 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6175 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6176 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6177 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6178 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6179 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6180 MachineBasicBlock *BB = *I;
6182 // Remove the landing pad successor from the invoke block and replace it
6183 // with the new dispatch block.
6184 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6186 while (!Successors.empty()) {
6187 MachineBasicBlock *SMBB = Successors.pop_back_val();
6188 if (SMBB->isLandingPad()) {
6189 BB->removeSuccessor(SMBB);
6190 MBBLPads.push_back(SMBB);
6194 BB->addSuccessor(DispatchBB);
6196 // Find the invoke call and mark all of the callee-saved registers as
6197 // 'implicit defined' so that they're spilled. This prevents code from
6198 // moving instructions to before the EH block, where they will never be
6200 for (MachineBasicBlock::reverse_iterator
6201 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6202 if (!II->isCall()) continue;
6204 DenseMap<unsigned, bool> DefRegs;
6205 for (MachineInstr::mop_iterator
6206 OI = II->operands_begin(), OE = II->operands_end();
6208 if (!OI->isReg()) continue;
6209 DefRegs[OI->getReg()] = true;
6212 MachineInstrBuilder MIB(&*II);
6214 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6215 unsigned Reg = SavedRegs[i];
6216 if (Subtarget->isThumb2() &&
6217 !ARM::tGPRRegClass.contains(Reg) &&
6218 !ARM::hGPRRegClass.contains(Reg))
6220 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6222 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6225 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6232 // Mark all former landing pads as non-landing pads. The dispatch is the only
6234 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6235 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6236 (*I)->setIsLandingPad(false);
6238 // The instruction is gone now.
6239 MI->eraseFromParent();
6245 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6246 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6247 E = MBB->succ_end(); I != E; ++I)
6250 llvm_unreachable("Expecting a BB with two successors!");
6253 MachineBasicBlock *ARMTargetLowering::
6254 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6255 // This pseudo instruction has 3 operands: dst, src, size
6256 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6257 // Otherwise, we will generate unrolled scalar copies.
6258 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6259 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6260 MachineFunction::iterator It = BB;
6263 unsigned dest = MI->getOperand(0).getReg();
6264 unsigned src = MI->getOperand(1).getReg();
6265 unsigned SizeVal = MI->getOperand(2).getImm();
6266 unsigned Align = MI->getOperand(3).getImm();
6267 DebugLoc dl = MI->getDebugLoc();
6269 bool isThumb2 = Subtarget->isThumb2();
6270 MachineFunction *MF = BB->getParent();
6271 MachineRegisterInfo &MRI = MF->getRegInfo();
6272 unsigned ldrOpc, strOpc, UnitSize = 0;
6274 const TargetRegisterClass *TRC = isThumb2 ?
6275 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6276 (const TargetRegisterClass*)&ARM::GPRRegClass;
6277 const TargetRegisterClass *TRC_Vec = 0;
6280 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6281 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6283 } else if (Align & 2) {
6284 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6285 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6288 // Check whether we can use NEON instructions.
6289 if (!MF->getFunction()->hasFnAttr(Attribute::NoImplicitFloat) &&
6290 Subtarget->hasNEON()) {
6291 if ((Align % 16 == 0) && SizeVal >= 16) {
6292 ldrOpc = ARM::VLD1q32wb_fixed;
6293 strOpc = ARM::VST1q32wb_fixed;
6295 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6297 else if ((Align % 8 == 0) && SizeVal >= 8) {
6298 ldrOpc = ARM::VLD1d32wb_fixed;
6299 strOpc = ARM::VST1d32wb_fixed;
6301 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6304 // Can't use NEON instructions.
6305 if (UnitSize == 0) {
6306 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6307 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6312 unsigned BytesLeft = SizeVal % UnitSize;
6313 unsigned LoopSize = SizeVal - BytesLeft;
6315 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6316 // Use LDR and STR to copy.
6317 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6318 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6319 unsigned srcIn = src;
6320 unsigned destIn = dest;
6321 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6322 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6323 unsigned srcOut = MRI.createVirtualRegister(TRC);
6324 unsigned destOut = MRI.createVirtualRegister(TRC);
6325 if (UnitSize >= 8) {
6326 AddDefaultPred(BuildMI(*BB, MI, dl,
6327 TII->get(ldrOpc), scratch)
6328 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6330 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6331 .addReg(destIn).addImm(0).addReg(scratch));
6332 } else if (isThumb2) {
6333 AddDefaultPred(BuildMI(*BB, MI, dl,
6334 TII->get(ldrOpc), scratch)
6335 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6337 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6338 .addReg(scratch).addReg(destIn)
6341 AddDefaultPred(BuildMI(*BB, MI, dl,
6342 TII->get(ldrOpc), scratch)
6343 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6346 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6347 .addReg(scratch).addReg(destIn)
6348 .addReg(0).addImm(UnitSize));
6354 // Handle the leftover bytes with LDRB and STRB.
6355 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6356 // [destOut] = STRB_POST(scratch, destIn, 1)
6357 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6358 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6359 for (unsigned i = 0; i < BytesLeft; i++) {
6360 unsigned scratch = MRI.createVirtualRegister(TRC);
6361 unsigned srcOut = MRI.createVirtualRegister(TRC);
6362 unsigned destOut = MRI.createVirtualRegister(TRC);
6364 AddDefaultPred(BuildMI(*BB, MI, dl,
6365 TII->get(ldrOpc),scratch)
6366 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6368 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6369 .addReg(scratch).addReg(destIn)
6370 .addReg(0).addImm(1));
6372 AddDefaultPred(BuildMI(*BB, MI, dl,
6373 TII->get(ldrOpc),scratch)
6374 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6376 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6377 .addReg(scratch).addReg(destIn)
6378 .addReg(0).addImm(1));
6383 MI->eraseFromParent(); // The instruction is gone now.
6387 // Expand the pseudo op to a loop.
6390 // movw varEnd, # --> with thumb2
6392 // ldrcp varEnd, idx --> without thumb2
6393 // fallthrough --> loopMBB
6395 // PHI varPhi, varEnd, varLoop
6396 // PHI srcPhi, src, srcLoop
6397 // PHI destPhi, dst, destLoop
6398 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6399 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6400 // subs varLoop, varPhi, #UnitSize
6402 // fallthrough --> exitMBB
6404 // epilogue to handle left-over bytes
6405 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6406 // [destOut] = STRB_POST(scratch, destLoop, 1)
6407 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6408 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6409 MF->insert(It, loopMBB);
6410 MF->insert(It, exitMBB);
6412 // Transfer the remainder of BB and its successor edges to exitMBB.
6413 exitMBB->splice(exitMBB->begin(), BB,
6414 llvm::next(MachineBasicBlock::iterator(MI)),
6416 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6418 // Load an immediate to varEnd.
6419 unsigned varEnd = MRI.createVirtualRegister(TRC);
6421 unsigned VReg1 = varEnd;
6422 if ((LoopSize & 0xFFFF0000) != 0)
6423 VReg1 = MRI.createVirtualRegister(TRC);
6424 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6425 .addImm(LoopSize & 0xFFFF));
6427 if ((LoopSize & 0xFFFF0000) != 0)
6428 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6430 .addImm(LoopSize >> 16));
6432 MachineConstantPool *ConstantPool = MF->getConstantPool();
6433 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6434 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6436 // MachineConstantPool wants an explicit alignment.
6437 unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6439 Align = getTargetData()->getTypeAllocSize(C->getType());
6440 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6442 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6443 .addReg(varEnd, RegState::Define)
6444 .addConstantPoolIndex(Idx)
6447 BB->addSuccessor(loopMBB);
6449 // Generate the loop body:
6450 // varPhi = PHI(varLoop, varEnd)
6451 // srcPhi = PHI(srcLoop, src)
6452 // destPhi = PHI(destLoop, dst)
6453 MachineBasicBlock *entryBB = BB;
6455 unsigned varLoop = MRI.createVirtualRegister(TRC);
6456 unsigned varPhi = MRI.createVirtualRegister(TRC);
6457 unsigned srcLoop = MRI.createVirtualRegister(TRC);
6458 unsigned srcPhi = MRI.createVirtualRegister(TRC);
6459 unsigned destLoop = MRI.createVirtualRegister(TRC);
6460 unsigned destPhi = MRI.createVirtualRegister(TRC);
6462 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6463 .addReg(varLoop).addMBB(loopMBB)
6464 .addReg(varEnd).addMBB(entryBB);
6465 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6466 .addReg(srcLoop).addMBB(loopMBB)
6467 .addReg(src).addMBB(entryBB);
6468 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6469 .addReg(destLoop).addMBB(loopMBB)
6470 .addReg(dest).addMBB(entryBB);
6472 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6473 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6474 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6475 if (UnitSize >= 8) {
6476 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6477 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6479 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6480 .addReg(destPhi).addImm(0).addReg(scratch));
6481 } else if (isThumb2) {
6482 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6483 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6485 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6486 .addReg(scratch).addReg(destPhi)
6489 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6490 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6493 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6494 .addReg(scratch).addReg(destPhi)
6495 .addReg(0).addImm(UnitSize));
6498 // Decrement loop variable by UnitSize.
6499 MachineInstrBuilder MIB = BuildMI(BB, dl,
6500 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6501 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6502 MIB->getOperand(5).setReg(ARM::CPSR);
6503 MIB->getOperand(5).setIsDef(true);
6505 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6506 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6508 // loopMBB can loop back to loopMBB or fall through to exitMBB.
6509 BB->addSuccessor(loopMBB);
6510 BB->addSuccessor(exitMBB);
6512 // Add epilogue to handle BytesLeft.
6514 MachineInstr *StartOfExit = exitMBB->begin();
6515 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6516 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6518 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6519 // [destOut] = STRB_POST(scratch, destLoop, 1)
6520 unsigned srcIn = srcLoop;
6521 unsigned destIn = destLoop;
6522 for (unsigned i = 0; i < BytesLeft; i++) {
6523 unsigned scratch = MRI.createVirtualRegister(TRC);
6524 unsigned srcOut = MRI.createVirtualRegister(TRC);
6525 unsigned destOut = MRI.createVirtualRegister(TRC);
6527 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6528 TII->get(ldrOpc),scratch)
6529 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6531 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6532 .addReg(scratch).addReg(destIn)
6535 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6536 TII->get(ldrOpc),scratch)
6537 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6539 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6540 .addReg(scratch).addReg(destIn)
6541 .addReg(0).addImm(1));
6547 MI->eraseFromParent(); // The instruction is gone now.
6552 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6553 MachineBasicBlock *BB) const {
6554 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6555 DebugLoc dl = MI->getDebugLoc();
6556 bool isThumb2 = Subtarget->isThumb2();
6557 switch (MI->getOpcode()) {
6560 llvm_unreachable("Unexpected instr type to insert");
6562 // The Thumb2 pre-indexed stores have the same MI operands, they just
6563 // define them differently in the .td files from the isel patterns, so
6564 // they need pseudos.
6565 case ARM::t2STR_preidx:
6566 MI->setDesc(TII->get(ARM::t2STR_PRE));
6568 case ARM::t2STRB_preidx:
6569 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6571 case ARM::t2STRH_preidx:
6572 MI->setDesc(TII->get(ARM::t2STRH_PRE));
6575 case ARM::STRi_preidx:
6576 case ARM::STRBi_preidx: {
6577 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6578 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6579 // Decode the offset.
6580 unsigned Offset = MI->getOperand(4).getImm();
6581 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6582 Offset = ARM_AM::getAM2Offset(Offset);
6586 MachineMemOperand *MMO = *MI->memoperands_begin();
6587 BuildMI(*BB, MI, dl, TII->get(NewOpc))
6588 .addOperand(MI->getOperand(0)) // Rn_wb
6589 .addOperand(MI->getOperand(1)) // Rt
6590 .addOperand(MI->getOperand(2)) // Rn
6591 .addImm(Offset) // offset (skip GPR==zero_reg)
6592 .addOperand(MI->getOperand(5)) // pred
6593 .addOperand(MI->getOperand(6))
6594 .addMemOperand(MMO);
6595 MI->eraseFromParent();
6598 case ARM::STRr_preidx:
6599 case ARM::STRBr_preidx:
6600 case ARM::STRH_preidx: {
6602 switch (MI->getOpcode()) {
6603 default: llvm_unreachable("unexpected opcode!");
6604 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6605 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6606 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6608 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6609 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6610 MIB.addOperand(MI->getOperand(i));
6611 MI->eraseFromParent();
6614 case ARM::ATOMIC_LOAD_ADD_I8:
6615 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6616 case ARM::ATOMIC_LOAD_ADD_I16:
6617 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6618 case ARM::ATOMIC_LOAD_ADD_I32:
6619 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6621 case ARM::ATOMIC_LOAD_AND_I8:
6622 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6623 case ARM::ATOMIC_LOAD_AND_I16:
6624 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6625 case ARM::ATOMIC_LOAD_AND_I32:
6626 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6628 case ARM::ATOMIC_LOAD_OR_I8:
6629 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6630 case ARM::ATOMIC_LOAD_OR_I16:
6631 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6632 case ARM::ATOMIC_LOAD_OR_I32:
6633 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6635 case ARM::ATOMIC_LOAD_XOR_I8:
6636 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6637 case ARM::ATOMIC_LOAD_XOR_I16:
6638 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6639 case ARM::ATOMIC_LOAD_XOR_I32:
6640 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6642 case ARM::ATOMIC_LOAD_NAND_I8:
6643 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6644 case ARM::ATOMIC_LOAD_NAND_I16:
6645 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6646 case ARM::ATOMIC_LOAD_NAND_I32:
6647 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6649 case ARM::ATOMIC_LOAD_SUB_I8:
6650 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6651 case ARM::ATOMIC_LOAD_SUB_I16:
6652 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6653 case ARM::ATOMIC_LOAD_SUB_I32:
6654 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6656 case ARM::ATOMIC_LOAD_MIN_I8:
6657 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6658 case ARM::ATOMIC_LOAD_MIN_I16:
6659 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6660 case ARM::ATOMIC_LOAD_MIN_I32:
6661 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6663 case ARM::ATOMIC_LOAD_MAX_I8:
6664 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6665 case ARM::ATOMIC_LOAD_MAX_I16:
6666 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6667 case ARM::ATOMIC_LOAD_MAX_I32:
6668 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6670 case ARM::ATOMIC_LOAD_UMIN_I8:
6671 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6672 case ARM::ATOMIC_LOAD_UMIN_I16:
6673 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6674 case ARM::ATOMIC_LOAD_UMIN_I32:
6675 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6677 case ARM::ATOMIC_LOAD_UMAX_I8:
6678 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6679 case ARM::ATOMIC_LOAD_UMAX_I16:
6680 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6681 case ARM::ATOMIC_LOAD_UMAX_I32:
6682 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6684 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
6685 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6686 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6688 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
6689 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6690 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6693 case ARM::ATOMADD6432:
6694 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6695 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6696 /*NeedsCarry*/ true);
6697 case ARM::ATOMSUB6432:
6698 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6699 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6700 /*NeedsCarry*/ true);
6701 case ARM::ATOMOR6432:
6702 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6703 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6704 case ARM::ATOMXOR6432:
6705 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6706 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6707 case ARM::ATOMAND6432:
6708 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6709 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6710 case ARM::ATOMSWAP6432:
6711 return EmitAtomicBinary64(MI, BB, 0, 0, false);
6712 case ARM::ATOMCMPXCHG6432:
6713 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6714 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6715 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6717 case ARM::tMOVCCr_pseudo: {
6718 // To "insert" a SELECT_CC instruction, we actually have to insert the
6719 // diamond control-flow pattern. The incoming instruction knows the
6720 // destination vreg to set, the condition code register to branch on, the
6721 // true/false values to select between, and a branch opcode to use.
6722 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6723 MachineFunction::iterator It = BB;
6729 // cmpTY ccX, r1, r2
6731 // fallthrough --> copy0MBB
6732 MachineBasicBlock *thisMBB = BB;
6733 MachineFunction *F = BB->getParent();
6734 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6735 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6736 F->insert(It, copy0MBB);
6737 F->insert(It, sinkMBB);
6739 // Transfer the remainder of BB and its successor edges to sinkMBB.
6740 sinkMBB->splice(sinkMBB->begin(), BB,
6741 llvm::next(MachineBasicBlock::iterator(MI)),
6743 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6745 BB->addSuccessor(copy0MBB);
6746 BB->addSuccessor(sinkMBB);
6748 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6749 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6752 // %FalseValue = ...
6753 // # fallthrough to sinkMBB
6756 // Update machine-CFG edges
6757 BB->addSuccessor(sinkMBB);
6760 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6763 BuildMI(*BB, BB->begin(), dl,
6764 TII->get(ARM::PHI), MI->getOperand(0).getReg())
6765 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6766 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6768 MI->eraseFromParent(); // The pseudo instruction is gone now.
6773 case ARM::BCCZi64: {
6774 // If there is an unconditional branch to the other successor, remove it.
6775 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6777 // Compare both parts that make up the double comparison separately for
6779 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6781 unsigned LHS1 = MI->getOperand(1).getReg();
6782 unsigned LHS2 = MI->getOperand(2).getReg();
6784 AddDefaultPred(BuildMI(BB, dl,
6785 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6786 .addReg(LHS1).addImm(0));
6787 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6788 .addReg(LHS2).addImm(0)
6789 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6791 unsigned RHS1 = MI->getOperand(3).getReg();
6792 unsigned RHS2 = MI->getOperand(4).getReg();
6793 AddDefaultPred(BuildMI(BB, dl,
6794 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6795 .addReg(LHS1).addReg(RHS1));
6796 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6797 .addReg(LHS2).addReg(RHS2)
6798 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6801 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6802 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6803 if (MI->getOperand(0).getImm() == ARMCC::NE)
6804 std::swap(destMBB, exitMBB);
6806 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6807 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6809 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6811 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6813 MI->eraseFromParent(); // The pseudo instruction is gone now.
6817 case ARM::Int_eh_sjlj_setjmp:
6818 case ARM::Int_eh_sjlj_setjmp_nofp:
6819 case ARM::tInt_eh_sjlj_setjmp:
6820 case ARM::t2Int_eh_sjlj_setjmp:
6821 case ARM::t2Int_eh_sjlj_setjmp_nofp:
6822 EmitSjLjDispatchBlock(MI, BB);
6827 // To insert an ABS instruction, we have to insert the
6828 // diamond control-flow pattern. The incoming instruction knows the
6829 // source vreg to test against 0, the destination vreg to set,
6830 // the condition code register to branch on, the
6831 // true/false values to select between, and a branch opcode to use.
6836 // BCC (branch to SinkBB if V0 >= 0)
6837 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
6838 // SinkBB: V1 = PHI(V2, V3)
6839 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6840 MachineFunction::iterator BBI = BB;
6842 MachineFunction *Fn = BB->getParent();
6843 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6844 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6845 Fn->insert(BBI, RSBBB);
6846 Fn->insert(BBI, SinkBB);
6848 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6849 unsigned int ABSDstReg = MI->getOperand(0).getReg();
6850 bool isThumb2 = Subtarget->isThumb2();
6851 MachineRegisterInfo &MRI = Fn->getRegInfo();
6852 // In Thumb mode S must not be specified if source register is the SP or
6853 // PC and if destination register is the SP, so restrict register class
6854 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
6855 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6856 (const TargetRegisterClass*)&ARM::GPRRegClass);
6858 // Transfer the remainder of BB and its successor edges to sinkMBB.
6859 SinkBB->splice(SinkBB->begin(), BB,
6860 llvm::next(MachineBasicBlock::iterator(MI)),
6862 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6864 BB->addSuccessor(RSBBB);
6865 BB->addSuccessor(SinkBB);
6867 // fall through to SinkMBB
6868 RSBBB->addSuccessor(SinkBB);
6870 // insert a cmp at the end of BB
6871 AddDefaultPred(BuildMI(BB, dl,
6872 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6873 .addReg(ABSSrcReg).addImm(0));
6875 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6877 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6878 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6880 // insert rsbri in RSBBB
6881 // Note: BCC and rsbri will be converted into predicated rsbmi
6882 // by if-conversion pass
6883 BuildMI(*RSBBB, RSBBB->begin(), dl,
6884 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6885 .addReg(ABSSrcReg, RegState::Kill)
6886 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6888 // insert PHI in SinkBB,
6889 // reuse ABSDstReg to not change uses of ABS instruction
6890 BuildMI(*SinkBB, SinkBB->begin(), dl,
6891 TII->get(ARM::PHI), ABSDstReg)
6892 .addReg(NewRsbDstReg).addMBB(RSBBB)
6893 .addReg(ABSSrcReg).addMBB(BB);
6895 // remove ABS instruction
6896 MI->eraseFromParent();
6898 // return last added BB
6901 case ARM::COPY_STRUCT_BYVAL_I32:
6903 return EmitStructByval(MI, BB);
6907 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6908 SDNode *Node) const {
6909 if (!MI->hasPostISelHook()) {
6910 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6911 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6915 const MCInstrDesc *MCID = &MI->getDesc();
6916 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6917 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6918 // operand is still set to noreg. If needed, set the optional operand's
6919 // register to CPSR, and remove the redundant implicit def.
6921 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6923 // Rename pseudo opcodes.
6924 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6926 const ARMBaseInstrInfo *TII =
6927 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6928 MCID = &TII->get(NewOpc);
6930 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6931 "converted opcode should be the same except for cc_out");
6935 // Add the optional cc_out operand
6936 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6938 unsigned ccOutIdx = MCID->getNumOperands() - 1;
6940 // Any ARM instruction that sets the 's' bit should specify an optional
6941 // "cc_out" operand in the last operand position.
6942 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6943 assert(!NewOpc && "Optional cc_out operand required");
6946 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6947 // since we already have an optional CPSR def.
6948 bool definesCPSR = false;
6949 bool deadCPSR = false;
6950 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6952 const MachineOperand &MO = MI->getOperand(i);
6953 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6957 MI->RemoveOperand(i);
6962 assert(!NewOpc && "Optional cc_out operand required");
6965 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6967 assert(!MI->getOperand(ccOutIdx).getReg() &&
6968 "expect uninitialized optional cc_out operand");
6972 // If this instruction was defined with an optional CPSR def and its dag node
6973 // had a live implicit CPSR def, then activate the optional CPSR def.
6974 MachineOperand &MO = MI->getOperand(ccOutIdx);
6975 MO.setReg(ARM::CPSR);
6979 //===----------------------------------------------------------------------===//
6980 // ARM Optimization Hooks
6981 //===----------------------------------------------------------------------===//
6984 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6985 TargetLowering::DAGCombinerInfo &DCI) {
6986 SelectionDAG &DAG = DCI.DAG;
6987 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6988 EVT VT = N->getValueType(0);
6989 unsigned Opc = N->getOpcode();
6990 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6991 SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6992 SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6993 ISD::CondCode CC = ISD::SETCC_INVALID;
6996 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6998 SDValue CCOp = Slct.getOperand(0);
6999 if (CCOp.getOpcode() == ISD::SETCC)
7000 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
7003 bool DoXform = false;
7005 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
7008 if (LHS.getOpcode() == ISD::Constant &&
7009 cast<ConstantSDNode>(LHS)->isNullValue()) {
7011 } else if (CC != ISD::SETCC_INVALID &&
7012 RHS.getOpcode() == ISD::Constant &&
7013 cast<ConstantSDNode>(RHS)->isNullValue()) {
7014 std::swap(LHS, RHS);
7015 SDValue Op0 = Slct.getOperand(0);
7016 EVT OpVT = isSlctCC ? Op0.getValueType() :
7017 Op0.getOperand(0).getValueType();
7018 bool isInt = OpVT.isInteger();
7019 CC = ISD::getSetCCInverse(CC, isInt);
7021 if (!TLI.isCondCodeLegal(CC, OpVT))
7022 return SDValue(); // Inverse operator isn't legal.
7029 SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
7031 return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
7032 Slct.getOperand(0), Slct.getOperand(1), CC);
7033 SDValue CCOp = Slct.getOperand(0);
7035 CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
7036 CCOp.getOperand(0), CCOp.getOperand(1), CC);
7037 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7038 CCOp, OtherOp, Result);
7043 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7044 // (only after legalization).
7045 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7046 TargetLowering::DAGCombinerInfo &DCI,
7047 const ARMSubtarget *Subtarget) {
7049 // Only perform optimization if after legalize, and if NEON is available. We
7050 // also expected both operands to be BUILD_VECTORs.
7051 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7052 || N0.getOpcode() != ISD::BUILD_VECTOR
7053 || N1.getOpcode() != ISD::BUILD_VECTOR)
7056 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7057 EVT VT = N->getValueType(0);
7058 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7061 // Check that the vector operands are of the right form.
7062 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7063 // operands, where N is the size of the formed vector.
7064 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7065 // index such that we have a pair wise add pattern.
7067 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7068 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7070 SDValue Vec = N0->getOperand(0)->getOperand(0);
7071 SDNode *V = Vec.getNode();
7072 unsigned nextIndex = 0;
7074 // For each operands to the ADD which are BUILD_VECTORs,
7075 // check to see if each of their operands are an EXTRACT_VECTOR with
7076 // the same vector and appropriate index.
7077 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7078 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7079 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7081 SDValue ExtVec0 = N0->getOperand(i);
7082 SDValue ExtVec1 = N1->getOperand(i);
7084 // First operand is the vector, verify its the same.
7085 if (V != ExtVec0->getOperand(0).getNode() ||
7086 V != ExtVec1->getOperand(0).getNode())
7089 // Second is the constant, verify its correct.
7090 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7091 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7093 // For the constant, we want to see all the even or all the odd.
7094 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7095 || C1->getZExtValue() != nextIndex+1)
7104 // Create VPADDL node.
7105 SelectionDAG &DAG = DCI.DAG;
7106 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7108 // Build operand list.
7109 SmallVector<SDValue, 8> Ops;
7110 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7111 TLI.getPointerTy()));
7113 // Input is the vector.
7116 // Get widened type and narrowed type.
7118 unsigned numElem = VT.getVectorNumElements();
7119 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7120 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7121 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7122 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7124 llvm_unreachable("Invalid vector element type for padd optimization.");
7127 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7128 widenType, &Ops[0], Ops.size());
7129 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7132 static SDValue findMUL_LOHI(SDValue V) {
7133 if (V->getOpcode() == ISD::UMUL_LOHI ||
7134 V->getOpcode() == ISD::SMUL_LOHI)
7139 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7140 TargetLowering::DAGCombinerInfo &DCI,
7141 const ARMSubtarget *Subtarget) {
7143 if (Subtarget->isThumb1Only()) return SDValue();
7145 // Only perform the checks after legalize when the pattern is available.
7146 if (DCI.isBeforeLegalize()) return SDValue();
7148 // Look for multiply add opportunities.
7149 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7150 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7151 // a glue link from the first add to the second add.
7152 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7153 // a S/UMLAL instruction.
7156 // \ / \ [no multiline comment]
7162 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7163 SDValue AddcOp0 = AddcNode->getOperand(0);
7164 SDValue AddcOp1 = AddcNode->getOperand(1);
7166 // Check if the two operands are from the same mul_lohi node.
7167 if (AddcOp0.getNode() == AddcOp1.getNode())
7170 assert(AddcNode->getNumValues() == 2 &&
7171 AddcNode->getValueType(0) == MVT::i32 &&
7172 AddcNode->getValueType(1) == MVT::Glue &&
7173 "Expect ADDC with two result values: i32, glue");
7175 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7176 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7177 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7178 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7179 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7182 // Look for the glued ADDE.
7183 SDNode* AddeNode = AddcNode->getGluedUser();
7184 if (AddeNode == NULL)
7187 // Make sure it is really an ADDE.
7188 if (AddeNode->getOpcode() != ISD::ADDE)
7191 assert(AddeNode->getNumOperands() == 3 &&
7192 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7193 "ADDE node has the wrong inputs");
7195 // Check for the triangle shape.
7196 SDValue AddeOp0 = AddeNode->getOperand(0);
7197 SDValue AddeOp1 = AddeNode->getOperand(1);
7199 // Make sure that the ADDE operands are not coming from the same node.
7200 if (AddeOp0.getNode() == AddeOp1.getNode())
7203 // Find the MUL_LOHI node walking up ADDE's operands.
7204 bool IsLeftOperandMUL = false;
7205 SDValue MULOp = findMUL_LOHI(AddeOp0);
7206 if (MULOp == SDValue())
7207 MULOp = findMUL_LOHI(AddeOp1);
7209 IsLeftOperandMUL = true;
7210 if (MULOp == SDValue())
7213 // Figure out the right opcode.
7214 unsigned Opc = MULOp->getOpcode();
7215 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7217 // Figure out the high and low input values to the MLAL node.
7218 SDValue* HiMul = &MULOp;
7219 SDValue* HiAdd = NULL;
7220 SDValue* LoMul = NULL;
7221 SDValue* LowAdd = NULL;
7223 if (IsLeftOperandMUL)
7229 if (AddcOp0->getOpcode() == Opc) {
7233 if (AddcOp1->getOpcode() == Opc) {
7241 if (LoMul->getNode() != HiMul->getNode())
7244 // Create the merged node.
7245 SelectionDAG &DAG = DCI.DAG;
7247 // Build operand list.
7248 SmallVector<SDValue, 8> Ops;
7249 Ops.push_back(LoMul->getOperand(0));
7250 Ops.push_back(LoMul->getOperand(1));
7251 Ops.push_back(*LowAdd);
7252 Ops.push_back(*HiAdd);
7254 SDValue MLALNode = DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7255 DAG.getVTList(MVT::i32, MVT::i32),
7256 &Ops[0], Ops.size());
7258 // Replace the ADDs' nodes uses by the MLA node's values.
7259 SDValue HiMLALResult(MLALNode.getNode(), 1);
7260 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7262 SDValue LoMLALResult(MLALNode.getNode(), 0);
7263 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7265 // Return original node to notify the driver to stop replacing.
7266 SDValue resNode(AddcNode, 0);
7270 /// PerformADDCCombine - Target-specific dag combine transform from
7271 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7272 static SDValue PerformADDCCombine(SDNode *N,
7273 TargetLowering::DAGCombinerInfo &DCI,
7274 const ARMSubtarget *Subtarget) {
7276 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7280 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7281 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7282 /// called with the default operands, and if that fails, with commuted
7284 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7285 TargetLowering::DAGCombinerInfo &DCI,
7286 const ARMSubtarget *Subtarget){
7288 // Attempt to create vpaddl for this add.
7289 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7290 if (Result.getNode())
7293 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7294 if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
7295 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7296 if (Result.getNode()) return Result;
7301 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7303 static SDValue PerformADDCombine(SDNode *N,
7304 TargetLowering::DAGCombinerInfo &DCI,
7305 const ARMSubtarget *Subtarget) {
7306 SDValue N0 = N->getOperand(0);
7307 SDValue N1 = N->getOperand(1);
7309 // First try with the default operand order.
7310 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7311 if (Result.getNode())
7314 // If that didn't work, try again with the operands commuted.
7315 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7318 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7320 static SDValue PerformSUBCombine(SDNode *N,
7321 TargetLowering::DAGCombinerInfo &DCI) {
7322 SDValue N0 = N->getOperand(0);
7323 SDValue N1 = N->getOperand(1);
7325 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7326 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
7327 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7328 if (Result.getNode()) return Result;
7334 /// PerformVMULCombine
7335 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7336 /// special multiplier accumulator forwarding.
7342 static SDValue PerformVMULCombine(SDNode *N,
7343 TargetLowering::DAGCombinerInfo &DCI,
7344 const ARMSubtarget *Subtarget) {
7345 if (!Subtarget->hasVMLxForwarding())
7348 SelectionDAG &DAG = DCI.DAG;
7349 SDValue N0 = N->getOperand(0);
7350 SDValue N1 = N->getOperand(1);
7351 unsigned Opcode = N0.getOpcode();
7352 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7353 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7354 Opcode = N1.getOpcode();
7355 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7356 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7361 EVT VT = N->getValueType(0);
7362 DebugLoc DL = N->getDebugLoc();
7363 SDValue N00 = N0->getOperand(0);
7364 SDValue N01 = N0->getOperand(1);
7365 return DAG.getNode(Opcode, DL, VT,
7366 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7367 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7370 static SDValue PerformMULCombine(SDNode *N,
7371 TargetLowering::DAGCombinerInfo &DCI,
7372 const ARMSubtarget *Subtarget) {
7373 SelectionDAG &DAG = DCI.DAG;
7375 if (Subtarget->isThumb1Only())
7378 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7381 EVT VT = N->getValueType(0);
7382 if (VT.is64BitVector() || VT.is128BitVector())
7383 return PerformVMULCombine(N, DCI, Subtarget);
7387 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7391 int64_t MulAmt = C->getSExtValue();
7392 unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7394 ShiftAmt = ShiftAmt & (32 - 1);
7395 SDValue V = N->getOperand(0);
7396 DebugLoc DL = N->getDebugLoc();
7399 MulAmt >>= ShiftAmt;
7402 if (isPowerOf2_32(MulAmt - 1)) {
7403 // (mul x, 2^N + 1) => (add (shl x, N), x)
7404 Res = DAG.getNode(ISD::ADD, DL, VT,
7406 DAG.getNode(ISD::SHL, DL, VT,
7408 DAG.getConstant(Log2_32(MulAmt - 1),
7410 } else if (isPowerOf2_32(MulAmt + 1)) {
7411 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7412 Res = DAG.getNode(ISD::SUB, DL, VT,
7413 DAG.getNode(ISD::SHL, DL, VT,
7415 DAG.getConstant(Log2_32(MulAmt + 1),
7421 uint64_t MulAmtAbs = -MulAmt;
7422 if (isPowerOf2_32(MulAmtAbs + 1)) {
7423 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7424 Res = DAG.getNode(ISD::SUB, DL, VT,
7426 DAG.getNode(ISD::SHL, DL, VT,
7428 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7430 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7431 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7432 Res = DAG.getNode(ISD::ADD, DL, VT,
7434 DAG.getNode(ISD::SHL, DL, VT,
7436 DAG.getConstant(Log2_32(MulAmtAbs-1),
7438 Res = DAG.getNode(ISD::SUB, DL, VT,
7439 DAG.getConstant(0, MVT::i32),Res);
7446 Res = DAG.getNode(ISD::SHL, DL, VT,
7447 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7449 // Do not add new nodes to DAG combiner worklist.
7450 DCI.CombineTo(N, Res, false);
7454 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
7455 if (N.getOpcode() != ARMISD::CMOV || !N.getNode()->hasOneUse())
7458 SDValue FalseVal = N.getOperand(0);
7459 ConstantSDNode *C = dyn_cast<ConstantSDNode>(FalseVal);
7463 return C->isAllOnesValue();
7464 return C->isNullValue();
7467 /// formConditionalOp - Combine an operation with a conditional move operand
7468 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
7469 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
7470 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
7472 SDValue N0 = N->getOperand(0);
7473 SDValue N1 = N->getOperand(1);
7475 bool isAND = N->getOpcode() == ISD::AND;
7476 bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
7477 if (!isCand && Commutable) {
7478 isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
7486 switch (N->getOpcode()) {
7487 default: llvm_unreachable("Unexpected node");
7488 case ISD::AND: Opc = ARMISD::CAND; break;
7489 case ISD::OR: Opc = ARMISD::COR; break;
7490 case ISD::XOR: Opc = ARMISD::CXOR; break;
7492 return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
7493 N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
7497 static SDValue PerformANDCombine(SDNode *N,
7498 TargetLowering::DAGCombinerInfo &DCI,
7499 const ARMSubtarget *Subtarget) {
7501 // Attempt to use immediate-form VBIC
7502 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7503 DebugLoc dl = N->getDebugLoc();
7504 EVT VT = N->getValueType(0);
7505 SelectionDAG &DAG = DCI.DAG;
7507 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7510 APInt SplatBits, SplatUndef;
7511 unsigned SplatBitSize;
7514 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7515 if (SplatBitSize <= 64) {
7517 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7518 SplatUndef.getZExtValue(), SplatBitSize,
7519 DAG, VbicVT, VT.is128BitVector(),
7521 if (Val.getNode()) {
7523 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7524 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7525 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7530 if (!Subtarget->isThumb1Only()) {
7531 // (and x, (cmov -1, y, cond)) => (and.cond x, y)
7532 SDValue CAND = formConditionalOp(N, DAG, true);
7540 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7541 static SDValue PerformORCombine(SDNode *N,
7542 TargetLowering::DAGCombinerInfo &DCI,
7543 const ARMSubtarget *Subtarget) {
7544 // Attempt to use immediate-form VORR
7545 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7546 DebugLoc dl = N->getDebugLoc();
7547 EVT VT = N->getValueType(0);
7548 SelectionDAG &DAG = DCI.DAG;
7550 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7553 APInt SplatBits, SplatUndef;
7554 unsigned SplatBitSize;
7556 if (BVN && Subtarget->hasNEON() &&
7557 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7558 if (SplatBitSize <= 64) {
7560 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7561 SplatUndef.getZExtValue(), SplatBitSize,
7562 DAG, VorrVT, VT.is128BitVector(),
7564 if (Val.getNode()) {
7566 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7567 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7568 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7573 if (!Subtarget->isThumb1Only()) {
7574 // (or x, (cmov 0, y, cond)) => (or.cond x, y)
7575 SDValue COR = formConditionalOp(N, DAG, true);
7580 SDValue N0 = N->getOperand(0);
7581 if (N0.getOpcode() != ISD::AND)
7583 SDValue N1 = N->getOperand(1);
7585 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7586 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7587 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7589 unsigned SplatBitSize;
7592 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7594 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7595 HasAnyUndefs) && !HasAnyUndefs) {
7596 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7598 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7599 HasAnyUndefs) && !HasAnyUndefs &&
7600 SplatBits0 == ~SplatBits1) {
7601 // Canonicalize the vector type to make instruction selection simpler.
7602 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7603 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7604 N0->getOperand(1), N0->getOperand(0),
7606 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7611 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7614 // BFI is only available on V6T2+
7615 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7618 DebugLoc DL = N->getDebugLoc();
7619 // 1) or (and A, mask), val => ARMbfi A, val, mask
7620 // iff (val & mask) == val
7622 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7623 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7624 // && mask == ~mask2
7625 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7626 // && ~mask == mask2
7627 // (i.e., copy a bitfield value into another bitfield of the same width)
7632 SDValue N00 = N0.getOperand(0);
7634 // The value and the mask need to be constants so we can verify this is
7635 // actually a bitfield set. If the mask is 0xffff, we can do better
7636 // via a movt instruction, so don't use BFI in that case.
7637 SDValue MaskOp = N0.getOperand(1);
7638 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7641 unsigned Mask = MaskC->getZExtValue();
7645 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7646 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7648 unsigned Val = N1C->getZExtValue();
7649 if ((Val & ~Mask) != Val)
7652 if (ARM::isBitFieldInvertedMask(Mask)) {
7653 Val >>= CountTrailingZeros_32(~Mask);
7655 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7656 DAG.getConstant(Val, MVT::i32),
7657 DAG.getConstant(Mask, MVT::i32));
7659 // Do not add new nodes to DAG combiner worklist.
7660 DCI.CombineTo(N, Res, false);
7663 } else if (N1.getOpcode() == ISD::AND) {
7664 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7665 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7668 unsigned Mask2 = N11C->getZExtValue();
7670 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7672 if (ARM::isBitFieldInvertedMask(Mask) &&
7674 // The pack halfword instruction works better for masks that fit it,
7675 // so use that when it's available.
7676 if (Subtarget->hasT2ExtractPack() &&
7677 (Mask == 0xffff || Mask == 0xffff0000))
7680 unsigned amt = CountTrailingZeros_32(Mask2);
7681 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7682 DAG.getConstant(amt, MVT::i32));
7683 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7684 DAG.getConstant(Mask, MVT::i32));
7685 // Do not add new nodes to DAG combiner worklist.
7686 DCI.CombineTo(N, Res, false);
7688 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7690 // The pack halfword instruction works better for masks that fit it,
7691 // so use that when it's available.
7692 if (Subtarget->hasT2ExtractPack() &&
7693 (Mask2 == 0xffff || Mask2 == 0xffff0000))
7696 unsigned lsb = CountTrailingZeros_32(Mask);
7697 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7698 DAG.getConstant(lsb, MVT::i32));
7699 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7700 DAG.getConstant(Mask2, MVT::i32));
7701 // Do not add new nodes to DAG combiner worklist.
7702 DCI.CombineTo(N, Res, false);
7707 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7708 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7709 ARM::isBitFieldInvertedMask(~Mask)) {
7710 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7711 // where lsb(mask) == #shamt and masked bits of B are known zero.
7712 SDValue ShAmt = N00.getOperand(1);
7713 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7714 unsigned LSB = CountTrailingZeros_32(Mask);
7718 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7719 DAG.getConstant(~Mask, MVT::i32));
7721 // Do not add new nodes to DAG combiner worklist.
7722 DCI.CombineTo(N, Res, false);
7728 static SDValue PerformXORCombine(SDNode *N,
7729 TargetLowering::DAGCombinerInfo &DCI,
7730 const ARMSubtarget *Subtarget) {
7731 EVT VT = N->getValueType(0);
7732 SelectionDAG &DAG = DCI.DAG;
7734 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7737 if (!Subtarget->isThumb1Only()) {
7738 // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7739 SDValue CXOR = formConditionalOp(N, DAG, true);
7747 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7748 /// the bits being cleared by the AND are not demanded by the BFI.
7749 static SDValue PerformBFICombine(SDNode *N,
7750 TargetLowering::DAGCombinerInfo &DCI) {
7751 SDValue N1 = N->getOperand(1);
7752 if (N1.getOpcode() == ISD::AND) {
7753 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7756 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7757 unsigned LSB = CountTrailingZeros_32(~InvMask);
7758 unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7759 unsigned Mask = (1 << Width)-1;
7760 unsigned Mask2 = N11C->getZExtValue();
7761 if ((Mask & (~Mask2)) == 0)
7762 return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7763 N->getOperand(0), N1.getOperand(0),
7769 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7770 /// ARMISD::VMOVRRD.
7771 static SDValue PerformVMOVRRDCombine(SDNode *N,
7772 TargetLowering::DAGCombinerInfo &DCI) {
7773 // vmovrrd(vmovdrr x, y) -> x,y
7774 SDValue InDouble = N->getOperand(0);
7775 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7776 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7778 // vmovrrd(load f64) -> (load i32), (load i32)
7779 SDNode *InNode = InDouble.getNode();
7780 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7781 InNode->getValueType(0) == MVT::f64 &&
7782 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7783 !cast<LoadSDNode>(InNode)->isVolatile()) {
7784 // TODO: Should this be done for non-FrameIndex operands?
7785 LoadSDNode *LD = cast<LoadSDNode>(InNode);
7787 SelectionDAG &DAG = DCI.DAG;
7788 DebugLoc DL = LD->getDebugLoc();
7789 SDValue BasePtr = LD->getBasePtr();
7790 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7791 LD->getPointerInfo(), LD->isVolatile(),
7792 LD->isNonTemporal(), LD->isInvariant(),
7793 LD->getAlignment());
7795 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7796 DAG.getConstant(4, MVT::i32));
7797 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7798 LD->getPointerInfo(), LD->isVolatile(),
7799 LD->isNonTemporal(), LD->isInvariant(),
7800 std::min(4U, LD->getAlignment() / 2));
7802 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7803 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7804 DCI.RemoveFromWorklist(LD);
7812 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7813 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
7814 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7815 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7816 SDValue Op0 = N->getOperand(0);
7817 SDValue Op1 = N->getOperand(1);
7818 if (Op0.getOpcode() == ISD::BITCAST)
7819 Op0 = Op0.getOperand(0);
7820 if (Op1.getOpcode() == ISD::BITCAST)
7821 Op1 = Op1.getOperand(0);
7822 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7823 Op0.getNode() == Op1.getNode() &&
7824 Op0.getResNo() == 0 && Op1.getResNo() == 1)
7825 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7826 N->getValueType(0), Op0.getOperand(0));
7830 /// PerformSTORECombine - Target-specific dag combine xforms for
7832 static SDValue PerformSTORECombine(SDNode *N,
7833 TargetLowering::DAGCombinerInfo &DCI) {
7834 StoreSDNode *St = cast<StoreSDNode>(N);
7835 if (St->isVolatile())
7838 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
7839 // pack all of the elements in one place. Next, store to memory in fewer
7841 SDValue StVal = St->getValue();
7842 EVT VT = StVal.getValueType();
7843 if (St->isTruncatingStore() && VT.isVector()) {
7844 SelectionDAG &DAG = DCI.DAG;
7845 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7846 EVT StVT = St->getMemoryVT();
7847 unsigned NumElems = VT.getVectorNumElements();
7848 assert(StVT != VT && "Cannot truncate to the same type");
7849 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
7850 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
7852 // From, To sizes and ElemCount must be pow of two
7853 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
7855 // We are going to use the original vector elt for storing.
7856 // Accumulated smaller vector elements must be a multiple of the store size.
7857 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
7859 unsigned SizeRatio = FromEltSz / ToEltSz;
7860 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
7862 // Create a type on which we perform the shuffle.
7863 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
7864 NumElems*SizeRatio);
7865 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
7867 DebugLoc DL = St->getDebugLoc();
7868 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
7869 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
7870 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
7872 // Can't shuffle using an illegal type.
7873 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
7875 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
7876 DAG.getUNDEF(WideVec.getValueType()),
7878 // At this point all of the data is stored at the bottom of the
7879 // register. We now need to save it to mem.
7881 // Find the largest store unit
7882 MVT StoreType = MVT::i8;
7883 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
7884 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
7885 MVT Tp = (MVT::SimpleValueType)tp;
7886 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
7889 // Didn't find a legal store type.
7890 if (!TLI.isTypeLegal(StoreType))
7893 // Bitcast the original vector into a vector of store-size units
7894 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
7895 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
7896 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
7897 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
7898 SmallVector<SDValue, 8> Chains;
7899 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
7900 TLI.getPointerTy());
7901 SDValue BasePtr = St->getBasePtr();
7903 // Perform one or more big stores into memory.
7904 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
7905 for (unsigned I = 0; I < E; I++) {
7906 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
7907 StoreType, ShuffWide,
7908 DAG.getIntPtrConstant(I));
7909 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
7910 St->getPointerInfo(), St->isVolatile(),
7911 St->isNonTemporal(), St->getAlignment());
7912 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
7914 Chains.push_back(Ch);
7916 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
7920 if (!ISD::isNormalStore(St))
7923 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
7924 // ARM stores of arguments in the same cache line.
7925 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7926 StVal.getNode()->hasOneUse()) {
7927 SelectionDAG &DAG = DCI.DAG;
7928 DebugLoc DL = St->getDebugLoc();
7929 SDValue BasePtr = St->getBasePtr();
7930 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7931 StVal.getNode()->getOperand(0), BasePtr,
7932 St->getPointerInfo(), St->isVolatile(),
7933 St->isNonTemporal(), St->getAlignment());
7935 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7936 DAG.getConstant(4, MVT::i32));
7937 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7938 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7939 St->isNonTemporal(),
7940 std::min(4U, St->getAlignment() / 2));
7943 if (StVal.getValueType() != MVT::i64 ||
7944 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7947 // Bitcast an i64 store extracted from a vector to f64.
7948 // Otherwise, the i64 value will be legalized to a pair of i32 values.
7949 SelectionDAG &DAG = DCI.DAG;
7950 DebugLoc dl = StVal.getDebugLoc();
7951 SDValue IntVec = StVal.getOperand(0);
7952 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7953 IntVec.getValueType().getVectorNumElements());
7954 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7955 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7956 Vec, StVal.getOperand(1));
7957 dl = N->getDebugLoc();
7958 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7959 // Make the DAGCombiner fold the bitcasts.
7960 DCI.AddToWorklist(Vec.getNode());
7961 DCI.AddToWorklist(ExtElt.getNode());
7962 DCI.AddToWorklist(V.getNode());
7963 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7964 St->getPointerInfo(), St->isVolatile(),
7965 St->isNonTemporal(), St->getAlignment(),
7969 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7970 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
7971 /// i64 vector to have f64 elements, since the value can then be loaded
7972 /// directly into a VFP register.
7973 static bool hasNormalLoadOperand(SDNode *N) {
7974 unsigned NumElts = N->getValueType(0).getVectorNumElements();
7975 for (unsigned i = 0; i < NumElts; ++i) {
7976 SDNode *Elt = N->getOperand(i).getNode();
7977 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7983 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7984 /// ISD::BUILD_VECTOR.
7985 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7986 TargetLowering::DAGCombinerInfo &DCI){
7987 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7988 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
7989 // into a pair of GPRs, which is fine when the value is used as a scalar,
7990 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7991 SelectionDAG &DAG = DCI.DAG;
7992 if (N->getNumOperands() == 2) {
7993 SDValue RV = PerformVMOVDRRCombine(N, DAG);
7998 // Load i64 elements as f64 values so that type legalization does not split
7999 // them up into i32 values.
8000 EVT VT = N->getValueType(0);
8001 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8003 DebugLoc dl = N->getDebugLoc();
8004 SmallVector<SDValue, 8> Ops;
8005 unsigned NumElts = VT.getVectorNumElements();
8006 for (unsigned i = 0; i < NumElts; ++i) {
8007 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8009 // Make the DAGCombiner fold the bitcast.
8010 DCI.AddToWorklist(V.getNode());
8012 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8013 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8014 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8017 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8018 /// ISD::INSERT_VECTOR_ELT.
8019 static SDValue PerformInsertEltCombine(SDNode *N,
8020 TargetLowering::DAGCombinerInfo &DCI) {
8021 // Bitcast an i64 load inserted into a vector to f64.
8022 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8023 EVT VT = N->getValueType(0);
8024 SDNode *Elt = N->getOperand(1).getNode();
8025 if (VT.getVectorElementType() != MVT::i64 ||
8026 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8029 SelectionDAG &DAG = DCI.DAG;
8030 DebugLoc dl = N->getDebugLoc();
8031 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8032 VT.getVectorNumElements());
8033 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8034 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8035 // Make the DAGCombiner fold the bitcasts.
8036 DCI.AddToWorklist(Vec.getNode());
8037 DCI.AddToWorklist(V.getNode());
8038 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8039 Vec, V, N->getOperand(2));
8040 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8043 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8044 /// ISD::VECTOR_SHUFFLE.
8045 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8046 // The LLVM shufflevector instruction does not require the shuffle mask
8047 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8048 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8049 // operands do not match the mask length, they are extended by concatenating
8050 // them with undef vectors. That is probably the right thing for other
8051 // targets, but for NEON it is better to concatenate two double-register
8052 // size vector operands into a single quad-register size vector. Do that
8053 // transformation here:
8054 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8055 // shuffle(concat(v1, v2), undef)
8056 SDValue Op0 = N->getOperand(0);
8057 SDValue Op1 = N->getOperand(1);
8058 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8059 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8060 Op0.getNumOperands() != 2 ||
8061 Op1.getNumOperands() != 2)
8063 SDValue Concat0Op1 = Op0.getOperand(1);
8064 SDValue Concat1Op1 = Op1.getOperand(1);
8065 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8066 Concat1Op1.getOpcode() != ISD::UNDEF)
8068 // Skip the transformation if any of the types are illegal.
8069 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8070 EVT VT = N->getValueType(0);
8071 if (!TLI.isTypeLegal(VT) ||
8072 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8073 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8076 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8077 Op0.getOperand(0), Op1.getOperand(0));
8078 // Translate the shuffle mask.
8079 SmallVector<int, 16> NewMask;
8080 unsigned NumElts = VT.getVectorNumElements();
8081 unsigned HalfElts = NumElts/2;
8082 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8083 for (unsigned n = 0; n < NumElts; ++n) {
8084 int MaskElt = SVN->getMaskElt(n);
8086 if (MaskElt < (int)HalfElts)
8088 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8089 NewElt = HalfElts + MaskElt - NumElts;
8090 NewMask.push_back(NewElt);
8092 return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8093 DAG.getUNDEF(VT), NewMask.data());
8096 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8097 /// NEON load/store intrinsics to merge base address updates.
8098 static SDValue CombineBaseUpdate(SDNode *N,
8099 TargetLowering::DAGCombinerInfo &DCI) {
8100 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8103 SelectionDAG &DAG = DCI.DAG;
8104 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8105 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8106 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8107 SDValue Addr = N->getOperand(AddrOpIdx);
8109 // Search for a use of the address operand that is an increment.
8110 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8111 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8113 if (User->getOpcode() != ISD::ADD ||
8114 UI.getUse().getResNo() != Addr.getResNo())
8117 // Check that the add is independent of the load/store. Otherwise, folding
8118 // it would create a cycle.
8119 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8122 // Find the new opcode for the updating load/store.
8124 bool isLaneOp = false;
8125 unsigned NewOpc = 0;
8126 unsigned NumVecs = 0;
8128 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8130 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8131 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8133 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8135 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8137 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8139 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8140 NumVecs = 2; isLaneOp = true; break;
8141 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8142 NumVecs = 3; isLaneOp = true; break;
8143 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8144 NumVecs = 4; isLaneOp = true; break;
8145 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8146 NumVecs = 1; isLoad = false; break;
8147 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8148 NumVecs = 2; isLoad = false; break;
8149 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8150 NumVecs = 3; isLoad = false; break;
8151 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8152 NumVecs = 4; isLoad = false; break;
8153 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8154 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8155 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8156 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8157 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8158 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8162 switch (N->getOpcode()) {
8163 default: llvm_unreachable("unexpected opcode for Neon base update");
8164 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8165 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8166 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8170 // Find the size of memory referenced by the load/store.
8173 VecTy = N->getValueType(0);
8175 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8176 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8178 NumBytes /= VecTy.getVectorNumElements();
8180 // If the increment is a constant, it must match the memory ref size.
8181 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8182 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8183 uint64_t IncVal = CInc->getZExtValue();
8184 if (IncVal != NumBytes)
8186 } else if (NumBytes >= 3 * 16) {
8187 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8188 // separate instructions that make it harder to use a non-constant update.
8192 // Create the new updating load/store node.
8194 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8196 for (n = 0; n < NumResultVecs; ++n)
8198 Tys[n++] = MVT::i32;
8199 Tys[n] = MVT::Other;
8200 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8201 SmallVector<SDValue, 8> Ops;
8202 Ops.push_back(N->getOperand(0)); // incoming chain
8203 Ops.push_back(N->getOperand(AddrOpIdx));
8205 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8206 Ops.push_back(N->getOperand(i));
8208 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8209 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8210 Ops.data(), Ops.size(),
8211 MemInt->getMemoryVT(),
8212 MemInt->getMemOperand());
8215 std::vector<SDValue> NewResults;
8216 for (unsigned i = 0; i < NumResultVecs; ++i) {
8217 NewResults.push_back(SDValue(UpdN.getNode(), i));
8219 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8220 DCI.CombineTo(N, NewResults);
8221 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8228 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8229 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8230 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8232 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8233 SelectionDAG &DAG = DCI.DAG;
8234 EVT VT = N->getValueType(0);
8235 // vldN-dup instructions only support 64-bit vectors for N > 1.
8236 if (!VT.is64BitVector())
8239 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8240 SDNode *VLD = N->getOperand(0).getNode();
8241 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8243 unsigned NumVecs = 0;
8244 unsigned NewOpc = 0;
8245 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8246 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8248 NewOpc = ARMISD::VLD2DUP;
8249 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8251 NewOpc = ARMISD::VLD3DUP;
8252 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8254 NewOpc = ARMISD::VLD4DUP;
8259 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8260 // numbers match the load.
8261 unsigned VLDLaneNo =
8262 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8263 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8265 // Ignore uses of the chain result.
8266 if (UI.getUse().getResNo() == NumVecs)
8269 if (User->getOpcode() != ARMISD::VDUPLANE ||
8270 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8274 // Create the vldN-dup node.
8277 for (n = 0; n < NumVecs; ++n)
8279 Tys[n] = MVT::Other;
8280 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8281 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8282 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8283 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8284 Ops, 2, VLDMemInt->getMemoryVT(),
8285 VLDMemInt->getMemOperand());
8288 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8290 unsigned ResNo = UI.getUse().getResNo();
8291 // Ignore uses of the chain result.
8292 if (ResNo == NumVecs)
8295 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8298 // Now the vldN-lane intrinsic is dead except for its chain result.
8299 // Update uses of the chain.
8300 std::vector<SDValue> VLDDupResults;
8301 for (unsigned n = 0; n < NumVecs; ++n)
8302 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8303 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8304 DCI.CombineTo(VLD, VLDDupResults);
8309 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8310 /// ARMISD::VDUPLANE.
8311 static SDValue PerformVDUPLANECombine(SDNode *N,
8312 TargetLowering::DAGCombinerInfo &DCI) {
8313 SDValue Op = N->getOperand(0);
8315 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8316 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8317 if (CombineVLDDUP(N, DCI))
8318 return SDValue(N, 0);
8320 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8321 // redundant. Ignore bit_converts for now; element sizes are checked below.
8322 while (Op.getOpcode() == ISD::BITCAST)
8323 Op = Op.getOperand(0);
8324 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8327 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8328 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8329 // The canonical VMOV for a zero vector uses a 32-bit element size.
8330 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8332 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8334 EVT VT = N->getValueType(0);
8335 if (EltSize > VT.getVectorElementType().getSizeInBits())
8338 return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8341 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8342 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8343 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8347 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8349 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8354 APFloat APF = C->getValueAPF();
8355 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8356 != APFloat::opOK || !isExact)
8359 c0 = (I == 0) ? cN : c0;
8360 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8367 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8368 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8369 /// when the VMUL has a constant operand that is a power of 2.
8371 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8372 /// vmul.f32 d16, d17, d16
8373 /// vcvt.s32.f32 d16, d16
8375 /// vcvt.s32.f32 d16, d16, #3
8376 static SDValue PerformVCVTCombine(SDNode *N,
8377 TargetLowering::DAGCombinerInfo &DCI,
8378 const ARMSubtarget *Subtarget) {
8379 SelectionDAG &DAG = DCI.DAG;
8380 SDValue Op = N->getOperand(0);
8382 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8383 Op.getOpcode() != ISD::FMUL)
8387 SDValue N0 = Op->getOperand(0);
8388 SDValue ConstVec = Op->getOperand(1);
8389 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8391 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8392 !isConstVecPow2(ConstVec, isSigned, C))
8395 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8396 Intrinsic::arm_neon_vcvtfp2fxu;
8397 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8399 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8400 DAG.getConstant(Log2_64(C), MVT::i32));
8403 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8404 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8405 /// when the VDIV has a constant operand that is a power of 2.
8407 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8408 /// vcvt.f32.s32 d16, d16
8409 /// vdiv.f32 d16, d17, d16
8411 /// vcvt.f32.s32 d16, d16, #3
8412 static SDValue PerformVDIVCombine(SDNode *N,
8413 TargetLowering::DAGCombinerInfo &DCI,
8414 const ARMSubtarget *Subtarget) {
8415 SelectionDAG &DAG = DCI.DAG;
8416 SDValue Op = N->getOperand(0);
8417 unsigned OpOpcode = Op.getNode()->getOpcode();
8419 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8420 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8424 SDValue ConstVec = N->getOperand(1);
8425 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8427 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8428 !isConstVecPow2(ConstVec, isSigned, C))
8431 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8432 Intrinsic::arm_neon_vcvtfxu2fp;
8433 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8435 DAG.getConstant(IntrinsicOpcode, MVT::i32),
8436 Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8439 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8440 /// operand of a vector shift operation, where all the elements of the
8441 /// build_vector must have the same constant integer value.
8442 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8443 // Ignore bit_converts.
8444 while (Op.getOpcode() == ISD::BITCAST)
8445 Op = Op.getOperand(0);
8446 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8447 APInt SplatBits, SplatUndef;
8448 unsigned SplatBitSize;
8450 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8451 HasAnyUndefs, ElementBits) ||
8452 SplatBitSize > ElementBits)
8454 Cnt = SplatBits.getSExtValue();
8458 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8459 /// operand of a vector shift left operation. That value must be in the range:
8460 /// 0 <= Value < ElementBits for a left shift; or
8461 /// 0 <= Value <= ElementBits for a long left shift.
8462 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8463 assert(VT.isVector() && "vector shift count is not a vector type");
8464 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8465 if (! getVShiftImm(Op, ElementBits, Cnt))
8467 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8470 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8471 /// operand of a vector shift right operation. For a shift opcode, the value
8472 /// is positive, but for an intrinsic the value count must be negative. The
8473 /// absolute value must be in the range:
8474 /// 1 <= |Value| <= ElementBits for a right shift; or
8475 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8476 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8478 assert(VT.isVector() && "vector shift count is not a vector type");
8479 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8480 if (! getVShiftImm(Op, ElementBits, Cnt))
8484 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8487 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8488 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8489 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8492 // Don't do anything for most intrinsics.
8495 // Vector shifts: check for immediate versions and lower them.
8496 // Note: This is done during DAG combining instead of DAG legalizing because
8497 // the build_vectors for 64-bit vector element shift counts are generally
8498 // not legal, and it is hard to see their values after they get legalized to
8499 // loads from a constant pool.
8500 case Intrinsic::arm_neon_vshifts:
8501 case Intrinsic::arm_neon_vshiftu:
8502 case Intrinsic::arm_neon_vshiftls:
8503 case Intrinsic::arm_neon_vshiftlu:
8504 case Intrinsic::arm_neon_vshiftn:
8505 case Intrinsic::arm_neon_vrshifts:
8506 case Intrinsic::arm_neon_vrshiftu:
8507 case Intrinsic::arm_neon_vrshiftn:
8508 case Intrinsic::arm_neon_vqshifts:
8509 case Intrinsic::arm_neon_vqshiftu:
8510 case Intrinsic::arm_neon_vqshiftsu:
8511 case Intrinsic::arm_neon_vqshiftns:
8512 case Intrinsic::arm_neon_vqshiftnu:
8513 case Intrinsic::arm_neon_vqshiftnsu:
8514 case Intrinsic::arm_neon_vqrshiftns:
8515 case Intrinsic::arm_neon_vqrshiftnu:
8516 case Intrinsic::arm_neon_vqrshiftnsu: {
8517 EVT VT = N->getOperand(1).getValueType();
8519 unsigned VShiftOpc = 0;
8522 case Intrinsic::arm_neon_vshifts:
8523 case Intrinsic::arm_neon_vshiftu:
8524 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8525 VShiftOpc = ARMISD::VSHL;
8528 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8529 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8530 ARMISD::VSHRs : ARMISD::VSHRu);
8535 case Intrinsic::arm_neon_vshiftls:
8536 case Intrinsic::arm_neon_vshiftlu:
8537 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8539 llvm_unreachable("invalid shift count for vshll intrinsic");
8541 case Intrinsic::arm_neon_vrshifts:
8542 case Intrinsic::arm_neon_vrshiftu:
8543 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8547 case Intrinsic::arm_neon_vqshifts:
8548 case Intrinsic::arm_neon_vqshiftu:
8549 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8553 case Intrinsic::arm_neon_vqshiftsu:
8554 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8556 llvm_unreachable("invalid shift count for vqshlu intrinsic");
8558 case Intrinsic::arm_neon_vshiftn:
8559 case Intrinsic::arm_neon_vrshiftn:
8560 case Intrinsic::arm_neon_vqshiftns:
8561 case Intrinsic::arm_neon_vqshiftnu:
8562 case Intrinsic::arm_neon_vqshiftnsu:
8563 case Intrinsic::arm_neon_vqrshiftns:
8564 case Intrinsic::arm_neon_vqrshiftnu:
8565 case Intrinsic::arm_neon_vqrshiftnsu:
8566 // Narrowing shifts require an immediate right shift.
8567 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
8569 llvm_unreachable("invalid shift count for narrowing vector shift "
8573 llvm_unreachable("unhandled vector shift");
8577 case Intrinsic::arm_neon_vshifts:
8578 case Intrinsic::arm_neon_vshiftu:
8579 // Opcode already set above.
8581 case Intrinsic::arm_neon_vshiftls:
8582 case Intrinsic::arm_neon_vshiftlu:
8583 if (Cnt == VT.getVectorElementType().getSizeInBits())
8584 VShiftOpc = ARMISD::VSHLLi;
8586 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
8587 ARMISD::VSHLLs : ARMISD::VSHLLu);
8589 case Intrinsic::arm_neon_vshiftn:
8590 VShiftOpc = ARMISD::VSHRN; break;
8591 case Intrinsic::arm_neon_vrshifts:
8592 VShiftOpc = ARMISD::VRSHRs; break;
8593 case Intrinsic::arm_neon_vrshiftu:
8594 VShiftOpc = ARMISD::VRSHRu; break;
8595 case Intrinsic::arm_neon_vrshiftn:
8596 VShiftOpc = ARMISD::VRSHRN; break;
8597 case Intrinsic::arm_neon_vqshifts:
8598 VShiftOpc = ARMISD::VQSHLs; break;
8599 case Intrinsic::arm_neon_vqshiftu:
8600 VShiftOpc = ARMISD::VQSHLu; break;
8601 case Intrinsic::arm_neon_vqshiftsu:
8602 VShiftOpc = ARMISD::VQSHLsu; break;
8603 case Intrinsic::arm_neon_vqshiftns:
8604 VShiftOpc = ARMISD::VQSHRNs; break;
8605 case Intrinsic::arm_neon_vqshiftnu:
8606 VShiftOpc = ARMISD::VQSHRNu; break;
8607 case Intrinsic::arm_neon_vqshiftnsu:
8608 VShiftOpc = ARMISD::VQSHRNsu; break;
8609 case Intrinsic::arm_neon_vqrshiftns:
8610 VShiftOpc = ARMISD::VQRSHRNs; break;
8611 case Intrinsic::arm_neon_vqrshiftnu:
8612 VShiftOpc = ARMISD::VQRSHRNu; break;
8613 case Intrinsic::arm_neon_vqrshiftnsu:
8614 VShiftOpc = ARMISD::VQRSHRNsu; break;
8617 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8618 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
8621 case Intrinsic::arm_neon_vshiftins: {
8622 EVT VT = N->getOperand(1).getValueType();
8624 unsigned VShiftOpc = 0;
8626 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
8627 VShiftOpc = ARMISD::VSLI;
8628 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
8629 VShiftOpc = ARMISD::VSRI;
8631 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
8634 return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
8635 N->getOperand(1), N->getOperand(2),
8636 DAG.getConstant(Cnt, MVT::i32));
8639 case Intrinsic::arm_neon_vqrshifts:
8640 case Intrinsic::arm_neon_vqrshiftu:
8641 // No immediate versions of these to check for.
8648 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
8649 /// lowers them. As with the vector shift intrinsics, this is done during DAG
8650 /// combining instead of DAG legalizing because the build_vectors for 64-bit
8651 /// vector element shift counts are generally not legal, and it is hard to see
8652 /// their values after they get legalized to loads from a constant pool.
8653 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
8654 const ARMSubtarget *ST) {
8655 EVT VT = N->getValueType(0);
8656 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
8657 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
8658 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
8659 SDValue N1 = N->getOperand(1);
8660 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8661 SDValue N0 = N->getOperand(0);
8662 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
8663 DAG.MaskedValueIsZero(N0.getOperand(0),
8664 APInt::getHighBitsSet(32, 16)))
8665 return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8669 // Nothing to be done for scalar shifts.
8670 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8671 if (!VT.isVector() || !TLI.isTypeLegal(VT))
8674 assert(ST->hasNEON() && "unexpected vector shift");
8677 switch (N->getOpcode()) {
8678 default: llvm_unreachable("unexpected shift opcode");
8681 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8682 return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8683 DAG.getConstant(Cnt, MVT::i32));
8688 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8689 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8690 ARMISD::VSHRs : ARMISD::VSHRu);
8691 return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8692 DAG.getConstant(Cnt, MVT::i32));
8698 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8699 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8700 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8701 const ARMSubtarget *ST) {
8702 SDValue N0 = N->getOperand(0);
8704 // Check for sign- and zero-extensions of vector extract operations of 8-
8705 // and 16-bit vector elements. NEON supports these directly. They are
8706 // handled during DAG combining because type legalization will promote them
8707 // to 32-bit types and it is messy to recognize the operations after that.
8708 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8709 SDValue Vec = N0.getOperand(0);
8710 SDValue Lane = N0.getOperand(1);
8711 EVT VT = N->getValueType(0);
8712 EVT EltVT = N0.getValueType();
8713 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8715 if (VT == MVT::i32 &&
8716 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8717 TLI.isTypeLegal(Vec.getValueType()) &&
8718 isa<ConstantSDNode>(Lane)) {
8721 switch (N->getOpcode()) {
8722 default: llvm_unreachable("unexpected opcode");
8723 case ISD::SIGN_EXTEND:
8724 Opc = ARMISD::VGETLANEs;
8726 case ISD::ZERO_EXTEND:
8727 case ISD::ANY_EXTEND:
8728 Opc = ARMISD::VGETLANEu;
8731 return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8738 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8739 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8740 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8741 const ARMSubtarget *ST) {
8742 // If the target supports NEON, try to use vmax/vmin instructions for f32
8743 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
8744 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
8745 // a NaN; only do the transformation when it matches that behavior.
8747 // For now only do this when using NEON for FP operations; if using VFP, it
8748 // is not obvious that the benefit outweighs the cost of switching to the
8750 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8751 N->getValueType(0) != MVT::f32)
8754 SDValue CondLHS = N->getOperand(0);
8755 SDValue CondRHS = N->getOperand(1);
8756 SDValue LHS = N->getOperand(2);
8757 SDValue RHS = N->getOperand(3);
8758 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8760 unsigned Opcode = 0;
8762 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8763 IsReversed = false; // x CC y ? x : y
8764 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8765 IsReversed = true ; // x CC y ? y : x
8779 // If LHS is NaN, an ordered comparison will be false and the result will
8780 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
8781 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8782 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8783 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8785 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8786 // will return -0, so vmin can only be used for unsafe math or if one of
8787 // the operands is known to be nonzero.
8788 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8789 !DAG.getTarget().Options.UnsafeFPMath &&
8790 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8792 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8801 // If LHS is NaN, an ordered comparison will be false and the result will
8802 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
8803 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
8804 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8805 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8807 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8808 // will return +0, so vmax can only be used for unsafe math or if one of
8809 // the operands is known to be nonzero.
8810 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8811 !DAG.getTarget().Options.UnsafeFPMath &&
8812 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8814 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8820 return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8823 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8825 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8826 SDValue Cmp = N->getOperand(4);
8827 if (Cmp.getOpcode() != ARMISD::CMPZ)
8828 // Only looking at EQ and NE cases.
8831 EVT VT = N->getValueType(0);
8832 DebugLoc dl = N->getDebugLoc();
8833 SDValue LHS = Cmp.getOperand(0);
8834 SDValue RHS = Cmp.getOperand(1);
8835 SDValue FalseVal = N->getOperand(0);
8836 SDValue TrueVal = N->getOperand(1);
8837 SDValue ARMcc = N->getOperand(2);
8838 ARMCC::CondCodes CC =
8839 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8857 /// FIXME: Turn this into a target neutral optimization?
8859 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8860 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8861 N->getOperand(3), Cmp);
8862 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8864 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8865 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8866 N->getOperand(3), NewCmp);
8869 if (Res.getNode()) {
8870 APInt KnownZero, KnownOne;
8871 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
8872 // Capture demanded bits information that would be otherwise lost.
8873 if (KnownZero == 0xfffffffe)
8874 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8875 DAG.getValueType(MVT::i1));
8876 else if (KnownZero == 0xffffff00)
8877 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8878 DAG.getValueType(MVT::i8));
8879 else if (KnownZero == 0xffff0000)
8880 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8881 DAG.getValueType(MVT::i16));
8887 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8888 DAGCombinerInfo &DCI) const {
8889 switch (N->getOpcode()) {
8891 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
8892 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
8893 case ISD::SUB: return PerformSUBCombine(N, DCI);
8894 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
8895 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
8896 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
8897 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
8898 case ARMISD::BFI: return PerformBFICombine(N, DCI);
8899 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8900 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8901 case ISD::STORE: return PerformSTORECombine(N, DCI);
8902 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8903 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8904 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8905 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8906 case ISD::FP_TO_SINT:
8907 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8908 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
8909 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8912 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
8913 case ISD::SIGN_EXTEND:
8914 case ISD::ZERO_EXTEND:
8915 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8916 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8917 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8918 case ARMISD::VLD2DUP:
8919 case ARMISD::VLD3DUP:
8920 case ARMISD::VLD4DUP:
8921 return CombineBaseUpdate(N, DCI);
8922 case ISD::INTRINSIC_VOID:
8923 case ISD::INTRINSIC_W_CHAIN:
8924 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8925 case Intrinsic::arm_neon_vld1:
8926 case Intrinsic::arm_neon_vld2:
8927 case Intrinsic::arm_neon_vld3:
8928 case Intrinsic::arm_neon_vld4:
8929 case Intrinsic::arm_neon_vld2lane:
8930 case Intrinsic::arm_neon_vld3lane:
8931 case Intrinsic::arm_neon_vld4lane:
8932 case Intrinsic::arm_neon_vst1:
8933 case Intrinsic::arm_neon_vst2:
8934 case Intrinsic::arm_neon_vst3:
8935 case Intrinsic::arm_neon_vst4:
8936 case Intrinsic::arm_neon_vst2lane:
8937 case Intrinsic::arm_neon_vst3lane:
8938 case Intrinsic::arm_neon_vst4lane:
8939 return CombineBaseUpdate(N, DCI);
8947 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8949 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8952 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8953 if (!Subtarget->allowsUnalignedMem())
8956 switch (VT.getSimpleVT().SimpleTy) {
8963 // FIXME: VLD1 etc with standard alignment is legal.
8967 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8968 unsigned AlignCheck) {
8969 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8970 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8973 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8974 unsigned DstAlign, unsigned SrcAlign,
8977 MachineFunction &MF) const {
8978 const Function *F = MF.getFunction();
8980 // See if we can use NEON instructions for this...
8982 !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8983 Subtarget->hasNEON()) {
8984 if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8986 } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8991 // Lowering to i32/i16 if the size permits.
8994 } else if (Size >= 2) {
8998 // Let the target-independent logic figure it out.
9002 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9007 switch (VT.getSimpleVT().SimpleTy) {
9008 default: return false;
9023 if ((V & (Scale - 1)) != 0)
9026 return V == (V & ((1LL << 5) - 1));
9029 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9030 const ARMSubtarget *Subtarget) {
9037 switch (VT.getSimpleVT().SimpleTy) {
9038 default: return false;
9043 // + imm12 or - imm8
9045 return V == (V & ((1LL << 8) - 1));
9046 return V == (V & ((1LL << 12) - 1));
9049 // Same as ARM mode. FIXME: NEON?
9050 if (!Subtarget->hasVFP2())
9055 return V == (V & ((1LL << 8) - 1));
9059 /// isLegalAddressImmediate - Return true if the integer value can be used
9060 /// as the offset of the target addressing mode for load / store of the
9062 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9063 const ARMSubtarget *Subtarget) {
9070 if (Subtarget->isThumb1Only())
9071 return isLegalT1AddressImmediate(V, VT);
9072 else if (Subtarget->isThumb2())
9073 return isLegalT2AddressImmediate(V, VT, Subtarget);
9078 switch (VT.getSimpleVT().SimpleTy) {
9079 default: return false;
9084 return V == (V & ((1LL << 12) - 1));
9087 return V == (V & ((1LL << 8) - 1));
9090 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9095 return V == (V & ((1LL << 8) - 1));
9099 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9101 int Scale = AM.Scale;
9105 switch (VT.getSimpleVT().SimpleTy) {
9106 default: return false;
9115 return Scale == 2 || Scale == 4 || Scale == 8;
9118 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9122 // Note, we allow "void" uses (basically, uses that aren't loads or
9123 // stores), because arm allows folding a scale into many arithmetic
9124 // operations. This should be made more precise and revisited later.
9126 // Allow r << imm, but the imm has to be a multiple of two.
9127 if (Scale & 1) return false;
9128 return isPowerOf2_32(Scale);
9132 /// isLegalAddressingMode - Return true if the addressing mode represented
9133 /// by AM is legal for this target, for a load/store of the specified type.
9134 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9136 EVT VT = getValueType(Ty, true);
9137 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9140 // Can never fold addr of global into load/store.
9145 case 0: // no scale reg, must be "r+i" or "r", or "i".
9148 if (Subtarget->isThumb1Only())
9152 // ARM doesn't support any R+R*scale+imm addr modes.
9159 if (Subtarget->isThumb2())
9160 return isLegalT2ScaledAddressingMode(AM, VT);
9162 int Scale = AM.Scale;
9163 switch (VT.getSimpleVT().SimpleTy) {
9164 default: return false;
9168 if (Scale < 0) Scale = -Scale;
9172 return isPowerOf2_32(Scale & ~1);
9176 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9181 // Note, we allow "void" uses (basically, uses that aren't loads or
9182 // stores), because arm allows folding a scale into many arithmetic
9183 // operations. This should be made more precise and revisited later.
9185 // Allow r << imm, but the imm has to be a multiple of two.
9186 if (Scale & 1) return false;
9187 return isPowerOf2_32(Scale);
9193 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9194 /// icmp immediate, that is the target has icmp instructions which can compare
9195 /// a register against the immediate without having to materialize the
9196 /// immediate into a register.
9197 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9198 // Thumb2 and ARM modes can use cmn for negative immediates.
9199 if (!Subtarget->isThumb())
9200 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9201 if (Subtarget->isThumb2())
9202 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9203 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9204 return Imm >= 0 && Imm <= 255;
9207 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9208 /// *or sub* immediate, that is the target has add or sub instructions which can
9209 /// add a register with the immediate without having to materialize the
9210 /// immediate into a register.
9211 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9212 // Same encoding for add/sub, just flip the sign.
9213 int64_t AbsImm = llvm::abs64(Imm);
9214 if (!Subtarget->isThumb())
9215 return ARM_AM::getSOImmVal(AbsImm) != -1;
9216 if (Subtarget->isThumb2())
9217 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9218 // Thumb1 only has 8-bit unsigned immediate.
9219 return AbsImm >= 0 && AbsImm <= 255;
9222 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9223 bool isSEXTLoad, SDValue &Base,
9224 SDValue &Offset, bool &isInc,
9225 SelectionDAG &DAG) {
9226 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9229 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9231 Base = Ptr->getOperand(0);
9232 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9233 int RHSC = (int)RHS->getZExtValue();
9234 if (RHSC < 0 && RHSC > -256) {
9235 assert(Ptr->getOpcode() == ISD::ADD);
9237 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9241 isInc = (Ptr->getOpcode() == ISD::ADD);
9242 Offset = Ptr->getOperand(1);
9244 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9246 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9247 int RHSC = (int)RHS->getZExtValue();
9248 if (RHSC < 0 && RHSC > -0x1000) {
9249 assert(Ptr->getOpcode() == ISD::ADD);
9251 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9252 Base = Ptr->getOperand(0);
9257 if (Ptr->getOpcode() == ISD::ADD) {
9259 ARM_AM::ShiftOpc ShOpcVal=
9260 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9261 if (ShOpcVal != ARM_AM::no_shift) {
9262 Base = Ptr->getOperand(1);
9263 Offset = Ptr->getOperand(0);
9265 Base = Ptr->getOperand(0);
9266 Offset = Ptr->getOperand(1);
9271 isInc = (Ptr->getOpcode() == ISD::ADD);
9272 Base = Ptr->getOperand(0);
9273 Offset = Ptr->getOperand(1);
9277 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9281 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9282 bool isSEXTLoad, SDValue &Base,
9283 SDValue &Offset, bool &isInc,
9284 SelectionDAG &DAG) {
9285 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9288 Base = Ptr->getOperand(0);
9289 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9290 int RHSC = (int)RHS->getZExtValue();
9291 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9292 assert(Ptr->getOpcode() == ISD::ADD);
9294 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9296 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9297 isInc = Ptr->getOpcode() == ISD::ADD;
9298 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9306 /// getPreIndexedAddressParts - returns true by value, base pointer and
9307 /// offset pointer and addressing mode by reference if the node's address
9308 /// can be legally represented as pre-indexed load / store address.
9310 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9312 ISD::MemIndexedMode &AM,
9313 SelectionDAG &DAG) const {
9314 if (Subtarget->isThumb1Only())
9319 bool isSEXTLoad = false;
9320 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9321 Ptr = LD->getBasePtr();
9322 VT = LD->getMemoryVT();
9323 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9324 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9325 Ptr = ST->getBasePtr();
9326 VT = ST->getMemoryVT();
9331 bool isLegal = false;
9332 if (Subtarget->isThumb2())
9333 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9334 Offset, isInc, DAG);
9336 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9337 Offset, isInc, DAG);
9341 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9345 /// getPostIndexedAddressParts - returns true by value, base pointer and
9346 /// offset pointer and addressing mode by reference if this node can be
9347 /// combined with a load / store to form a post-indexed load / store.
9348 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9351 ISD::MemIndexedMode &AM,
9352 SelectionDAG &DAG) const {
9353 if (Subtarget->isThumb1Only())
9358 bool isSEXTLoad = false;
9359 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9360 VT = LD->getMemoryVT();
9361 Ptr = LD->getBasePtr();
9362 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9363 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9364 VT = ST->getMemoryVT();
9365 Ptr = ST->getBasePtr();
9370 bool isLegal = false;
9371 if (Subtarget->isThumb2())
9372 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9375 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9381 // Swap base ptr and offset to catch more post-index load / store when
9382 // it's legal. In Thumb2 mode, offset must be an immediate.
9383 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9384 !Subtarget->isThumb2())
9385 std::swap(Base, Offset);
9387 // Post-indexed load / store update the base pointer.
9392 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9396 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9399 const SelectionDAG &DAG,
9400 unsigned Depth) const {
9401 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9402 switch (Op.getOpcode()) {
9404 case ARMISD::CMOV: {
9405 // Bits are known zero/one if known on the LHS and RHS.
9406 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9407 if (KnownZero == 0 && KnownOne == 0) return;
9409 APInt KnownZeroRHS, KnownOneRHS;
9410 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9411 KnownZero &= KnownZeroRHS;
9412 KnownOne &= KnownOneRHS;
9418 //===----------------------------------------------------------------------===//
9419 // ARM Inline Assembly Support
9420 //===----------------------------------------------------------------------===//
9422 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9423 // Looking for "rev" which is V6+.
9424 if (!Subtarget->hasV6Ops())
9427 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9428 std::string AsmStr = IA->getAsmString();
9429 SmallVector<StringRef, 4> AsmPieces;
9430 SplitString(AsmStr, AsmPieces, ";\n");
9432 switch (AsmPieces.size()) {
9433 default: return false;
9435 AsmStr = AsmPieces[0];
9437 SplitString(AsmStr, AsmPieces, " \t,");
9440 if (AsmPieces.size() == 3 &&
9441 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9442 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9443 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9444 if (Ty && Ty->getBitWidth() == 32)
9445 return IntrinsicLowering::LowerToByteSwap(CI);
9453 /// getConstraintType - Given a constraint letter, return the type of
9454 /// constraint it is for this target.
9455 ARMTargetLowering::ConstraintType
9456 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9457 if (Constraint.size() == 1) {
9458 switch (Constraint[0]) {
9460 case 'l': return C_RegisterClass;
9461 case 'w': return C_RegisterClass;
9462 case 'h': return C_RegisterClass;
9463 case 'x': return C_RegisterClass;
9464 case 't': return C_RegisterClass;
9465 case 'j': return C_Other; // Constant for movw.
9466 // An address with a single base register. Due to the way we
9467 // currently handle addresses it is the same as an 'r' memory constraint.
9468 case 'Q': return C_Memory;
9470 } else if (Constraint.size() == 2) {
9471 switch (Constraint[0]) {
9473 // All 'U+' constraints are addresses.
9474 case 'U': return C_Memory;
9477 return TargetLowering::getConstraintType(Constraint);
9480 /// Examine constraint type and operand type and determine a weight value.
9481 /// This object must already have been set up with the operand type
9482 /// and the current alternative constraint selected.
9483 TargetLowering::ConstraintWeight
9484 ARMTargetLowering::getSingleConstraintMatchWeight(
9485 AsmOperandInfo &info, const char *constraint) const {
9486 ConstraintWeight weight = CW_Invalid;
9487 Value *CallOperandVal = info.CallOperandVal;
9488 // If we don't have a value, we can't do a match,
9489 // but allow it at the lowest weight.
9490 if (CallOperandVal == NULL)
9492 Type *type = CallOperandVal->getType();
9493 // Look at the constraint type.
9494 switch (*constraint) {
9496 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9499 if (type->isIntegerTy()) {
9500 if (Subtarget->isThumb())
9501 weight = CW_SpecificReg;
9503 weight = CW_Register;
9507 if (type->isFloatingPointTy())
9508 weight = CW_Register;
9514 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9516 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9518 if (Constraint.size() == 1) {
9519 // GCC ARM Constraint Letters
9520 switch (Constraint[0]) {
9521 case 'l': // Low regs or general regs.
9522 if (Subtarget->isThumb())
9523 return RCPair(0U, &ARM::tGPRRegClass);
9524 return RCPair(0U, &ARM::GPRRegClass);
9525 case 'h': // High regs or no regs.
9526 if (Subtarget->isThumb())
9527 return RCPair(0U, &ARM::hGPRRegClass);
9530 return RCPair(0U, &ARM::GPRRegClass);
9533 return RCPair(0U, &ARM::SPRRegClass);
9534 if (VT.getSizeInBits() == 64)
9535 return RCPair(0U, &ARM::DPRRegClass);
9536 if (VT.getSizeInBits() == 128)
9537 return RCPair(0U, &ARM::QPRRegClass);
9541 return RCPair(0U, &ARM::SPR_8RegClass);
9542 if (VT.getSizeInBits() == 64)
9543 return RCPair(0U, &ARM::DPR_8RegClass);
9544 if (VT.getSizeInBits() == 128)
9545 return RCPair(0U, &ARM::QPR_8RegClass);
9549 return RCPair(0U, &ARM::SPRRegClass);
9553 if (StringRef("{cc}").equals_lower(Constraint))
9554 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
9556 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9559 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9560 /// vector. If it is invalid, don't add anything to Ops.
9561 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9562 std::string &Constraint,
9563 std::vector<SDValue>&Ops,
9564 SelectionDAG &DAG) const {
9565 SDValue Result(0, 0);
9567 // Currently only support length 1 constraints.
9568 if (Constraint.length() != 1) return;
9570 char ConstraintLetter = Constraint[0];
9571 switch (ConstraintLetter) {
9574 case 'I': case 'J': case 'K': case 'L':
9575 case 'M': case 'N': case 'O':
9576 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
9580 int64_t CVal64 = C->getSExtValue();
9581 int CVal = (int) CVal64;
9582 // None of these constraints allow values larger than 32 bits. Check
9583 // that the value fits in an int.
9587 switch (ConstraintLetter) {
9589 // Constant suitable for movw, must be between 0 and
9591 if (Subtarget->hasV6T2Ops())
9592 if (CVal >= 0 && CVal <= 65535)
9596 if (Subtarget->isThumb1Only()) {
9597 // This must be a constant between 0 and 255, for ADD
9599 if (CVal >= 0 && CVal <= 255)
9601 } else if (Subtarget->isThumb2()) {
9602 // A constant that can be used as an immediate value in a
9603 // data-processing instruction.
9604 if (ARM_AM::getT2SOImmVal(CVal) != -1)
9607 // A constant that can be used as an immediate value in a
9608 // data-processing instruction.
9609 if (ARM_AM::getSOImmVal(CVal) != -1)
9615 if (Subtarget->isThumb()) { // FIXME thumb2
9616 // This must be a constant between -255 and -1, for negated ADD
9617 // immediates. This can be used in GCC with an "n" modifier that
9618 // prints the negated value, for use with SUB instructions. It is
9619 // not useful otherwise but is implemented for compatibility.
9620 if (CVal >= -255 && CVal <= -1)
9623 // This must be a constant between -4095 and 4095. It is not clear
9624 // what this constraint is intended for. Implemented for
9625 // compatibility with GCC.
9626 if (CVal >= -4095 && CVal <= 4095)
9632 if (Subtarget->isThumb1Only()) {
9633 // A 32-bit value where only one byte has a nonzero value. Exclude
9634 // zero to match GCC. This constraint is used by GCC internally for
9635 // constants that can be loaded with a move/shift combination.
9636 // It is not useful otherwise but is implemented for compatibility.
9637 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
9639 } else if (Subtarget->isThumb2()) {
9640 // A constant whose bitwise inverse can be used as an immediate
9641 // value in a data-processing instruction. This can be used in GCC
9642 // with a "B" modifier that prints the inverted value, for use with
9643 // BIC and MVN instructions. It is not useful otherwise but is
9644 // implemented for compatibility.
9645 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
9648 // A constant whose bitwise inverse can be used as an immediate
9649 // value in a data-processing instruction. This can be used in GCC
9650 // with a "B" modifier that prints the inverted value, for use with
9651 // BIC and MVN instructions. It is not useful otherwise but is
9652 // implemented for compatibility.
9653 if (ARM_AM::getSOImmVal(~CVal) != -1)
9659 if (Subtarget->isThumb1Only()) {
9660 // This must be a constant between -7 and 7,
9661 // for 3-operand ADD/SUB immediate instructions.
9662 if (CVal >= -7 && CVal < 7)
9664 } else if (Subtarget->isThumb2()) {
9665 // A constant whose negation can be used as an immediate value in a
9666 // data-processing instruction. This can be used in GCC with an "n"
9667 // modifier that prints the negated value, for use with SUB
9668 // instructions. It is not useful otherwise but is implemented for
9670 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
9673 // A constant whose negation can be used as an immediate value in a
9674 // data-processing instruction. This can be used in GCC with an "n"
9675 // modifier that prints the negated value, for use with SUB
9676 // instructions. It is not useful otherwise but is implemented for
9678 if (ARM_AM::getSOImmVal(-CVal) != -1)
9684 if (Subtarget->isThumb()) { // FIXME thumb2
9685 // This must be a multiple of 4 between 0 and 1020, for
9686 // ADD sp + immediate.
9687 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9690 // A power of two or a constant between 0 and 32. This is used in
9691 // GCC for the shift amount on shifted register operands, but it is
9692 // useful in general for any shift amounts.
9693 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9699 if (Subtarget->isThumb()) { // FIXME thumb2
9700 // This must be a constant between 0 and 31, for shift amounts.
9701 if (CVal >= 0 && CVal <= 31)
9707 if (Subtarget->isThumb()) { // FIXME thumb2
9708 // This must be a multiple of 4 between -508 and 508, for
9709 // ADD/SUB sp = sp + immediate.
9710 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9715 Result = DAG.getTargetConstant(CVal, Op.getValueType());
9719 if (Result.getNode()) {
9720 Ops.push_back(Result);
9723 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9727 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9728 // The ARM target isn't yet aware of offsets.
9732 bool ARM::isBitFieldInvertedMask(unsigned v) {
9733 if (v == 0xffffffff)
9735 // there can be 1's on either or both "outsides", all the "inside"
9737 unsigned int lsb = 0, msb = 31;
9738 while (v & (1 << msb)) --msb;
9739 while (v & (1 << lsb)) ++lsb;
9740 for (unsigned int i = lsb; i <= msb; ++i) {
9747 /// isFPImmLegal - Returns true if the target can instruction select the
9748 /// specified FP immediate natively. If false, the legalizer will
9749 /// materialize the FP immediate as a load from a constant pool.
9750 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9751 if (!Subtarget->hasVFP3())
9754 return ARM_AM::getFP32Imm(Imm) != -1;
9756 return ARM_AM::getFP64Imm(Imm) != -1;
9760 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9761 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
9762 /// specified in the intrinsic calls.
9763 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9765 unsigned Intrinsic) const {
9766 switch (Intrinsic) {
9767 case Intrinsic::arm_neon_vld1:
9768 case Intrinsic::arm_neon_vld2:
9769 case Intrinsic::arm_neon_vld3:
9770 case Intrinsic::arm_neon_vld4:
9771 case Intrinsic::arm_neon_vld2lane:
9772 case Intrinsic::arm_neon_vld3lane:
9773 case Intrinsic::arm_neon_vld4lane: {
9774 Info.opc = ISD::INTRINSIC_W_CHAIN;
9775 // Conservatively set memVT to the entire set of vectors loaded.
9776 uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9777 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9778 Info.ptrVal = I.getArgOperand(0);
9780 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9781 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9782 Info.vol = false; // volatile loads with NEON intrinsics not supported
9783 Info.readMem = true;
9784 Info.writeMem = false;
9787 case Intrinsic::arm_neon_vst1:
9788 case Intrinsic::arm_neon_vst2:
9789 case Intrinsic::arm_neon_vst3:
9790 case Intrinsic::arm_neon_vst4:
9791 case Intrinsic::arm_neon_vst2lane:
9792 case Intrinsic::arm_neon_vst3lane:
9793 case Intrinsic::arm_neon_vst4lane: {
9794 Info.opc = ISD::INTRINSIC_VOID;
9795 // Conservatively set memVT to the entire set of vectors stored.
9796 unsigned NumElts = 0;
9797 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9798 Type *ArgTy = I.getArgOperand(ArgI)->getType();
9799 if (!ArgTy->isVectorTy())
9801 NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9803 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9804 Info.ptrVal = I.getArgOperand(0);
9806 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9807 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9808 Info.vol = false; // volatile stores with NEON intrinsics not supported
9809 Info.readMem = false;
9810 Info.writeMem = true;
9813 case Intrinsic::arm_strexd: {
9814 Info.opc = ISD::INTRINSIC_W_CHAIN;
9815 Info.memVT = MVT::i64;
9816 Info.ptrVal = I.getArgOperand(2);
9820 Info.readMem = false;
9821 Info.writeMem = true;
9824 case Intrinsic::arm_ldrexd: {
9825 Info.opc = ISD::INTRINSIC_W_CHAIN;
9826 Info.memVT = MVT::i64;
9827 Info.ptrVal = I.getArgOperand(0);
9831 Info.readMem = true;
9832 Info.writeMem = false;