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 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Target/TargetOptions.h"
52 #define DEBUG_TYPE "arm-isel"
54 STATISTIC(NumTailCalls, "Number of tail calls");
55 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
59 EnableARMLongCalls("arm-long-calls", cl::Hidden,
60 cl::desc("Generate calls via indirect call instructions"),
64 ARMInterworking("arm-interworking", cl::Hidden,
65 cl::desc("Enable / disable ARM interworking (for debugging only)"),
69 class ARMCCState : public CCState {
71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
73 LLVMContext &C, ParmContext PC)
74 : CCState(CC, isVarArg, MF, TM, locs, C) {
75 assert(((PC == Call) || (PC == Prologue)) &&
76 "ARMCCState users must specify whether their context is call"
77 "or prologue generation.");
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85 ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89 MVT PromotedBitwiseVT) {
90 if (VT != PromotedLdStVT) {
91 setOperationAction(ISD::LOAD, VT, Promote);
92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94 setOperationAction(ISD::STORE, VT, Promote);
95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98 MVT ElemTy = VT.getVectorElementType();
99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100 setOperationAction(ISD::SETCC, VT, Custom);
101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103 if (ElemTy == MVT::i32) {
104 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118 setOperationAction(ISD::SELECT, VT, Expand);
119 setOperationAction(ISD::SELECT_CC, VT, Expand);
120 setOperationAction(ISD::VSELECT, VT, Expand);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122 if (VT.isInteger()) {
123 setOperationAction(ISD::SHL, VT, Custom);
124 setOperationAction(ISD::SRA, VT, Custom);
125 setOperationAction(ISD::SRL, VT, Custom);
128 // Promote all bit-wise operations.
129 if (VT.isInteger() && VT != PromotedBitwiseVT) {
130 setOperationAction(ISD::AND, VT, Promote);
131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132 setOperationAction(ISD::OR, VT, Promote);
133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::XOR, VT, Promote);
135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138 // Neon does not support vector divide/remainder operations.
139 setOperationAction(ISD::SDIV, VT, Expand);
140 setOperationAction(ISD::UDIV, VT, Expand);
141 setOperationAction(ISD::FDIV, VT, Expand);
142 setOperationAction(ISD::SREM, VT, Expand);
143 setOperationAction(ISD::UREM, VT, Expand);
144 setOperationAction(ISD::FREM, VT, Expand);
147 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
148 addRegisterClass(VT, &ARM::DPRRegClass);
149 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
152 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
153 addRegisterClass(VT, &ARM::DPairRegClass);
154 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
157 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
158 if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
159 return new TargetLoweringObjectFileMachO();
161 return new ARMElfTargetObjectFile();
164 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
165 : TargetLowering(TM, createTLOF(TM)) {
166 Subtarget = &TM.getSubtarget<ARMSubtarget>();
167 RegInfo = TM.getRegisterInfo();
168 Itins = TM.getInstrItineraryData();
170 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172 if (Subtarget->isTargetMachO()) {
173 // Uses VFP for Thumb libfuncs if available.
174 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
175 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
176 // Single-precision floating-point arithmetic.
177 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
178 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
179 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
180 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
182 // Double-precision floating-point arithmetic.
183 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
184 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
185 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
186 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
188 // Single-precision comparisons.
189 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
190 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
191 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
192 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
193 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
194 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
195 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
196 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
198 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
199 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
200 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
207 // Double-precision comparisons.
208 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
209 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
210 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
211 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
212 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
213 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
214 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
215 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
217 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
218 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
219 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
226 // Floating-point to integer conversions.
227 // i64 conversions are done via library routines even when generating VFP
228 // instructions, so use the same ones.
229 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
230 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
231 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
232 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
234 // Conversions between floating types.
235 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
236 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
238 // Integer to floating-point conversions.
239 // i64 conversions are done via library routines even when generating VFP
240 // instructions, so use the same ones.
241 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
242 // e.g., __floatunsidf vs. __floatunssidfvfp.
243 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
244 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
245 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
246 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
250 // These libcalls are not available in 32-bit.
251 setLibcallName(RTLIB::SHL_I128, nullptr);
252 setLibcallName(RTLIB::SRL_I128, nullptr);
253 setLibcallName(RTLIB::SRA_I128, nullptr);
255 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
256 !Subtarget->isTargetWindows()) {
257 // Double-precision floating-point arithmetic helper functions
258 // RTABI chapter 4.1.2, Table 2
259 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
260 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
261 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
262 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
263 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
264 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
265 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
266 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
268 // Double-precision floating-point comparison helper functions
269 // RTABI chapter 4.1.2, Table 3
270 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
271 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
272 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
273 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
274 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
275 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
276 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
277 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
278 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
279 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
280 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
281 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
282 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
283 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
284 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
285 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
286 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
287 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
288 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
289 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
290 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
295 // Single-precision floating-point arithmetic helper functions
296 // RTABI chapter 4.1.2, Table 4
297 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
298 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
299 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
300 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
301 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
302 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
303 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
304 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
306 // Single-precision floating-point comparison helper functions
307 // RTABI chapter 4.1.2, Table 5
308 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
309 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
310 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
311 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
312 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
313 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
314 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
315 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
316 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
317 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
318 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
319 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
320 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
321 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
322 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
323 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
324 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
325 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
326 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
327 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
328 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
333 // Floating-point to integer conversions.
334 // RTABI chapter 4.1.2, Table 6
335 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
336 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
337 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
338 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
339 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
340 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
341 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
342 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
343 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
344 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
345 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
346 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
347 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
352 // Conversions between floating types.
353 // RTABI chapter 4.1.2, Table 7
354 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
355 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
356 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
357 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
359 // Integer to floating-point conversions.
360 // RTABI chapter 4.1.2, Table 8
361 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
362 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
363 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
364 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
365 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
366 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
367 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
368 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
369 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
370 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
371 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
372 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
373 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
378 // Long long helper functions
379 // RTABI chapter 4.2, Table 9
380 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
381 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
382 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
383 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
384 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
385 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
386 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
387 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
388 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
391 // Integer division functions
392 // RTABI chapter 4.3.1
393 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
394 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
395 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
396 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
397 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
398 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
399 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
400 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
401 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
402 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
403 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
404 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
405 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
411 // RTABI chapter 4.3.4
412 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
413 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
414 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
415 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
416 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
417 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
420 // Use divmod compiler-rt calls for iOS 5.0 and later.
421 if (Subtarget->getTargetTriple().isiOS() &&
422 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
423 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
424 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
427 if (Subtarget->isThumb1Only())
428 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
430 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
431 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
432 !Subtarget->isThumb1Only()) {
433 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
434 if (!Subtarget->isFPOnlySP())
435 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
437 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
440 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
441 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
442 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
444 setTruncStoreAction((MVT::SimpleValueType)VT,
445 (MVT::SimpleValueType)InnerVT, Expand);
446 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
447 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
448 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
450 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
451 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
452 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
453 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
456 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
457 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
459 if (Subtarget->hasNEON()) {
460 addDRTypeForNEON(MVT::v2f32);
461 addDRTypeForNEON(MVT::v8i8);
462 addDRTypeForNEON(MVT::v4i16);
463 addDRTypeForNEON(MVT::v2i32);
464 addDRTypeForNEON(MVT::v1i64);
466 addQRTypeForNEON(MVT::v4f32);
467 addQRTypeForNEON(MVT::v2f64);
468 addQRTypeForNEON(MVT::v16i8);
469 addQRTypeForNEON(MVT::v8i16);
470 addQRTypeForNEON(MVT::v4i32);
471 addQRTypeForNEON(MVT::v2i64);
473 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474 // neither Neon nor VFP support any arithmetic operations on it.
475 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476 // supported for v4f32.
477 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480 // FIXME: Code duplication: FDIV and FREM are expanded always, see
481 // ARMTargetLowering::addTypeForNEON method for details.
482 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484 // FIXME: Create unittest.
485 // In another words, find a way when "copysign" appears in DAG with vector
487 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488 // FIXME: Code duplication: SETCC has custom operation action, see
489 // ARMTargetLowering::addTypeForNEON method for details.
490 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491 // FIXME: Create unittest for FNEG and for FABS.
492 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
512 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
513 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
514 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
515 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
516 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
517 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
518 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
519 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
520 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
521 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
523 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
524 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
525 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
526 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
528 // Mark v2f32 intrinsics.
529 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
530 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
531 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
532 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
533 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
534 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
535 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
536 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
537 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
538 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
539 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
540 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
541 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
542 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
543 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
545 // Neon does not support some operations on v1i64 and v2i64 types.
546 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
547 // Custom handling for some quad-vector types to detect VMULL.
548 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
549 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
550 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
551 // Custom handling for some vector types to avoid expensive expansions
552 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
553 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
554 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
555 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
556 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
557 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
558 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
559 // a destination type that is wider than the source, and nor does
560 // it have a FP_TO_[SU]INT instruction with a narrower destination than
562 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
563 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
564 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
565 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
567 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
568 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
570 // NEON does not have single instruction CTPOP for vectors with element
571 // types wider than 8-bits. However, custom lowering can leverage the
572 // v8i8/v16i8 vcnt instruction.
573 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
574 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
575 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
576 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
578 // NEON only has FMA instructions as of VFP4.
579 if (!Subtarget->hasVFP4()) {
580 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
581 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
584 setTargetDAGCombine(ISD::INTRINSIC_VOID);
585 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
586 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
587 setTargetDAGCombine(ISD::SHL);
588 setTargetDAGCombine(ISD::SRL);
589 setTargetDAGCombine(ISD::SRA);
590 setTargetDAGCombine(ISD::SIGN_EXTEND);
591 setTargetDAGCombine(ISD::ZERO_EXTEND);
592 setTargetDAGCombine(ISD::ANY_EXTEND);
593 setTargetDAGCombine(ISD::SELECT_CC);
594 setTargetDAGCombine(ISD::BUILD_VECTOR);
595 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
596 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
597 setTargetDAGCombine(ISD::STORE);
598 setTargetDAGCombine(ISD::FP_TO_SINT);
599 setTargetDAGCombine(ISD::FP_TO_UINT);
600 setTargetDAGCombine(ISD::FDIV);
602 // It is legal to extload from v4i8 to v4i16 or v4i32.
603 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
604 MVT::v4i16, MVT::v2i16,
606 for (unsigned i = 0; i < 6; ++i) {
607 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
608 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
609 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
613 // ARM and Thumb2 support UMLAL/SMLAL.
614 if (!Subtarget->isThumb1Only())
615 setTargetDAGCombine(ISD::ADDC);
618 computeRegisterProperties();
620 // ARM does not have f32 extending load.
621 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
623 // ARM does not have i1 sign extending load.
624 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
626 // ARM supports all 4 flavors of integer indexed load / store.
627 if (!Subtarget->isThumb1Only()) {
628 for (unsigned im = (unsigned)ISD::PRE_INC;
629 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
630 setIndexedLoadAction(im, MVT::i1, Legal);
631 setIndexedLoadAction(im, MVT::i8, Legal);
632 setIndexedLoadAction(im, MVT::i16, Legal);
633 setIndexedLoadAction(im, MVT::i32, Legal);
634 setIndexedStoreAction(im, MVT::i1, Legal);
635 setIndexedStoreAction(im, MVT::i8, Legal);
636 setIndexedStoreAction(im, MVT::i16, Legal);
637 setIndexedStoreAction(im, MVT::i32, Legal);
641 // i64 operation support.
642 setOperationAction(ISD::MUL, MVT::i64, Expand);
643 setOperationAction(ISD::MULHU, MVT::i32, Expand);
644 if (Subtarget->isThumb1Only()) {
645 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
646 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
648 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
649 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
650 setOperationAction(ISD::MULHS, MVT::i32, Expand);
652 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
653 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
654 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
655 setOperationAction(ISD::SRL, MVT::i64, Custom);
656 setOperationAction(ISD::SRA, MVT::i64, Custom);
658 if (!Subtarget->isThumb1Only()) {
659 // FIXME: We should do this for Thumb1 as well.
660 setOperationAction(ISD::ADDC, MVT::i32, Custom);
661 setOperationAction(ISD::ADDE, MVT::i32, Custom);
662 setOperationAction(ISD::SUBC, MVT::i32, Custom);
663 setOperationAction(ISD::SUBE, MVT::i32, Custom);
666 // ARM does not have ROTL.
667 setOperationAction(ISD::ROTL, MVT::i32, Expand);
668 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
669 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
670 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
671 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
673 // These just redirect to CTTZ and CTLZ on ARM.
674 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
675 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
677 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
679 // Only ARMv6 has BSWAP.
680 if (!Subtarget->hasV6Ops())
681 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
683 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
684 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
685 // These are expanded into libcalls if the cpu doesn't have HW divider.
686 setOperationAction(ISD::SDIV, MVT::i32, Expand);
687 setOperationAction(ISD::UDIV, MVT::i32, Expand);
690 // FIXME: Also set divmod for SREM on EABI
691 setOperationAction(ISD::SREM, MVT::i32, Expand);
692 setOperationAction(ISD::UREM, MVT::i32, Expand);
693 // Register based DivRem for AEABI (RTABI 4.2)
694 if (Subtarget->isTargetAEABI()) {
695 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
696 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
697 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
698 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
699 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
700 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
701 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
702 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
704 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
705 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
706 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
707 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
708 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
709 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
710 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
711 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
713 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
714 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
716 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
717 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
720 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
721 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
722 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
723 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
724 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
726 setOperationAction(ISD::TRAP, MVT::Other, Legal);
728 // Use the default implementation.
729 setOperationAction(ISD::VASTART, MVT::Other, Custom);
730 setOperationAction(ISD::VAARG, MVT::Other, Expand);
731 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
732 setOperationAction(ISD::VAEND, MVT::Other, Expand);
733 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
734 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
736 if (!Subtarget->isTargetMachO()) {
737 // Non-MachO platforms may return values in these registers via the
738 // personality function.
739 setExceptionPointerRegister(ARM::R0);
740 setExceptionSelectorRegister(ARM::R1);
743 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
744 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
745 // the default expansion.
746 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
747 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
748 // to ldrex/strex loops already.
749 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
751 // On v8, we have particularly efficient implementations of atomic fences
752 // if they can be combined with nearby atomic loads and stores.
753 if (!Subtarget->hasV8Ops()) {
754 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
755 setInsertFencesForAtomic(true);
758 // If there's anything we can use as a barrier, go through custom lowering
760 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
761 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
763 // Set them all for expansion, which will force libcalls.
764 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
765 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
766 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
767 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
768 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
769 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
770 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
771 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
772 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
773 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
774 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
775 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
776 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
777 // Unordered/Monotonic case.
778 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
779 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
782 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
784 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
785 if (!Subtarget->hasV6Ops()) {
786 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
787 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
789 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
791 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
792 !Subtarget->isThumb1Only()) {
793 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
794 // iff target supports vfp2.
795 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
796 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
799 // We want to custom lower some of our intrinsics.
800 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
801 if (Subtarget->isTargetDarwin()) {
802 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
803 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
804 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
807 setOperationAction(ISD::SETCC, MVT::i32, Expand);
808 setOperationAction(ISD::SETCC, MVT::f32, Expand);
809 setOperationAction(ISD::SETCC, MVT::f64, Expand);
810 setOperationAction(ISD::SELECT, MVT::i32, Custom);
811 setOperationAction(ISD::SELECT, MVT::f32, Custom);
812 setOperationAction(ISD::SELECT, MVT::f64, Custom);
813 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
814 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
815 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
817 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
818 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
819 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
820 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
821 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
823 // We don't support sin/cos/fmod/copysign/pow
824 setOperationAction(ISD::FSIN, MVT::f64, Expand);
825 setOperationAction(ISD::FSIN, MVT::f32, Expand);
826 setOperationAction(ISD::FCOS, MVT::f32, Expand);
827 setOperationAction(ISD::FCOS, MVT::f64, Expand);
828 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
829 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
830 setOperationAction(ISD::FREM, MVT::f64, Expand);
831 setOperationAction(ISD::FREM, MVT::f32, Expand);
832 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
833 !Subtarget->isThumb1Only()) {
834 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
835 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
837 setOperationAction(ISD::FPOW, MVT::f64, Expand);
838 setOperationAction(ISD::FPOW, MVT::f32, Expand);
840 if (!Subtarget->hasVFP4()) {
841 setOperationAction(ISD::FMA, MVT::f64, Expand);
842 setOperationAction(ISD::FMA, MVT::f32, Expand);
845 // Various VFP goodness
846 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
847 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
848 if (Subtarget->hasVFP2()) {
849 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
850 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
851 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
852 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
854 // Special handling for half-precision FP.
855 if (!Subtarget->hasFP16()) {
856 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
857 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
861 // Combine sin / cos into one node or libcall if possible.
862 if (Subtarget->hasSinCos()) {
863 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
864 setLibcallName(RTLIB::SINCOS_F64, "sincos");
865 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
866 // For iOS, we don't want to the normal expansion of a libcall to
867 // sincos. We want to issue a libcall to __sincos_stret.
868 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
869 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
873 // We have target-specific dag combine patterns for the following nodes:
874 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
875 setTargetDAGCombine(ISD::ADD);
876 setTargetDAGCombine(ISD::SUB);
877 setTargetDAGCombine(ISD::MUL);
878 setTargetDAGCombine(ISD::AND);
879 setTargetDAGCombine(ISD::OR);
880 setTargetDAGCombine(ISD::XOR);
882 if (Subtarget->hasV6Ops())
883 setTargetDAGCombine(ISD::SRL);
885 setStackPointerRegisterToSaveRestore(ARM::SP);
887 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
888 !Subtarget->hasVFP2())
889 setSchedulingPreference(Sched::RegPressure);
891 setSchedulingPreference(Sched::Hybrid);
893 //// temporary - rewrite interface to use type
894 MaxStoresPerMemset = 8;
895 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
896 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
897 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
898 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
899 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
901 // On ARM arguments smaller than 4 bytes are extended, so all arguments
902 // are at least 4 bytes aligned.
903 setMinStackArgumentAlignment(4);
905 // Prefer likely predicted branches to selects on out-of-order cores.
906 PredictableSelectIsExpensive = Subtarget->isLikeA9();
908 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
911 // FIXME: It might make sense to define the representative register class as the
912 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
913 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
914 // SPR's representative would be DPR_VFP2. This should work well if register
915 // pressure tracking were modified such that a register use would increment the
916 // pressure of the register class's representative and all of it's super
917 // classes' representatives transitively. We have not implemented this because
918 // of the difficulty prior to coalescing of modeling operand register classes
919 // due to the common occurrence of cross class copies and subregister insertions
921 std::pair<const TargetRegisterClass*, uint8_t>
922 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
923 const TargetRegisterClass *RRC = nullptr;
925 switch (VT.SimpleTy) {
927 return TargetLowering::findRepresentativeClass(VT);
928 // Use DPR as representative register class for all floating point
929 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
930 // the cost is 1 for both f32 and f64.
931 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
932 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
933 RRC = &ARM::DPRRegClass;
934 // When NEON is used for SP, only half of the register file is available
935 // because operations that define both SP and DP results will be constrained
936 // to the VFP2 class (D0-D15). We currently model this constraint prior to
937 // coalescing by double-counting the SP regs. See the FIXME above.
938 if (Subtarget->useNEONForSinglePrecisionFP())
941 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
942 case MVT::v4f32: case MVT::v2f64:
943 RRC = &ARM::DPRRegClass;
947 RRC = &ARM::DPRRegClass;
951 RRC = &ARM::DPRRegClass;
955 return std::make_pair(RRC, Cost);
958 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
960 default: return nullptr;
961 case ARMISD::Wrapper: return "ARMISD::Wrapper";
962 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
963 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
964 case ARMISD::CALL: return "ARMISD::CALL";
965 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
966 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
967 case ARMISD::tCALL: return "ARMISD::tCALL";
968 case ARMISD::BRCOND: return "ARMISD::BRCOND";
969 case ARMISD::BR_JT: return "ARMISD::BR_JT";
970 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
971 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
972 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
973 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
974 case ARMISD::CMP: return "ARMISD::CMP";
975 case ARMISD::CMN: return "ARMISD::CMN";
976 case ARMISD::CMPZ: return "ARMISD::CMPZ";
977 case ARMISD::CMPFP: return "ARMISD::CMPFP";
978 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
979 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
980 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
982 case ARMISD::CMOV: return "ARMISD::CMOV";
984 case ARMISD::RBIT: return "ARMISD::RBIT";
986 case ARMISD::FTOSI: return "ARMISD::FTOSI";
987 case ARMISD::FTOUI: return "ARMISD::FTOUI";
988 case ARMISD::SITOF: return "ARMISD::SITOF";
989 case ARMISD::UITOF: return "ARMISD::UITOF";
991 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
992 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
993 case ARMISD::RRX: return "ARMISD::RRX";
995 case ARMISD::ADDC: return "ARMISD::ADDC";
996 case ARMISD::ADDE: return "ARMISD::ADDE";
997 case ARMISD::SUBC: return "ARMISD::SUBC";
998 case ARMISD::SUBE: return "ARMISD::SUBE";
1000 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1001 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1003 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1004 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1006 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1008 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1010 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1012 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1014 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1016 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1017 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1018 case ARMISD::VCGE: return "ARMISD::VCGE";
1019 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1020 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1021 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1022 case ARMISD::VCGT: return "ARMISD::VCGT";
1023 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1024 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1025 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1026 case ARMISD::VTST: return "ARMISD::VTST";
1028 case ARMISD::VSHL: return "ARMISD::VSHL";
1029 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1030 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1031 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1032 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1033 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1034 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1035 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1036 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1037 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1038 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1039 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1040 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1041 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1042 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1043 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1044 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1045 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1046 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1047 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1048 case ARMISD::VDUP: return "ARMISD::VDUP";
1049 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1050 case ARMISD::VEXT: return "ARMISD::VEXT";
1051 case ARMISD::VREV64: return "ARMISD::VREV64";
1052 case ARMISD::VREV32: return "ARMISD::VREV32";
1053 case ARMISD::VREV16: return "ARMISD::VREV16";
1054 case ARMISD::VZIP: return "ARMISD::VZIP";
1055 case ARMISD::VUZP: return "ARMISD::VUZP";
1056 case ARMISD::VTRN: return "ARMISD::VTRN";
1057 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1058 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1059 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1060 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1061 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1062 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1063 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1064 case ARMISD::FMAX: return "ARMISD::FMAX";
1065 case ARMISD::FMIN: return "ARMISD::FMIN";
1066 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1067 case ARMISD::VMINNM: return "ARMISD::VMIN";
1068 case ARMISD::BFI: return "ARMISD::BFI";
1069 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1070 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1071 case ARMISD::VBSL: return "ARMISD::VBSL";
1072 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1073 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1074 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1075 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1076 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1077 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1078 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1079 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1080 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1081 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1082 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1083 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1084 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1085 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1086 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1087 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1088 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1089 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1090 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1091 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1095 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1096 if (!VT.isVector()) return getPointerTy();
1097 return VT.changeVectorElementTypeToInteger();
1100 /// getRegClassFor - Return the register class that should be used for the
1101 /// specified value type.
1102 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1103 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1104 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1105 // load / store 4 to 8 consecutive D registers.
1106 if (Subtarget->hasNEON()) {
1107 if (VT == MVT::v4i64)
1108 return &ARM::QQPRRegClass;
1109 if (VT == MVT::v8i64)
1110 return &ARM::QQQQPRRegClass;
1112 return TargetLowering::getRegClassFor(VT);
1115 // Create a fast isel object.
1117 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1118 const TargetLibraryInfo *libInfo) const {
1119 return ARM::createFastISel(funcInfo, libInfo);
1122 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1123 /// be used for loads / stores from the global.
1124 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1125 return (Subtarget->isThumb1Only() ? 127 : 4095);
1128 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1129 unsigned NumVals = N->getNumValues();
1131 return Sched::RegPressure;
1133 for (unsigned i = 0; i != NumVals; ++i) {
1134 EVT VT = N->getValueType(i);
1135 if (VT == MVT::Glue || VT == MVT::Other)
1137 if (VT.isFloatingPoint() || VT.isVector())
1141 if (!N->isMachineOpcode())
1142 return Sched::RegPressure;
1144 // Load are scheduled for latency even if there instruction itinerary
1145 // is not available.
1146 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1147 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1149 if (MCID.getNumDefs() == 0)
1150 return Sched::RegPressure;
1151 if (!Itins->isEmpty() &&
1152 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1155 return Sched::RegPressure;
1158 //===----------------------------------------------------------------------===//
1160 //===----------------------------------------------------------------------===//
1162 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1163 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1165 default: llvm_unreachable("Unknown condition code!");
1166 case ISD::SETNE: return ARMCC::NE;
1167 case ISD::SETEQ: return ARMCC::EQ;
1168 case ISD::SETGT: return ARMCC::GT;
1169 case ISD::SETGE: return ARMCC::GE;
1170 case ISD::SETLT: return ARMCC::LT;
1171 case ISD::SETLE: return ARMCC::LE;
1172 case ISD::SETUGT: return ARMCC::HI;
1173 case ISD::SETUGE: return ARMCC::HS;
1174 case ISD::SETULT: return ARMCC::LO;
1175 case ISD::SETULE: return ARMCC::LS;
1179 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1180 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1181 ARMCC::CondCodes &CondCode2) {
1182 CondCode2 = ARMCC::AL;
1184 default: llvm_unreachable("Unknown FP condition!");
1186 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1188 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1190 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1191 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1192 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1193 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1194 case ISD::SETO: CondCode = ARMCC::VC; break;
1195 case ISD::SETUO: CondCode = ARMCC::VS; break;
1196 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1197 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1198 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1200 case ISD::SETULT: CondCode = ARMCC::LT; break;
1202 case ISD::SETULE: CondCode = ARMCC::LE; break;
1204 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1208 //===----------------------------------------------------------------------===//
1209 // Calling Convention Implementation
1210 //===----------------------------------------------------------------------===//
1212 #include "ARMGenCallingConv.inc"
1214 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1215 /// given CallingConvention value.
1216 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1218 bool isVarArg) const {
1221 llvm_unreachable("Unsupported calling convention");
1222 case CallingConv::Fast:
1223 if (Subtarget->hasVFP2() && !isVarArg) {
1224 if (!Subtarget->isAAPCS_ABI())
1225 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1226 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1227 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1230 case CallingConv::C: {
1231 // Use target triple & subtarget features to do actual dispatch.
1232 if (!Subtarget->isAAPCS_ABI())
1233 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1234 else if (Subtarget->hasVFP2() &&
1235 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1237 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1238 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1240 case CallingConv::ARM_AAPCS_VFP:
1242 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1244 case CallingConv::ARM_AAPCS:
1245 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1246 case CallingConv::ARM_APCS:
1247 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1248 case CallingConv::GHC:
1249 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1253 /// LowerCallResult - Lower the result values of a call into the
1254 /// appropriate copies out of appropriate physical registers.
1256 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1257 CallingConv::ID CallConv, bool isVarArg,
1258 const SmallVectorImpl<ISD::InputArg> &Ins,
1259 SDLoc dl, SelectionDAG &DAG,
1260 SmallVectorImpl<SDValue> &InVals,
1261 bool isThisReturn, SDValue ThisVal) const {
1263 // Assign locations to each value returned by this call.
1264 SmallVector<CCValAssign, 16> RVLocs;
1265 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1266 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1267 CCInfo.AnalyzeCallResult(Ins,
1268 CCAssignFnForNode(CallConv, /* Return*/ true,
1271 // Copy all of the result registers out of their specified physreg.
1272 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1273 CCValAssign VA = RVLocs[i];
1275 // Pass 'this' value directly from the argument to return value, to avoid
1276 // reg unit interference
1277 if (i == 0 && isThisReturn) {
1278 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1279 "unexpected return calling convention register assignment");
1280 InVals.push_back(ThisVal);
1285 if (VA.needsCustom()) {
1286 // Handle f64 or half of a v2f64.
1287 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1289 Chain = Lo.getValue(1);
1290 InFlag = Lo.getValue(2);
1291 VA = RVLocs[++i]; // skip ahead to next loc
1292 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1294 Chain = Hi.getValue(1);
1295 InFlag = Hi.getValue(2);
1296 if (!Subtarget->isLittle())
1298 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1300 if (VA.getLocVT() == MVT::v2f64) {
1301 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1302 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1303 DAG.getConstant(0, MVT::i32));
1305 VA = RVLocs[++i]; // skip ahead to next loc
1306 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1307 Chain = Lo.getValue(1);
1308 InFlag = Lo.getValue(2);
1309 VA = RVLocs[++i]; // skip ahead to next loc
1310 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1311 Chain = Hi.getValue(1);
1312 InFlag = Hi.getValue(2);
1313 if (!Subtarget->isLittle())
1315 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1316 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1317 DAG.getConstant(1, MVT::i32));
1320 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1322 Chain = Val.getValue(1);
1323 InFlag = Val.getValue(2);
1326 switch (VA.getLocInfo()) {
1327 default: llvm_unreachable("Unknown loc info!");
1328 case CCValAssign::Full: break;
1329 case CCValAssign::BCvt:
1330 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1334 InVals.push_back(Val);
1340 /// LowerMemOpCallTo - Store the argument to the stack.
1342 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1343 SDValue StackPtr, SDValue Arg,
1344 SDLoc dl, SelectionDAG &DAG,
1345 const CCValAssign &VA,
1346 ISD::ArgFlagsTy Flags) const {
1347 unsigned LocMemOffset = VA.getLocMemOffset();
1348 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1349 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1350 return DAG.getStore(Chain, dl, Arg, PtrOff,
1351 MachinePointerInfo::getStack(LocMemOffset),
1355 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1356 SDValue Chain, SDValue &Arg,
1357 RegsToPassVector &RegsToPass,
1358 CCValAssign &VA, CCValAssign &NextVA,
1360 SmallVectorImpl<SDValue> &MemOpChains,
1361 ISD::ArgFlagsTy Flags) const {
1363 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1364 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1365 unsigned id = Subtarget->isLittle() ? 0 : 1;
1366 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1368 if (NextVA.isRegLoc())
1369 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1371 assert(NextVA.isMemLoc());
1372 if (!StackPtr.getNode())
1373 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1375 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1381 /// LowerCall - Lowering a call into a callseq_start <-
1382 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1385 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1386 SmallVectorImpl<SDValue> &InVals) const {
1387 SelectionDAG &DAG = CLI.DAG;
1389 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1390 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1391 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1392 SDValue Chain = CLI.Chain;
1393 SDValue Callee = CLI.Callee;
1394 bool &isTailCall = CLI.IsTailCall;
1395 CallingConv::ID CallConv = CLI.CallConv;
1396 bool doesNotRet = CLI.DoesNotReturn;
1397 bool isVarArg = CLI.IsVarArg;
1399 MachineFunction &MF = DAG.getMachineFunction();
1400 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1401 bool isThisReturn = false;
1402 bool isSibCall = false;
1404 // Disable tail calls if they're not supported.
1405 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1409 // Check if it's really possible to do a tail call.
1410 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1411 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1412 Outs, OutVals, Ins, DAG);
1413 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1414 report_fatal_error("failed to perform tail call elimination on a call "
1415 "site marked musttail");
1416 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1417 // detected sibcalls.
1424 // Analyze operands of the call, assigning locations to each operand.
1425 SmallVector<CCValAssign, 16> ArgLocs;
1426 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1427 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1428 CCInfo.AnalyzeCallOperands(Outs,
1429 CCAssignFnForNode(CallConv, /* Return*/ false,
1432 // Get a count of how many bytes are to be pushed on the stack.
1433 unsigned NumBytes = CCInfo.getNextStackOffset();
1435 // For tail calls, memory operands are available in our caller's stack.
1439 // Adjust the stack pointer for the new arguments...
1440 // These operations are automatically eliminated by the prolog/epilog pass
1442 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1445 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1447 RegsToPassVector RegsToPass;
1448 SmallVector<SDValue, 8> MemOpChains;
1450 // Walk the register/memloc assignments, inserting copies/loads. In the case
1451 // of tail call optimization, arguments are handled later.
1452 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1454 ++i, ++realArgIdx) {
1455 CCValAssign &VA = ArgLocs[i];
1456 SDValue Arg = OutVals[realArgIdx];
1457 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1458 bool isByVal = Flags.isByVal();
1460 // Promote the value if needed.
1461 switch (VA.getLocInfo()) {
1462 default: llvm_unreachable("Unknown loc info!");
1463 case CCValAssign::Full: break;
1464 case CCValAssign::SExt:
1465 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1467 case CCValAssign::ZExt:
1468 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1470 case CCValAssign::AExt:
1471 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1473 case CCValAssign::BCvt:
1474 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1478 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1479 if (VA.needsCustom()) {
1480 if (VA.getLocVT() == MVT::v2f64) {
1481 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1482 DAG.getConstant(0, MVT::i32));
1483 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1484 DAG.getConstant(1, MVT::i32));
1486 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1487 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1489 VA = ArgLocs[++i]; // skip ahead to next loc
1490 if (VA.isRegLoc()) {
1491 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1492 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1494 assert(VA.isMemLoc());
1496 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1497 dl, DAG, VA, Flags));
1500 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1501 StackPtr, MemOpChains, Flags);
1503 } else if (VA.isRegLoc()) {
1504 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1505 assert(VA.getLocVT() == MVT::i32 &&
1506 "unexpected calling convention register assignment");
1507 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1508 "unexpected use of 'returned'");
1509 isThisReturn = true;
1511 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1512 } else if (isByVal) {
1513 assert(VA.isMemLoc());
1514 unsigned offset = 0;
1516 // True if this byval aggregate will be split between registers
1518 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1519 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1521 if (CurByValIdx < ByValArgsCount) {
1523 unsigned RegBegin, RegEnd;
1524 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1526 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1528 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1529 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1530 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1531 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1532 MachinePointerInfo(),
1533 false, false, false,
1534 DAG.InferPtrAlignment(AddArg));
1535 MemOpChains.push_back(Load.getValue(1));
1536 RegsToPass.push_back(std::make_pair(j, Load));
1539 // If parameter size outsides register area, "offset" value
1540 // helps us to calculate stack slot for remained part properly.
1541 offset = RegEnd - RegBegin;
1543 CCInfo.nextInRegsParam();
1546 if (Flags.getByValSize() > 4*offset) {
1547 unsigned LocMemOffset = VA.getLocMemOffset();
1548 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1549 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1551 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1552 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1553 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1555 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1557 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1558 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1559 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1562 } else if (!isSibCall) {
1563 assert(VA.isMemLoc());
1565 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1566 dl, DAG, VA, Flags));
1570 if (!MemOpChains.empty())
1571 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1573 // Build a sequence of copy-to-reg nodes chained together with token chain
1574 // and flag operands which copy the outgoing args into the appropriate regs.
1576 // Tail call byval lowering might overwrite argument registers so in case of
1577 // tail call optimization the copies to registers are lowered later.
1579 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1580 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1581 RegsToPass[i].second, InFlag);
1582 InFlag = Chain.getValue(1);
1585 // For tail calls lower the arguments to the 'real' stack slot.
1587 // Force all the incoming stack arguments to be loaded from the stack
1588 // before any new outgoing arguments are stored to the stack, because the
1589 // outgoing stack slots may alias the incoming argument stack slots, and
1590 // the alias isn't otherwise explicit. This is slightly more conservative
1591 // than necessary, because it means that each store effectively depends
1592 // on every argument instead of just those arguments it would clobber.
1594 // Do not flag preceding copytoreg stuff together with the following stuff.
1596 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1597 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1598 RegsToPass[i].second, InFlag);
1599 InFlag = Chain.getValue(1);
1604 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1605 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1606 // node so that legalize doesn't hack it.
1607 bool isDirect = false;
1608 bool isARMFunc = false;
1609 bool isLocalARMFunc = false;
1610 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1612 if (EnableARMLongCalls) {
1613 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1614 && "long-calls with non-static relocation model!");
1615 // Handle a global address or an external symbol. If it's not one of
1616 // those, the target's already in a register, so we don't need to do
1618 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1619 const GlobalValue *GV = G->getGlobal();
1620 // Create a constant pool entry for the callee address
1621 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1622 ARMConstantPoolValue *CPV =
1623 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1625 // Get the address of the callee into a register
1626 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1627 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1628 Callee = DAG.getLoad(getPointerTy(), dl,
1629 DAG.getEntryNode(), CPAddr,
1630 MachinePointerInfo::getConstantPool(),
1631 false, false, false, 0);
1632 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1633 const char *Sym = S->getSymbol();
1635 // Create a constant pool entry for the callee address
1636 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1637 ARMConstantPoolValue *CPV =
1638 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1639 ARMPCLabelIndex, 0);
1640 // Get the address of the callee into a register
1641 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1642 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1643 Callee = DAG.getLoad(getPointerTy(), dl,
1644 DAG.getEntryNode(), CPAddr,
1645 MachinePointerInfo::getConstantPool(),
1646 false, false, false, 0);
1648 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1649 const GlobalValue *GV = G->getGlobal();
1651 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1652 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1653 getTargetMachine().getRelocationModel() != Reloc::Static;
1654 isARMFunc = !Subtarget->isThumb() || isStub;
1655 // ARM call to a local ARM function is predicable.
1656 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1657 // tBX takes a register source operand.
1658 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1659 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1660 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1661 DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1663 // On ELF targets for PIC code, direct calls should go through the PLT
1664 unsigned OpFlags = 0;
1665 if (Subtarget->isTargetELF() &&
1666 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1667 OpFlags = ARMII::MO_PLT;
1668 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1670 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1672 bool isStub = Subtarget->isTargetMachO() &&
1673 getTargetMachine().getRelocationModel() != Reloc::Static;
1674 isARMFunc = !Subtarget->isThumb() || isStub;
1675 // tBX takes a register source operand.
1676 const char *Sym = S->getSymbol();
1677 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1678 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1679 ARMConstantPoolValue *CPV =
1680 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1681 ARMPCLabelIndex, 4);
1682 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1683 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1684 Callee = DAG.getLoad(getPointerTy(), dl,
1685 DAG.getEntryNode(), CPAddr,
1686 MachinePointerInfo::getConstantPool(),
1687 false, false, false, 0);
1688 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1689 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1690 getPointerTy(), Callee, PICLabel);
1692 unsigned OpFlags = 0;
1693 // On ELF targets for PIC code, direct calls should go through the PLT
1694 if (Subtarget->isTargetELF() &&
1695 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1696 OpFlags = ARMII::MO_PLT;
1697 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1701 // FIXME: handle tail calls differently.
1703 bool HasMinSizeAttr = Subtarget->isMinSize();
1704 if (Subtarget->isThumb()) {
1705 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1706 CallOpc = ARMISD::CALL_NOLINK;
1708 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1710 if (!isDirect && !Subtarget->hasV5TOps())
1711 CallOpc = ARMISD::CALL_NOLINK;
1712 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1713 // Emit regular call when code size is the priority
1715 // "mov lr, pc; b _foo" to avoid confusing the RSP
1716 CallOpc = ARMISD::CALL_NOLINK;
1718 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1721 std::vector<SDValue> Ops;
1722 Ops.push_back(Chain);
1723 Ops.push_back(Callee);
1725 // Add argument registers to the end of the list so that they are known live
1727 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1728 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1729 RegsToPass[i].second.getValueType()));
1731 // Add a register mask operand representing the call-preserved registers.
1733 const uint32_t *Mask;
1734 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1735 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1737 // For 'this' returns, use the R0-preserving mask if applicable
1738 Mask = ARI->getThisReturnPreservedMask(CallConv);
1740 // Set isThisReturn to false if the calling convention is not one that
1741 // allows 'returned' to be modeled in this way, so LowerCallResult does
1742 // not try to pass 'this' straight through
1743 isThisReturn = false;
1744 Mask = ARI->getCallPreservedMask(CallConv);
1747 Mask = ARI->getCallPreservedMask(CallConv);
1749 assert(Mask && "Missing call preserved mask for calling convention");
1750 Ops.push_back(DAG.getRegisterMask(Mask));
1753 if (InFlag.getNode())
1754 Ops.push_back(InFlag);
1756 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1758 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1760 // Returns a chain and a flag for retval copy to use.
1761 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1762 InFlag = Chain.getValue(1);
1764 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1765 DAG.getIntPtrConstant(0, true), InFlag, dl);
1767 InFlag = Chain.getValue(1);
1769 // Handle result values, copying them out of physregs into vregs that we
1771 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1772 InVals, isThisReturn,
1773 isThisReturn ? OutVals[0] : SDValue());
1776 /// HandleByVal - Every parameter *after* a byval parameter is passed
1777 /// on the stack. Remember the next parameter register to allocate,
1778 /// and then confiscate the rest of the parameter registers to insure
1781 ARMTargetLowering::HandleByVal(
1782 CCState *State, unsigned &size, unsigned Align) const {
1783 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1784 assert((State->getCallOrPrologue() == Prologue ||
1785 State->getCallOrPrologue() == Call) &&
1786 "unhandled ParmContext");
1788 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1789 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1790 unsigned AlignInRegs = Align / 4;
1791 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1792 for (unsigned i = 0; i < Waste; ++i)
1793 reg = State->AllocateReg(GPRArgRegs, 4);
1796 unsigned excess = 4 * (ARM::R4 - reg);
1798 // Special case when NSAA != SP and parameter size greater than size of
1799 // all remained GPR regs. In that case we can't split parameter, we must
1800 // send it to stack. We also must set NCRN to R4, so waste all
1801 // remained registers.
1802 const unsigned NSAAOffset = State->getNextStackOffset();
1803 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1804 while (State->AllocateReg(GPRArgRegs, 4))
1809 // First register for byval parameter is the first register that wasn't
1810 // allocated before this method call, so it would be "reg".
1811 // If parameter is small enough to be saved in range [reg, r4), then
1812 // the end (first after last) register would be reg + param-size-in-regs,
1813 // else parameter would be splitted between registers and stack,
1814 // end register would be r4 in this case.
1815 unsigned ByValRegBegin = reg;
1816 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1817 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1818 // Note, first register is allocated in the beginning of function already,
1819 // allocate remained amount of registers we need.
1820 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1821 State->AllocateReg(GPRArgRegs, 4);
1822 // A byval parameter that is split between registers and memory needs its
1823 // size truncated here.
1824 // In the case where the entire structure fits in registers, we set the
1825 // size in memory to zero.
1834 /// MatchingStackOffset - Return true if the given stack call argument is
1835 /// already available in the same position (relatively) of the caller's
1836 /// incoming argument stack.
1838 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1839 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1840 const TargetInstrInfo *TII) {
1841 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1843 if (Arg.getOpcode() == ISD::CopyFromReg) {
1844 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1845 if (!TargetRegisterInfo::isVirtualRegister(VR))
1847 MachineInstr *Def = MRI->getVRegDef(VR);
1850 if (!Flags.isByVal()) {
1851 if (!TII->isLoadFromStackSlot(Def, FI))
1856 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1857 if (Flags.isByVal())
1858 // ByVal argument is passed in as a pointer but it's now being
1859 // dereferenced. e.g.
1860 // define @foo(%struct.X* %A) {
1861 // tail call @bar(%struct.X* byval %A)
1864 SDValue Ptr = Ld->getBasePtr();
1865 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1868 FI = FINode->getIndex();
1872 assert(FI != INT_MAX);
1873 if (!MFI->isFixedObjectIndex(FI))
1875 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1878 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1879 /// for tail call optimization. Targets which want to do tail call
1880 /// optimization should implement this function.
1882 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1883 CallingConv::ID CalleeCC,
1885 bool isCalleeStructRet,
1886 bool isCallerStructRet,
1887 const SmallVectorImpl<ISD::OutputArg> &Outs,
1888 const SmallVectorImpl<SDValue> &OutVals,
1889 const SmallVectorImpl<ISD::InputArg> &Ins,
1890 SelectionDAG& DAG) const {
1891 const Function *CallerF = DAG.getMachineFunction().getFunction();
1892 CallingConv::ID CallerCC = CallerF->getCallingConv();
1893 bool CCMatch = CallerCC == CalleeCC;
1895 // Look for obvious safe cases to perform tail call optimization that do not
1896 // require ABI changes. This is what gcc calls sibcall.
1898 // Do not sibcall optimize vararg calls unless the call site is not passing
1900 if (isVarArg && !Outs.empty())
1903 // Exception-handling functions need a special set of instructions to indicate
1904 // a return to the hardware. Tail-calling another function would probably
1906 if (CallerF->hasFnAttribute("interrupt"))
1909 // Also avoid sibcall optimization if either caller or callee uses struct
1910 // return semantics.
1911 if (isCalleeStructRet || isCallerStructRet)
1914 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1915 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1916 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1917 // support in the assembler and linker to be used. This would need to be
1918 // fixed to fully support tail calls in Thumb1.
1920 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1921 // LR. This means if we need to reload LR, it takes an extra instructions,
1922 // which outweighs the value of the tail call; but here we don't know yet
1923 // whether LR is going to be used. Probably the right approach is to
1924 // generate the tail call here and turn it back into CALL/RET in
1925 // emitEpilogue if LR is used.
1927 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1928 // but we need to make sure there are enough registers; the only valid
1929 // registers are the 4 used for parameters. We don't currently do this
1931 if (Subtarget->isThumb1Only())
1934 // If the calling conventions do not match, then we'd better make sure the
1935 // results are returned in the same way as what the caller expects.
1937 SmallVector<CCValAssign, 16> RVLocs1;
1938 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1939 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1940 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1942 SmallVector<CCValAssign, 16> RVLocs2;
1943 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1944 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1945 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1947 if (RVLocs1.size() != RVLocs2.size())
1949 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1950 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1952 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1954 if (RVLocs1[i].isRegLoc()) {
1955 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1958 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1964 // If Caller's vararg or byval argument has been split between registers and
1965 // stack, do not perform tail call, since part of the argument is in caller's
1967 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1968 getInfo<ARMFunctionInfo>();
1969 if (AFI_Caller->getArgRegsSaveSize())
1972 // If the callee takes no arguments then go on to check the results of the
1974 if (!Outs.empty()) {
1975 // Check if stack adjustment is needed. For now, do not do this if any
1976 // argument is passed on the stack.
1977 SmallVector<CCValAssign, 16> ArgLocs;
1978 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1979 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1980 CCInfo.AnalyzeCallOperands(Outs,
1981 CCAssignFnForNode(CalleeCC, false, isVarArg));
1982 if (CCInfo.getNextStackOffset()) {
1983 MachineFunction &MF = DAG.getMachineFunction();
1985 // Check if the arguments are already laid out in the right way as
1986 // the caller's fixed stack objects.
1987 MachineFrameInfo *MFI = MF.getFrameInfo();
1988 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1989 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1990 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1992 ++i, ++realArgIdx) {
1993 CCValAssign &VA = ArgLocs[i];
1994 EVT RegVT = VA.getLocVT();
1995 SDValue Arg = OutVals[realArgIdx];
1996 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1997 if (VA.getLocInfo() == CCValAssign::Indirect)
1999 if (VA.needsCustom()) {
2000 // f64 and vector types are split into multiple registers or
2001 // register/stack-slot combinations. The types will not match
2002 // the registers; give up on memory f64 refs until we figure
2003 // out what to do about this.
2006 if (!ArgLocs[++i].isRegLoc())
2008 if (RegVT == MVT::v2f64) {
2009 if (!ArgLocs[++i].isRegLoc())
2011 if (!ArgLocs[++i].isRegLoc())
2014 } else if (!VA.isRegLoc()) {
2015 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2027 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2028 MachineFunction &MF, bool isVarArg,
2029 const SmallVectorImpl<ISD::OutputArg> &Outs,
2030 LLVMContext &Context) const {
2031 SmallVector<CCValAssign, 16> RVLocs;
2032 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2033 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2037 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2038 SDLoc DL, SelectionDAG &DAG) {
2039 const MachineFunction &MF = DAG.getMachineFunction();
2040 const Function *F = MF.getFunction();
2042 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2044 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2045 // version of the "preferred return address". These offsets affect the return
2046 // instruction if this is a return from PL1 without hypervisor extensions.
2047 // IRQ/FIQ: +4 "subs pc, lr, #4"
2048 // SWI: 0 "subs pc, lr, #0"
2049 // ABORT: +4 "subs pc, lr, #4"
2050 // UNDEF: +4/+2 "subs pc, lr, #0"
2051 // UNDEF varies depending on where the exception came from ARM or Thumb
2052 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2055 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2058 else if (IntKind == "SWI" || IntKind == "UNDEF")
2061 report_fatal_error("Unsupported interrupt attribute. If present, value "
2062 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2064 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2066 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2070 ARMTargetLowering::LowerReturn(SDValue Chain,
2071 CallingConv::ID CallConv, bool isVarArg,
2072 const SmallVectorImpl<ISD::OutputArg> &Outs,
2073 const SmallVectorImpl<SDValue> &OutVals,
2074 SDLoc dl, SelectionDAG &DAG) const {
2076 // CCValAssign - represent the assignment of the return value to a location.
2077 SmallVector<CCValAssign, 16> RVLocs;
2079 // CCState - Info about the registers and stack slots.
2080 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2081 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2083 // Analyze outgoing return values.
2084 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2088 SmallVector<SDValue, 4> RetOps;
2089 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2090 bool isLittleEndian = Subtarget->isLittle();
2092 // Copy the result values into the output registers.
2093 for (unsigned i = 0, realRVLocIdx = 0;
2095 ++i, ++realRVLocIdx) {
2096 CCValAssign &VA = RVLocs[i];
2097 assert(VA.isRegLoc() && "Can only return in registers!");
2099 SDValue Arg = OutVals[realRVLocIdx];
2101 switch (VA.getLocInfo()) {
2102 default: llvm_unreachable("Unknown loc info!");
2103 case CCValAssign::Full: break;
2104 case CCValAssign::BCvt:
2105 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2109 if (VA.needsCustom()) {
2110 if (VA.getLocVT() == MVT::v2f64) {
2111 // Extract the first half and return it in two registers.
2112 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2113 DAG.getConstant(0, MVT::i32));
2114 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2115 DAG.getVTList(MVT::i32, MVT::i32), Half);
2117 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2118 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2120 Flag = Chain.getValue(1);
2121 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2122 VA = RVLocs[++i]; // skip ahead to next loc
2123 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2124 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2126 Flag = Chain.getValue(1);
2127 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2128 VA = RVLocs[++i]; // skip ahead to next loc
2130 // Extract the 2nd half and fall through to handle it as an f64 value.
2131 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2132 DAG.getConstant(1, MVT::i32));
2134 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2136 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2137 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2138 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2139 fmrrd.getValue(isLittleEndian ? 0 : 1),
2141 Flag = Chain.getValue(1);
2142 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2143 VA = RVLocs[++i]; // skip ahead to next loc
2144 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2145 fmrrd.getValue(isLittleEndian ? 1 : 0),
2148 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2150 // Guarantee that all emitted copies are
2151 // stuck together, avoiding something bad.
2152 Flag = Chain.getValue(1);
2153 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2156 // Update chain and glue.
2159 RetOps.push_back(Flag);
2161 // CPUs which aren't M-class use a special sequence to return from
2162 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2163 // though we use "subs pc, lr, #N").
2165 // M-class CPUs actually use a normal return sequence with a special
2166 // (hardware-provided) value in LR, so the normal code path works.
2167 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2168 !Subtarget->isMClass()) {
2169 if (Subtarget->isThumb1Only())
2170 report_fatal_error("interrupt attribute is not supported in Thumb1");
2171 return LowerInterruptReturn(RetOps, dl, DAG);
2174 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2177 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2178 if (N->getNumValues() != 1)
2180 if (!N->hasNUsesOfValue(1, 0))
2183 SDValue TCChain = Chain;
2184 SDNode *Copy = *N->use_begin();
2185 if (Copy->getOpcode() == ISD::CopyToReg) {
2186 // If the copy has a glue operand, we conservatively assume it isn't safe to
2187 // perform a tail call.
2188 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2190 TCChain = Copy->getOperand(0);
2191 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2192 SDNode *VMov = Copy;
2193 // f64 returned in a pair of GPRs.
2194 SmallPtrSet<SDNode*, 2> Copies;
2195 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2197 if (UI->getOpcode() != ISD::CopyToReg)
2201 if (Copies.size() > 2)
2204 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2206 SDValue UseChain = UI->getOperand(0);
2207 if (Copies.count(UseChain.getNode()))
2214 } else if (Copy->getOpcode() == ISD::BITCAST) {
2215 // f32 returned in a single GPR.
2216 if (!Copy->hasOneUse())
2218 Copy = *Copy->use_begin();
2219 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2221 TCChain = Copy->getOperand(0);
2226 bool HasRet = false;
2227 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2229 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2230 UI->getOpcode() != ARMISD::INTRET_FLAG)
2242 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2243 if (!Subtarget->supportsTailCall())
2246 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2249 return !Subtarget->isThumb1Only();
2252 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2253 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2254 // one of the above mentioned nodes. It has to be wrapped because otherwise
2255 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2256 // be used to form addressing mode. These wrapped nodes will be selected
2258 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2259 EVT PtrVT = Op.getValueType();
2260 // FIXME there is no actual debug info here
2262 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2264 if (CP->isMachineConstantPoolEntry())
2265 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2266 CP->getAlignment());
2268 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2269 CP->getAlignment());
2270 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2273 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2274 return MachineJumpTableInfo::EK_Inline;
2277 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2278 SelectionDAG &DAG) const {
2279 MachineFunction &MF = DAG.getMachineFunction();
2280 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2281 unsigned ARMPCLabelIndex = 0;
2283 EVT PtrVT = getPointerTy();
2284 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2285 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2287 if (RelocM == Reloc::Static) {
2288 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2290 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2291 ARMPCLabelIndex = AFI->createPICLabelUId();
2292 ARMConstantPoolValue *CPV =
2293 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2294 ARMCP::CPBlockAddress, PCAdj);
2295 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2297 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2298 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2299 MachinePointerInfo::getConstantPool(),
2300 false, false, false, 0);
2301 if (RelocM == Reloc::Static)
2303 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2304 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2307 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2309 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2310 SelectionDAG &DAG) const {
2312 EVT PtrVT = getPointerTy();
2313 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2314 MachineFunction &MF = DAG.getMachineFunction();
2315 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2316 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2317 ARMConstantPoolValue *CPV =
2318 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2319 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2320 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2321 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2322 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2323 MachinePointerInfo::getConstantPool(),
2324 false, false, false, 0);
2325 SDValue Chain = Argument.getValue(1);
2327 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2328 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2330 // call __tls_get_addr.
2333 Entry.Node = Argument;
2334 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2335 Args.push_back(Entry);
2336 // FIXME: is there useful debug info available here?
2337 TargetLowering::CallLoweringInfo CLI(Chain,
2338 (Type *) Type::getInt32Ty(*DAG.getContext()),
2339 false, false, false, false,
2340 0, CallingConv::C, /*isTailCall=*/false,
2341 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2342 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2343 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2344 return CallResult.first;
2347 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2348 // "local exec" model.
2350 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2352 TLSModel::Model model) const {
2353 const GlobalValue *GV = GA->getGlobal();
2356 SDValue Chain = DAG.getEntryNode();
2357 EVT PtrVT = getPointerTy();
2358 // Get the Thread Pointer
2359 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2361 if (model == TLSModel::InitialExec) {
2362 MachineFunction &MF = DAG.getMachineFunction();
2363 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2364 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2365 // Initial exec model.
2366 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2367 ARMConstantPoolValue *CPV =
2368 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2369 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2371 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2372 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2373 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2374 MachinePointerInfo::getConstantPool(),
2375 false, false, false, 0);
2376 Chain = Offset.getValue(1);
2378 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2379 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2381 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2382 MachinePointerInfo::getConstantPool(),
2383 false, false, false, 0);
2386 assert(model == TLSModel::LocalExec);
2387 ARMConstantPoolValue *CPV =
2388 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2389 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2390 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2391 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2392 MachinePointerInfo::getConstantPool(),
2393 false, false, false, 0);
2396 // The address of the thread local variable is the add of the thread
2397 // pointer with the offset of the variable.
2398 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2402 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2403 // TODO: implement the "local dynamic" model
2404 assert(Subtarget->isTargetELF() &&
2405 "TLS not implemented for non-ELF targets");
2406 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2408 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2411 case TLSModel::GeneralDynamic:
2412 case TLSModel::LocalDynamic:
2413 return LowerToTLSGeneralDynamicModel(GA, DAG);
2414 case TLSModel::InitialExec:
2415 case TLSModel::LocalExec:
2416 return LowerToTLSExecModels(GA, DAG, model);
2418 llvm_unreachable("bogus TLS model");
2421 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2422 SelectionDAG &DAG) const {
2423 EVT PtrVT = getPointerTy();
2425 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2426 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2427 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2428 ARMConstantPoolValue *CPV =
2429 ARMConstantPoolConstant::Create(GV,
2430 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2431 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2432 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2433 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2435 MachinePointerInfo::getConstantPool(),
2436 false, false, false, 0);
2437 SDValue Chain = Result.getValue(1);
2438 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2439 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2441 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2442 MachinePointerInfo::getGOT(),
2443 false, false, false, 0);
2447 // If we have T2 ops, we can materialize the address directly via movt/movw
2448 // pair. This is always cheaper.
2449 if (Subtarget->useMovt()) {
2451 // FIXME: Once remat is capable of dealing with instructions with register
2452 // operands, expand this into two nodes.
2453 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2454 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2456 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2457 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2458 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2459 MachinePointerInfo::getConstantPool(),
2460 false, false, false, 0);
2464 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2465 SelectionDAG &DAG) const {
2466 EVT PtrVT = getPointerTy();
2468 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2469 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2471 if (Subtarget->useMovt())
2474 // FIXME: Once remat is capable of dealing with instructions with register
2475 // operands, expand this into multiple nodes
2477 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2479 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2480 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2482 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2483 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2484 MachinePointerInfo::getGOT(), false, false, false, 0);
2488 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2489 SelectionDAG &DAG) const {
2490 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2491 assert(Subtarget->useMovt() && "Windows on ARM expects to use movw/movt");
2493 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2494 EVT PtrVT = getPointerTy();
2499 // FIXME: Once remat is capable of dealing with instructions with register
2500 // operands, expand this into two nodes.
2501 return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2502 DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2505 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2506 SelectionDAG &DAG) const {
2507 assert(Subtarget->isTargetELF() &&
2508 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2509 MachineFunction &MF = DAG.getMachineFunction();
2510 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2511 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2512 EVT PtrVT = getPointerTy();
2514 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2515 ARMConstantPoolValue *CPV =
2516 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2517 ARMPCLabelIndex, PCAdj);
2518 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2519 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2520 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2521 MachinePointerInfo::getConstantPool(),
2522 false, false, false, 0);
2523 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2524 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2528 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2530 SDValue Val = DAG.getConstant(0, MVT::i32);
2531 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2532 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2533 Op.getOperand(1), Val);
2537 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2539 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2540 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2544 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2545 const ARMSubtarget *Subtarget) const {
2546 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2549 default: return SDValue(); // Don't custom lower most intrinsics.
2550 case Intrinsic::arm_thread_pointer: {
2551 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2552 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2554 case Intrinsic::eh_sjlj_lsda: {
2555 MachineFunction &MF = DAG.getMachineFunction();
2556 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2557 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2558 EVT PtrVT = getPointerTy();
2559 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2561 unsigned PCAdj = (RelocM != Reloc::PIC_)
2562 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2563 ARMConstantPoolValue *CPV =
2564 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2565 ARMCP::CPLSDA, PCAdj);
2566 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2567 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2569 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2570 MachinePointerInfo::getConstantPool(),
2571 false, false, false, 0);
2573 if (RelocM == Reloc::PIC_) {
2574 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2575 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2579 case Intrinsic::arm_neon_vmulls:
2580 case Intrinsic::arm_neon_vmullu: {
2581 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2582 ? ARMISD::VMULLs : ARMISD::VMULLu;
2583 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2584 Op.getOperand(1), Op.getOperand(2));
2589 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2590 const ARMSubtarget *Subtarget) {
2591 // FIXME: handle "fence singlethread" more efficiently.
2593 if (!Subtarget->hasDataBarrier()) {
2594 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2595 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2597 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2598 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2599 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2600 DAG.getConstant(0, MVT::i32));
2603 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2604 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2605 unsigned Domain = ARM_MB::ISH;
2606 if (Subtarget->isMClass()) {
2607 // Only a full system barrier exists in the M-class architectures.
2608 Domain = ARM_MB::SY;
2609 } else if (Subtarget->isSwift() && Ord == Release) {
2610 // Swift happens to implement ISHST barriers in a way that's compatible with
2611 // Release semantics but weaker than ISH so we'd be fools not to use
2612 // it. Beware: other processors probably don't!
2613 Domain = ARM_MB::ISHST;
2616 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2617 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2618 DAG.getConstant(Domain, MVT::i32));
2621 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2622 const ARMSubtarget *Subtarget) {
2623 // ARM pre v5TE and Thumb1 does not have preload instructions.
2624 if (!(Subtarget->isThumb2() ||
2625 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2626 // Just preserve the chain.
2627 return Op.getOperand(0);
2630 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2632 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2633 // ARMv7 with MP extension has PLDW.
2634 return Op.getOperand(0);
2636 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2637 if (Subtarget->isThumb()) {
2639 isRead = ~isRead & 1;
2640 isData = ~isData & 1;
2643 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2644 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2645 DAG.getConstant(isData, MVT::i32));
2648 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2649 MachineFunction &MF = DAG.getMachineFunction();
2650 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2652 // vastart just stores the address of the VarArgsFrameIndex slot into the
2653 // memory location argument.
2655 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2656 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2657 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2658 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2659 MachinePointerInfo(SV), false, false, 0);
2663 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2664 SDValue &Root, SelectionDAG &DAG,
2666 MachineFunction &MF = DAG.getMachineFunction();
2667 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2669 const TargetRegisterClass *RC;
2670 if (AFI->isThumb1OnlyFunction())
2671 RC = &ARM::tGPRRegClass;
2673 RC = &ARM::GPRRegClass;
2675 // Transform the arguments stored in physical registers into virtual ones.
2676 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2677 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2680 if (NextVA.isMemLoc()) {
2681 MachineFrameInfo *MFI = MF.getFrameInfo();
2682 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2684 // Create load node to retrieve arguments from the stack.
2685 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2686 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2687 MachinePointerInfo::getFixedStack(FI),
2688 false, false, false, 0);
2690 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2691 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2693 if (!Subtarget->isLittle())
2694 std::swap (ArgValue, ArgValue2);
2695 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2699 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2700 unsigned InRegsParamRecordIdx,
2702 unsigned &ArgRegsSize,
2703 unsigned &ArgRegsSaveSize)
2706 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2707 unsigned RBegin, REnd;
2708 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2709 NumGPRs = REnd - RBegin;
2711 unsigned int firstUnalloced;
2712 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2713 sizeof(GPRArgRegs) /
2714 sizeof(GPRArgRegs[0]));
2715 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2718 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2719 ArgRegsSize = NumGPRs * 4;
2721 // If parameter is split between stack and GPRs...
2722 if (NumGPRs && Align > 4 &&
2723 (ArgRegsSize < ArgSize ||
2724 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2725 // Add padding for part of param recovered from GPRs. For example,
2726 // if Align == 8, its last byte must be at address K*8 - 1.
2727 // We need to do it, since remained (stack) part of parameter has
2728 // stack alignment, and we need to "attach" "GPRs head" without gaps
2731 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2732 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2734 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2736 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2737 ArgRegsSaveSize = ArgRegsSize + Padding;
2739 // We don't need to extend regs save size for byval parameters if they
2740 // are passed via GPRs only.
2741 ArgRegsSaveSize = ArgRegsSize;
2744 // The remaining GPRs hold either the beginning of variable-argument
2745 // data, or the beginning of an aggregate passed by value (usually
2746 // byval). Either way, we allocate stack slots adjacent to the data
2747 // provided by our caller, and store the unallocated registers there.
2748 // If this is a variadic function, the va_list pointer will begin with
2749 // these values; otherwise, this reassembles a (byval) structure that
2750 // was split between registers and memory.
2751 // Return: The frame index registers were stored into.
2753 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2754 SDLoc dl, SDValue &Chain,
2755 const Value *OrigArg,
2756 unsigned InRegsParamRecordIdx,
2757 unsigned OffsetFromOrigArg,
2761 unsigned ByValStoreOffset,
2762 unsigned TotalArgRegsSaveSize) const {
2764 // Currently, two use-cases possible:
2765 // Case #1. Non-var-args function, and we meet first byval parameter.
2766 // Setup first unallocated register as first byval register;
2767 // eat all remained registers
2768 // (these two actions are performed by HandleByVal method).
2769 // Then, here, we initialize stack frame with
2770 // "store-reg" instructions.
2771 // Case #2. Var-args function, that doesn't contain byval parameters.
2772 // The same: eat all remained unallocated registers,
2773 // initialize stack frame.
2775 MachineFunction &MF = DAG.getMachineFunction();
2776 MachineFrameInfo *MFI = MF.getFrameInfo();
2777 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2778 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2779 unsigned RBegin, REnd;
2780 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2781 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2782 firstRegToSaveIndex = RBegin - ARM::R0;
2783 lastRegToSaveIndex = REnd - ARM::R0;
2785 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2786 (GPRArgRegs, array_lengthof(GPRArgRegs));
2787 lastRegToSaveIndex = 4;
2790 unsigned ArgRegsSize, ArgRegsSaveSize;
2791 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2792 ArgRegsSize, ArgRegsSaveSize);
2794 // Store any by-val regs to their spots on the stack so that they may be
2795 // loaded by deferencing the result of formal parameter pointer or va_next.
2796 // Note: once stack area for byval/varargs registers
2797 // was initialized, it can't be initialized again.
2798 if (ArgRegsSaveSize) {
2799 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2802 assert(AFI->getStoredByValParamsPadding() == 0 &&
2803 "The only parameter may be padded.");
2804 AFI->setStoredByValParamsPadding(Padding);
2807 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2810 (int64_t)TotalArgRegsSaveSize,
2812 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2814 MFI->CreateFixedObject(Padding,
2815 ArgOffset + ByValStoreOffset -
2816 (int64_t)ArgRegsSaveSize,
2820 SmallVector<SDValue, 4> MemOps;
2821 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2822 ++firstRegToSaveIndex, ++i) {
2823 const TargetRegisterClass *RC;
2824 if (AFI->isThumb1OnlyFunction())
2825 RC = &ARM::tGPRRegClass;
2827 RC = &ARM::GPRRegClass;
2829 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2830 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2832 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2833 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2835 MemOps.push_back(Store);
2836 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2837 DAG.getConstant(4, getPointerTy()));
2840 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2842 if (!MemOps.empty())
2843 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2847 // We cannot allocate a zero-byte object for the first variadic argument,
2848 // so just make up a size.
2851 // This will point to the next argument passed via stack.
2852 return MFI->CreateFixedObject(
2853 ArgSize, ArgOffset, !ForceMutable);
2857 // Setup stack frame, the va_list pointer will start from.
2859 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2860 SDLoc dl, SDValue &Chain,
2862 unsigned TotalArgRegsSaveSize,
2863 bool ForceMutable) const {
2864 MachineFunction &MF = DAG.getMachineFunction();
2865 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2867 // Try to store any remaining integer argument regs
2868 // to their spots on the stack so that they may be loaded by deferencing
2869 // the result of va_next.
2870 // If there is no regs to be stored, just point address after last
2871 // argument passed via stack.
2873 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2874 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2875 0, TotalArgRegsSaveSize);
2877 AFI->setVarArgsFrameIndex(FrameIndex);
2881 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2882 CallingConv::ID CallConv, bool isVarArg,
2883 const SmallVectorImpl<ISD::InputArg>
2885 SDLoc dl, SelectionDAG &DAG,
2886 SmallVectorImpl<SDValue> &InVals)
2888 MachineFunction &MF = DAG.getMachineFunction();
2889 MachineFrameInfo *MFI = MF.getFrameInfo();
2891 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2893 // Assign locations to all of the incoming arguments.
2894 SmallVector<CCValAssign, 16> ArgLocs;
2895 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2896 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2897 CCInfo.AnalyzeFormalArguments(Ins,
2898 CCAssignFnForNode(CallConv, /* Return*/ false,
2901 SmallVector<SDValue, 16> ArgValues;
2902 int lastInsIndex = -1;
2904 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2905 unsigned CurArgIdx = 0;
2907 // Initially ArgRegsSaveSize is zero.
2908 // Then we increase this value each time we meet byval parameter.
2909 // We also increase this value in case of varargs function.
2910 AFI->setArgRegsSaveSize(0);
2912 unsigned ByValStoreOffset = 0;
2913 unsigned TotalArgRegsSaveSize = 0;
2914 unsigned ArgRegsSaveSizeMaxAlign = 4;
2916 // Calculate the amount of stack space that we need to allocate to store
2917 // byval and variadic arguments that are passed in registers.
2918 // We need to know this before we allocate the first byval or variadic
2919 // argument, as they will be allocated a stack slot below the CFA (Canonical
2920 // Frame Address, the stack pointer at entry to the function).
2921 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2922 CCValAssign &VA = ArgLocs[i];
2923 if (VA.isMemLoc()) {
2924 int index = VA.getValNo();
2925 if (index != lastInsIndex) {
2926 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2927 if (Flags.isByVal()) {
2928 unsigned ExtraArgRegsSize;
2929 unsigned ExtraArgRegsSaveSize;
2930 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2931 Flags.getByValSize(),
2932 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2934 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2935 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2936 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2937 CCInfo.nextInRegsParam();
2939 lastInsIndex = index;
2943 CCInfo.rewindByValRegsInfo();
2946 unsigned ExtraArgRegsSize;
2947 unsigned ExtraArgRegsSaveSize;
2948 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2949 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2950 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2952 // If the arg regs save area contains N-byte aligned values, the
2953 // bottom of it must be at least N-byte aligned.
2954 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2955 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2957 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2958 CCValAssign &VA = ArgLocs[i];
2959 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2960 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2961 // Arguments stored in registers.
2962 if (VA.isRegLoc()) {
2963 EVT RegVT = VA.getLocVT();
2965 if (VA.needsCustom()) {
2966 // f64 and vector types are split up into multiple registers or
2967 // combinations of registers and stack slots.
2968 if (VA.getLocVT() == MVT::v2f64) {
2969 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2971 VA = ArgLocs[++i]; // skip ahead to next loc
2973 if (VA.isMemLoc()) {
2974 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2975 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2976 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2977 MachinePointerInfo::getFixedStack(FI),
2978 false, false, false, 0);
2980 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2983 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2984 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2985 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2986 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2987 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2989 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2992 const TargetRegisterClass *RC;
2994 if (RegVT == MVT::f32)
2995 RC = &ARM::SPRRegClass;
2996 else if (RegVT == MVT::f64)
2997 RC = &ARM::DPRRegClass;
2998 else if (RegVT == MVT::v2f64)
2999 RC = &ARM::QPRRegClass;
3000 else if (RegVT == MVT::i32)
3001 RC = AFI->isThumb1OnlyFunction() ?
3002 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3003 (const TargetRegisterClass*)&ARM::GPRRegClass;
3005 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3007 // Transform the arguments in physical registers into virtual ones.
3008 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3009 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3012 // If this is an 8 or 16-bit value, it is really passed promoted
3013 // to 32 bits. Insert an assert[sz]ext to capture this, then
3014 // truncate to the right size.
3015 switch (VA.getLocInfo()) {
3016 default: llvm_unreachable("Unknown loc info!");
3017 case CCValAssign::Full: break;
3018 case CCValAssign::BCvt:
3019 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3021 case CCValAssign::SExt:
3022 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3023 DAG.getValueType(VA.getValVT()));
3024 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3026 case CCValAssign::ZExt:
3027 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3028 DAG.getValueType(VA.getValVT()));
3029 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3033 InVals.push_back(ArgValue);
3035 } else { // VA.isRegLoc()
3038 assert(VA.isMemLoc());
3039 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3041 int index = ArgLocs[i].getValNo();
3043 // Some Ins[] entries become multiple ArgLoc[] entries.
3044 // Process them only once.
3045 if (index != lastInsIndex)
3047 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3048 // FIXME: For now, all byval parameter objects are marked mutable.
3049 // This can be changed with more analysis.
3050 // In case of tail call optimization mark all arguments mutable.
3051 // Since they could be overwritten by lowering of arguments in case of
3053 if (Flags.isByVal()) {
3054 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3056 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3057 int FrameIndex = StoreByValRegs(
3058 CCInfo, DAG, dl, Chain, CurOrigArg,
3060 Ins[VA.getValNo()].PartOffset,
3061 VA.getLocMemOffset(),
3062 Flags.getByValSize(),
3063 true /*force mutable frames*/,
3065 TotalArgRegsSaveSize);
3066 ByValStoreOffset += Flags.getByValSize();
3067 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3068 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3069 CCInfo.nextInRegsParam();
3071 unsigned FIOffset = VA.getLocMemOffset();
3072 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3075 // Create load nodes to retrieve arguments from the stack.
3076 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3077 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3078 MachinePointerInfo::getFixedStack(FI),
3079 false, false, false, 0));
3081 lastInsIndex = index;
3088 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3089 CCInfo.getNextStackOffset(),
3090 TotalArgRegsSaveSize);
3092 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3097 /// isFloatingPointZero - Return true if this is +0.0.
3098 static bool isFloatingPointZero(SDValue Op) {
3099 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3100 return CFP->getValueAPF().isPosZero();
3101 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3102 // Maybe this has already been legalized into the constant pool?
3103 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3104 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3105 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3106 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3107 return CFP->getValueAPF().isPosZero();
3113 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3114 /// the given operands.
3116 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3117 SDValue &ARMcc, SelectionDAG &DAG,
3119 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3120 unsigned C = RHSC->getZExtValue();
3121 if (!isLegalICmpImmediate(C)) {
3122 // Constant does not fit, try adjusting it by one?
3127 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3128 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3129 RHS = DAG.getConstant(C-1, MVT::i32);
3134 if (C != 0 && isLegalICmpImmediate(C-1)) {
3135 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3136 RHS = DAG.getConstant(C-1, MVT::i32);
3141 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3142 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3143 RHS = DAG.getConstant(C+1, MVT::i32);
3148 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3149 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3150 RHS = DAG.getConstant(C+1, MVT::i32);
3157 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3158 ARMISD::NodeType CompareType;
3161 CompareType = ARMISD::CMP;
3166 CompareType = ARMISD::CMPZ;
3169 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3170 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3173 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3175 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3178 if (!isFloatingPointZero(RHS))
3179 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3181 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3182 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3185 /// duplicateCmp - Glue values can have only one use, so this function
3186 /// duplicates a comparison node.
3188 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3189 unsigned Opc = Cmp.getOpcode();
3191 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3192 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3194 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3195 Cmp = Cmp.getOperand(0);
3196 Opc = Cmp.getOpcode();
3197 if (Opc == ARMISD::CMPFP)
3198 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3200 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3201 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3203 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3206 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3207 SDValue Cond = Op.getOperand(0);
3208 SDValue SelectTrue = Op.getOperand(1);
3209 SDValue SelectFalse = Op.getOperand(2);
3214 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3215 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3217 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3218 const ConstantSDNode *CMOVTrue =
3219 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3220 const ConstantSDNode *CMOVFalse =
3221 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3223 if (CMOVTrue && CMOVFalse) {
3224 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3225 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3229 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3231 False = SelectFalse;
3232 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3237 if (True.getNode() && False.getNode()) {
3238 EVT VT = Op.getValueType();
3239 SDValue ARMcc = Cond.getOperand(2);
3240 SDValue CCR = Cond.getOperand(3);
3241 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3242 assert(True.getValueType() == VT);
3243 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3248 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3249 // undefined bits before doing a full-word comparison with zero.
3250 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3251 DAG.getConstant(1, Cond.getValueType()));
3253 return DAG.getSelectCC(dl, Cond,
3254 DAG.getConstant(0, Cond.getValueType()),
3255 SelectTrue, SelectFalse, ISD::SETNE);
3258 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3259 if (CC == ISD::SETNE)
3261 return ISD::getSetCCInverse(CC, true);
3264 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3265 bool &swpCmpOps, bool &swpVselOps) {
3266 // Start by selecting the GE condition code for opcodes that return true for
3268 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3270 CondCode = ARMCC::GE;
3272 // and GT for opcodes that return false for 'equality'.
3273 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3275 CondCode = ARMCC::GT;
3277 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3278 // to swap the compare operands.
3279 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3283 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3284 // If we have an unordered opcode, we need to swap the operands to the VSEL
3285 // instruction (effectively negating the condition).
3287 // This also has the effect of swapping which one of 'less' or 'greater'
3288 // returns true, so we also swap the compare operands. It also switches
3289 // whether we return true for 'equality', so we compensate by picking the
3290 // opposite condition code to our original choice.
3291 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3292 CC == ISD::SETUGT) {
3293 swpCmpOps = !swpCmpOps;
3294 swpVselOps = !swpVselOps;
3295 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3298 // 'ordered' is 'anything but unordered', so use the VS condition code and
3299 // swap the VSEL operands.
3300 if (CC == ISD::SETO) {
3301 CondCode = ARMCC::VS;
3305 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3306 // code and swap the VSEL operands.
3307 if (CC == ISD::SETUNE) {
3308 CondCode = ARMCC::EQ;
3313 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3314 EVT VT = Op.getValueType();
3315 SDValue LHS = Op.getOperand(0);
3316 SDValue RHS = Op.getOperand(1);
3317 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3318 SDValue TrueVal = Op.getOperand(2);
3319 SDValue FalseVal = Op.getOperand(3);
3322 if (LHS.getValueType() == MVT::i32) {
3323 // Try to generate VSEL on ARMv8.
3324 // The VSEL instruction can't use all the usual ARM condition
3325 // codes: it only has two bits to select the condition code, so it's
3326 // constrained to use only GE, GT, VS and EQ.
3328 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3329 // swap the operands of the previous compare instruction (effectively
3330 // inverting the compare condition, swapping 'less' and 'greater') and
3331 // sometimes need to swap the operands to the VSEL (which inverts the
3332 // condition in the sense of firing whenever the previous condition didn't)
3333 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3334 TrueVal.getValueType() == MVT::f64)) {
3335 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3336 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3337 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3338 CC = getInverseCCForVSEL(CC);
3339 std::swap(TrueVal, FalseVal);
3344 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3345 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3346 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3350 ARMCC::CondCodes CondCode, CondCode2;
3351 FPCCToARMCC(CC, CondCode, CondCode2);
3353 // Try to generate VSEL on ARMv8.
3354 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3355 TrueVal.getValueType() == MVT::f64)) {
3356 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3357 // same operands, as follows:
3358 // c = fcmp [ogt, olt, ugt, ult] a, b
3360 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3361 // handled differently than the original code sequence.
3362 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3364 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3365 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3366 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3367 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3370 bool swpCmpOps = false;
3371 bool swpVselOps = false;
3372 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3374 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3375 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3377 std::swap(LHS, RHS);
3379 std::swap(TrueVal, FalseVal);
3383 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3384 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3385 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3386 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3388 if (CondCode2 != ARMCC::AL) {
3389 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3390 // FIXME: Needs another CMP because flag can have but one use.
3391 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3392 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3393 Result, TrueVal, ARMcc2, CCR, Cmp2);
3398 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3399 /// to morph to an integer compare sequence.
3400 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3401 const ARMSubtarget *Subtarget) {
3402 SDNode *N = Op.getNode();
3403 if (!N->hasOneUse())
3404 // Otherwise it requires moving the value from fp to integer registers.
3406 if (!N->getNumValues())
3408 EVT VT = Op.getValueType();
3409 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3410 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3411 // vmrs are very slow, e.g. cortex-a8.
3414 if (isFloatingPointZero(Op)) {
3418 return ISD::isNormalLoad(N);
3421 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3422 if (isFloatingPointZero(Op))
3423 return DAG.getConstant(0, MVT::i32);
3425 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3426 return DAG.getLoad(MVT::i32, SDLoc(Op),
3427 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3428 Ld->isVolatile(), Ld->isNonTemporal(),
3429 Ld->isInvariant(), Ld->getAlignment());
3431 llvm_unreachable("Unknown VFP cmp argument!");
3434 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3435 SDValue &RetVal1, SDValue &RetVal2) {
3436 if (isFloatingPointZero(Op)) {
3437 RetVal1 = DAG.getConstant(0, MVT::i32);
3438 RetVal2 = DAG.getConstant(0, MVT::i32);
3442 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3443 SDValue Ptr = Ld->getBasePtr();
3444 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3445 Ld->getChain(), Ptr,
3446 Ld->getPointerInfo(),
3447 Ld->isVolatile(), Ld->isNonTemporal(),
3448 Ld->isInvariant(), Ld->getAlignment());
3450 EVT PtrType = Ptr.getValueType();
3451 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3452 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3453 PtrType, Ptr, DAG.getConstant(4, PtrType));
3454 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3455 Ld->getChain(), NewPtr,
3456 Ld->getPointerInfo().getWithOffset(4),
3457 Ld->isVolatile(), Ld->isNonTemporal(),
3458 Ld->isInvariant(), NewAlign);
3462 llvm_unreachable("Unknown VFP cmp argument!");
3465 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3466 /// f32 and even f64 comparisons to integer ones.
3468 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3469 SDValue Chain = Op.getOperand(0);
3470 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3471 SDValue LHS = Op.getOperand(2);
3472 SDValue RHS = Op.getOperand(3);
3473 SDValue Dest = Op.getOperand(4);
3476 bool LHSSeenZero = false;
3477 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3478 bool RHSSeenZero = false;
3479 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3480 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3481 // If unsafe fp math optimization is enabled and there are no other uses of
3482 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3483 // to an integer comparison.
3484 if (CC == ISD::SETOEQ)
3486 else if (CC == ISD::SETUNE)
3489 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3491 if (LHS.getValueType() == MVT::f32) {
3492 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3493 bitcastf32Toi32(LHS, DAG), Mask);
3494 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3495 bitcastf32Toi32(RHS, DAG), Mask);
3496 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3497 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3498 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3499 Chain, Dest, ARMcc, CCR, Cmp);
3504 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3505 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3506 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3507 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3508 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3509 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3510 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3511 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3512 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3518 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3519 SDValue Chain = Op.getOperand(0);
3520 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3521 SDValue LHS = Op.getOperand(2);
3522 SDValue RHS = Op.getOperand(3);
3523 SDValue Dest = Op.getOperand(4);
3526 if (LHS.getValueType() == MVT::i32) {
3528 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3529 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3530 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3531 Chain, Dest, ARMcc, CCR, Cmp);
3534 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3536 if (getTargetMachine().Options.UnsafeFPMath &&
3537 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3538 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3539 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3540 if (Result.getNode())
3544 ARMCC::CondCodes CondCode, CondCode2;
3545 FPCCToARMCC(CC, CondCode, CondCode2);
3547 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3548 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3549 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3550 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3551 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3552 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3553 if (CondCode2 != ARMCC::AL) {
3554 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3555 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3556 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3561 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3562 SDValue Chain = Op.getOperand(0);
3563 SDValue Table = Op.getOperand(1);
3564 SDValue Index = Op.getOperand(2);
3567 EVT PTy = getPointerTy();
3568 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3569 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3570 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3571 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3572 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3573 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3574 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3575 if (Subtarget->isThumb2()) {
3576 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3577 // which does another jump to the destination. This also makes it easier
3578 // to translate it to TBB / TBH later.
3579 // FIXME: This might not work if the function is extremely large.
3580 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3581 Addr, Op.getOperand(2), JTI, UId);
3583 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3584 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3585 MachinePointerInfo::getJumpTable(),
3586 false, false, false, 0);
3587 Chain = Addr.getValue(1);
3588 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3589 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3591 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3592 MachinePointerInfo::getJumpTable(),
3593 false, false, false, 0);
3594 Chain = Addr.getValue(1);
3595 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3599 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3600 EVT VT = Op.getValueType();
3603 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3604 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3606 return DAG.UnrollVectorOp(Op.getNode());
3609 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3610 "Invalid type for custom lowering!");
3611 if (VT != MVT::v4i16)
3612 return DAG.UnrollVectorOp(Op.getNode());
3614 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3615 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3618 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3619 EVT VT = Op.getValueType();
3621 return LowerVectorFP_TO_INT(Op, DAG);
3626 switch (Op.getOpcode()) {
3627 default: llvm_unreachable("Invalid opcode!");
3628 case ISD::FP_TO_SINT:
3629 Opc = ARMISD::FTOSI;
3631 case ISD::FP_TO_UINT:
3632 Opc = ARMISD::FTOUI;
3635 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3636 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3639 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3640 EVT VT = Op.getValueType();
3643 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3644 if (VT.getVectorElementType() == MVT::f32)
3646 return DAG.UnrollVectorOp(Op.getNode());
3649 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3650 "Invalid type for custom lowering!");
3651 if (VT != MVT::v4f32)
3652 return DAG.UnrollVectorOp(Op.getNode());
3656 switch (Op.getOpcode()) {
3657 default: llvm_unreachable("Invalid opcode!");
3658 case ISD::SINT_TO_FP:
3659 CastOpc = ISD::SIGN_EXTEND;
3660 Opc = ISD::SINT_TO_FP;
3662 case ISD::UINT_TO_FP:
3663 CastOpc = ISD::ZERO_EXTEND;
3664 Opc = ISD::UINT_TO_FP;
3668 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3669 return DAG.getNode(Opc, dl, VT, Op);
3672 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3673 EVT VT = Op.getValueType();
3675 return LowerVectorINT_TO_FP(Op, DAG);
3680 switch (Op.getOpcode()) {
3681 default: llvm_unreachable("Invalid opcode!");
3682 case ISD::SINT_TO_FP:
3683 Opc = ARMISD::SITOF;
3685 case ISD::UINT_TO_FP:
3686 Opc = ARMISD::UITOF;
3690 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3691 return DAG.getNode(Opc, dl, VT, Op);
3694 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3695 // Implement fcopysign with a fabs and a conditional fneg.
3696 SDValue Tmp0 = Op.getOperand(0);
3697 SDValue Tmp1 = Op.getOperand(1);
3699 EVT VT = Op.getValueType();
3700 EVT SrcVT = Tmp1.getValueType();
3701 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3702 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3703 bool UseNEON = !InGPR && Subtarget->hasNEON();
3706 // Use VBSL to copy the sign bit.
3707 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3708 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3709 DAG.getTargetConstant(EncodedVal, MVT::i32));
3710 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3712 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3713 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3714 DAG.getConstant(32, MVT::i32));
3715 else /*if (VT == MVT::f32)*/
3716 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3717 if (SrcVT == MVT::f32) {
3718 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3720 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3721 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3722 DAG.getConstant(32, MVT::i32));
3723 } else if (VT == MVT::f32)
3724 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3725 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3726 DAG.getConstant(32, MVT::i32));
3727 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3728 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3730 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3732 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3733 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3734 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3736 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3737 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3738 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3739 if (VT == MVT::f32) {
3740 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3741 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3742 DAG.getConstant(0, MVT::i32));
3744 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3750 // Bitcast operand 1 to i32.
3751 if (SrcVT == MVT::f64)
3752 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3754 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3756 // Or in the signbit with integer operations.
3757 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3758 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3759 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3760 if (VT == MVT::f32) {
3761 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3762 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3763 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3764 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3767 // f64: Or the high part with signbit and then combine two parts.
3768 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3770 SDValue Lo = Tmp0.getValue(0);
3771 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3772 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3773 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3776 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3777 MachineFunction &MF = DAG.getMachineFunction();
3778 MachineFrameInfo *MFI = MF.getFrameInfo();
3779 MFI->setReturnAddressIsTaken(true);
3781 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3784 EVT VT = Op.getValueType();
3786 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3788 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3789 SDValue Offset = DAG.getConstant(4, MVT::i32);
3790 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3791 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3792 MachinePointerInfo(), false, false, false, 0);
3795 // Return LR, which contains the return address. Mark it an implicit live-in.
3796 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3797 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3800 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3801 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3802 MFI->setFrameAddressIsTaken(true);
3804 EVT VT = Op.getValueType();
3805 SDLoc dl(Op); // FIXME probably not meaningful
3806 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3807 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3808 ? ARM::R7 : ARM::R11;
3809 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3811 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3812 MachinePointerInfo(),
3813 false, false, false, 0);
3817 // FIXME? Maybe this could be a TableGen attribute on some registers and
3818 // this table could be generated automatically from RegInfo.
3819 unsigned ARMTargetLowering::getRegisterByName(const char* RegName) const {
3820 unsigned Reg = StringSwitch<unsigned>(RegName)
3821 .Case("sp", ARM::SP)
3825 report_fatal_error("Invalid register name global variable");
3828 /// ExpandBITCAST - If the target supports VFP, this function is called to
3829 /// expand a bit convert where either the source or destination type is i64 to
3830 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3831 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3832 /// vectors), since the legalizer won't know what to do with that.
3833 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3834 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3836 SDValue Op = N->getOperand(0);
3838 // This function is only supposed to be called for i64 types, either as the
3839 // source or destination of the bit convert.
3840 EVT SrcVT = Op.getValueType();
3841 EVT DstVT = N->getValueType(0);
3842 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3843 "ExpandBITCAST called for non-i64 type");
3845 // Turn i64->f64 into VMOVDRR.
3846 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3847 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3848 DAG.getConstant(0, MVT::i32));
3849 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3850 DAG.getConstant(1, MVT::i32));
3851 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3852 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3855 // Turn f64->i64 into VMOVRRD.
3856 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3857 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3858 DAG.getVTList(MVT::i32, MVT::i32), Op);
3859 // Merge the pieces into a single i64 value.
3860 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3866 /// getZeroVector - Returns a vector of specified type with all zero elements.
3867 /// Zero vectors are used to represent vector negation and in those cases
3868 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3869 /// not support i64 elements, so sometimes the zero vectors will need to be
3870 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3872 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3873 assert(VT.isVector() && "Expected a vector type");
3874 // The canonical modified immediate encoding of a zero vector is....0!
3875 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3876 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3877 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3878 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3881 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3882 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3883 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3884 SelectionDAG &DAG) const {
3885 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3886 EVT VT = Op.getValueType();
3887 unsigned VTBits = VT.getSizeInBits();
3889 SDValue ShOpLo = Op.getOperand(0);
3890 SDValue ShOpHi = Op.getOperand(1);
3891 SDValue ShAmt = Op.getOperand(2);
3893 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3895 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3897 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3898 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3899 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3900 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3901 DAG.getConstant(VTBits, MVT::i32));
3902 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3903 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3904 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3906 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3907 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3909 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3910 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3913 SDValue Ops[2] = { Lo, Hi };
3914 return DAG.getMergeValues(Ops, dl);
3917 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3918 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3919 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3920 SelectionDAG &DAG) const {
3921 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3922 EVT VT = Op.getValueType();
3923 unsigned VTBits = VT.getSizeInBits();
3925 SDValue ShOpLo = Op.getOperand(0);
3926 SDValue ShOpHi = Op.getOperand(1);
3927 SDValue ShAmt = Op.getOperand(2);
3930 assert(Op.getOpcode() == ISD::SHL_PARTS);
3931 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3932 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3933 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3934 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3935 DAG.getConstant(VTBits, MVT::i32));
3936 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3937 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3939 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3940 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3941 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3943 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3944 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3947 SDValue Ops[2] = { Lo, Hi };
3948 return DAG.getMergeValues(Ops, dl);
3951 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3952 SelectionDAG &DAG) const {
3953 // The rounding mode is in bits 23:22 of the FPSCR.
3954 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3955 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3956 // so that the shift + and get folded into a bitfield extract.
3958 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3959 DAG.getConstant(Intrinsic::arm_get_fpscr,
3961 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3962 DAG.getConstant(1U << 22, MVT::i32));
3963 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3964 DAG.getConstant(22, MVT::i32));
3965 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3966 DAG.getConstant(3, MVT::i32));
3969 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3970 const ARMSubtarget *ST) {
3971 EVT VT = N->getValueType(0);
3974 if (!ST->hasV6T2Ops())
3977 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3978 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3981 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3982 /// for each 16-bit element from operand, repeated. The basic idea is to
3983 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3985 /// Trace for v4i16:
3986 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3987 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3988 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3989 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3990 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3991 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3992 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3993 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3994 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3995 EVT VT = N->getValueType(0);
3998 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3999 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4000 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4001 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4002 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4003 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4006 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4007 /// bit-count for each 16-bit element from the operand. We need slightly
4008 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4009 /// 64/128-bit registers.
4011 /// Trace for v4i16:
4012 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4013 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4014 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4015 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4016 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4017 EVT VT = N->getValueType(0);
4020 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4021 if (VT.is64BitVector()) {
4022 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4023 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4024 DAG.getIntPtrConstant(0));
4026 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4027 BitCounts, DAG.getIntPtrConstant(0));
4028 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4032 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4033 /// bit-count for each 32-bit element from the operand. The idea here is
4034 /// to split the vector into 16-bit elements, leverage the 16-bit count
4035 /// routine, and then combine the results.
4037 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4038 /// input = [v0 v1 ] (vi: 32-bit elements)
4039 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4040 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4041 /// vrev: N0 = [k1 k0 k3 k2 ]
4043 /// N1 =+[k1 k0 k3 k2 ]
4045 /// N2 =+[k1 k3 k0 k2 ]
4047 /// Extended =+[k1 k3 k0 k2 ]
4049 /// Extracted=+[k1 k3 ]
4051 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4052 EVT VT = N->getValueType(0);
4055 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4057 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4058 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4059 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4060 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4061 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4063 if (VT.is64BitVector()) {
4064 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4065 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4066 DAG.getIntPtrConstant(0));
4068 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4069 DAG.getIntPtrConstant(0));
4070 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4074 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4075 const ARMSubtarget *ST) {
4076 EVT VT = N->getValueType(0);
4078 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4079 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4080 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4081 "Unexpected type for custom ctpop lowering");
4083 if (VT.getVectorElementType() == MVT::i32)
4084 return lowerCTPOP32BitElements(N, DAG);
4086 return lowerCTPOP16BitElements(N, DAG);
4089 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4090 const ARMSubtarget *ST) {
4091 EVT VT = N->getValueType(0);
4097 // Lower vector shifts on NEON to use VSHL.
4098 assert(ST->hasNEON() && "unexpected vector shift");
4100 // Left shifts translate directly to the vshiftu intrinsic.
4101 if (N->getOpcode() == ISD::SHL)
4102 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4103 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4104 N->getOperand(0), N->getOperand(1));
4106 assert((N->getOpcode() == ISD::SRA ||
4107 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4109 // NEON uses the same intrinsics for both left and right shifts. For
4110 // right shifts, the shift amounts are negative, so negate the vector of
4112 EVT ShiftVT = N->getOperand(1).getValueType();
4113 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4114 getZeroVector(ShiftVT, DAG, dl),
4116 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4117 Intrinsic::arm_neon_vshifts :
4118 Intrinsic::arm_neon_vshiftu);
4119 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4120 DAG.getConstant(vshiftInt, MVT::i32),
4121 N->getOperand(0), NegatedCount);
4124 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4125 const ARMSubtarget *ST) {
4126 EVT VT = N->getValueType(0);
4129 // We can get here for a node like i32 = ISD::SHL i32, i64
4133 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4134 "Unknown shift to lower!");
4136 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4137 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4138 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4141 // If we are in thumb mode, we don't have RRX.
4142 if (ST->isThumb1Only()) return SDValue();
4144 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4145 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4146 DAG.getConstant(0, MVT::i32));
4147 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4148 DAG.getConstant(1, MVT::i32));
4150 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4151 // captures the result into a carry flag.
4152 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4153 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4155 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4156 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4158 // Merge the pieces into a single i64 value.
4159 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4162 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4163 SDValue TmpOp0, TmpOp1;
4164 bool Invert = false;
4168 SDValue Op0 = Op.getOperand(0);
4169 SDValue Op1 = Op.getOperand(1);
4170 SDValue CC = Op.getOperand(2);
4171 EVT VT = Op.getValueType();
4172 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4175 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4176 switch (SetCCOpcode) {
4177 default: llvm_unreachable("Illegal FP comparison");
4179 case ISD::SETNE: Invert = true; // Fallthrough
4181 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4183 case ISD::SETLT: Swap = true; // Fallthrough
4185 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4187 case ISD::SETLE: Swap = true; // Fallthrough
4189 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4190 case ISD::SETUGE: Swap = true; // Fallthrough
4191 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4192 case ISD::SETUGT: Swap = true; // Fallthrough
4193 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4194 case ISD::SETUEQ: Invert = true; // Fallthrough
4196 // Expand this to (OLT | OGT).
4200 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4201 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4203 case ISD::SETUO: Invert = true; // Fallthrough
4205 // Expand this to (OLT | OGE).
4209 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4210 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4214 // Integer comparisons.
4215 switch (SetCCOpcode) {
4216 default: llvm_unreachable("Illegal integer comparison");
4217 case ISD::SETNE: Invert = true;
4218 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4219 case ISD::SETLT: Swap = true;
4220 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4221 case ISD::SETLE: Swap = true;
4222 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4223 case ISD::SETULT: Swap = true;
4224 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4225 case ISD::SETULE: Swap = true;
4226 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4229 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4230 if (Opc == ARMISD::VCEQ) {
4233 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4235 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4238 // Ignore bitconvert.
4239 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4240 AndOp = AndOp.getOperand(0);
4242 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4244 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4245 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4252 std::swap(Op0, Op1);
4254 // If one of the operands is a constant vector zero, attempt to fold the
4255 // comparison to a specialized compare-against-zero form.
4257 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4259 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4260 if (Opc == ARMISD::VCGE)
4261 Opc = ARMISD::VCLEZ;
4262 else if (Opc == ARMISD::VCGT)
4263 Opc = ARMISD::VCLTZ;
4268 if (SingleOp.getNode()) {
4271 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4273 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4275 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4277 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4279 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4281 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4284 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4288 Result = DAG.getNOT(dl, Result, VT);
4293 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4294 /// valid vector constant for a NEON instruction with a "modified immediate"
4295 /// operand (e.g., VMOV). If so, return the encoded value.
4296 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4297 unsigned SplatBitSize, SelectionDAG &DAG,
4298 EVT &VT, bool is128Bits, NEONModImmType type) {
4299 unsigned OpCmode, Imm;
4301 // SplatBitSize is set to the smallest size that splats the vector, so a
4302 // zero vector will always have SplatBitSize == 8. However, NEON modified
4303 // immediate instructions others than VMOV do not support the 8-bit encoding
4304 // of a zero vector, and the default encoding of zero is supposed to be the
4309 switch (SplatBitSize) {
4311 if (type != VMOVModImm)
4313 // Any 1-byte value is OK. Op=0, Cmode=1110.
4314 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4317 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4321 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4322 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4323 if ((SplatBits & ~0xff) == 0) {
4324 // Value = 0x00nn: Op=x, Cmode=100x.
4329 if ((SplatBits & ~0xff00) == 0) {
4330 // Value = 0xnn00: Op=x, Cmode=101x.
4332 Imm = SplatBits >> 8;
4338 // NEON's 32-bit VMOV supports splat values where:
4339 // * only one byte is nonzero, or
4340 // * the least significant byte is 0xff and the second byte is nonzero, or
4341 // * the least significant 2 bytes are 0xff and the third is nonzero.
4342 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4343 if ((SplatBits & ~0xff) == 0) {
4344 // Value = 0x000000nn: Op=x, Cmode=000x.
4349 if ((SplatBits & ~0xff00) == 0) {
4350 // Value = 0x0000nn00: Op=x, Cmode=001x.
4352 Imm = SplatBits >> 8;
4355 if ((SplatBits & ~0xff0000) == 0) {
4356 // Value = 0x00nn0000: Op=x, Cmode=010x.
4358 Imm = SplatBits >> 16;
4361 if ((SplatBits & ~0xff000000) == 0) {
4362 // Value = 0xnn000000: Op=x, Cmode=011x.
4364 Imm = SplatBits >> 24;
4368 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4369 if (type == OtherModImm) return SDValue();
4371 if ((SplatBits & ~0xffff) == 0 &&
4372 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4373 // Value = 0x0000nnff: Op=x, Cmode=1100.
4375 Imm = SplatBits >> 8;
4379 if ((SplatBits & ~0xffffff) == 0 &&
4380 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4381 // Value = 0x00nnffff: Op=x, Cmode=1101.
4383 Imm = SplatBits >> 16;
4387 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4388 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4389 // VMOV.I32. A (very) minor optimization would be to replicate the value
4390 // and fall through here to test for a valid 64-bit splat. But, then the
4391 // caller would also need to check and handle the change in size.
4395 if (type != VMOVModImm)
4397 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4398 uint64_t BitMask = 0xff;
4400 unsigned ImmMask = 1;
4402 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4403 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4406 } else if ((SplatBits & BitMask) != 0) {
4412 // Op=1, Cmode=1110.
4414 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4419 llvm_unreachable("unexpected size for isNEONModifiedImm");
4422 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4423 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4426 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4427 const ARMSubtarget *ST) const {
4431 bool IsDouble = Op.getValueType() == MVT::f64;
4432 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4434 // Try splatting with a VMOV.f32...
4435 APFloat FPVal = CFP->getValueAPF();
4436 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4439 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4440 // We have code in place to select a valid ConstantFP already, no need to
4445 // It's a float and we are trying to use NEON operations where
4446 // possible. Lower it to a splat followed by an extract.
4448 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4449 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4451 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4452 DAG.getConstant(0, MVT::i32));
4455 // The rest of our options are NEON only, make sure that's allowed before
4457 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4461 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4463 // It wouldn't really be worth bothering for doubles except for one very
4464 // important value, which does happen to match: 0.0. So make sure we don't do
4466 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4469 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4470 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4472 if (NewVal != SDValue()) {
4474 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4477 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4479 // It's a float: cast and extract a vector element.
4480 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4482 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4483 DAG.getConstant(0, MVT::i32));
4486 // Finally, try a VMVN.i32
4487 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4489 if (NewVal != SDValue()) {
4491 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4494 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4496 // It's a float: cast and extract a vector element.
4497 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4499 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4500 DAG.getConstant(0, MVT::i32));
4506 // check if an VEXT instruction can handle the shuffle mask when the
4507 // vector sources of the shuffle are the same.
4508 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4509 unsigned NumElts = VT.getVectorNumElements();
4511 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4517 // If this is a VEXT shuffle, the immediate value is the index of the first
4518 // element. The other shuffle indices must be the successive elements after
4520 unsigned ExpectedElt = Imm;
4521 for (unsigned i = 1; i < NumElts; ++i) {
4522 // Increment the expected index. If it wraps around, just follow it
4523 // back to index zero and keep going.
4525 if (ExpectedElt == NumElts)
4528 if (M[i] < 0) continue; // ignore UNDEF indices
4529 if (ExpectedElt != static_cast<unsigned>(M[i]))
4537 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4538 bool &ReverseVEXT, unsigned &Imm) {
4539 unsigned NumElts = VT.getVectorNumElements();
4540 ReverseVEXT = false;
4542 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4548 // If this is a VEXT shuffle, the immediate value is the index of the first
4549 // element. The other shuffle indices must be the successive elements after
4551 unsigned ExpectedElt = Imm;
4552 for (unsigned i = 1; i < NumElts; ++i) {
4553 // Increment the expected index. If it wraps around, it may still be
4554 // a VEXT but the source vectors must be swapped.
4556 if (ExpectedElt == NumElts * 2) {
4561 if (M[i] < 0) continue; // ignore UNDEF indices
4562 if (ExpectedElt != static_cast<unsigned>(M[i]))
4566 // Adjust the index value if the source operands will be swapped.
4573 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4574 /// instruction with the specified blocksize. (The order of the elements
4575 /// within each block of the vector is reversed.)
4576 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4577 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4578 "Only possible block sizes for VREV are: 16, 32, 64");
4580 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4584 unsigned NumElts = VT.getVectorNumElements();
4585 unsigned BlockElts = M[0] + 1;
4586 // If the first shuffle index is UNDEF, be optimistic.
4588 BlockElts = BlockSize / EltSz;
4590 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4593 for (unsigned i = 0; i < NumElts; ++i) {
4594 if (M[i] < 0) continue; // ignore UNDEF indices
4595 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4602 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4603 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4604 // range, then 0 is placed into the resulting vector. So pretty much any mask
4605 // of 8 elements can work here.
4606 return VT == MVT::v8i8 && M.size() == 8;
4609 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4610 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4614 unsigned NumElts = VT.getVectorNumElements();
4615 WhichResult = (M[0] == 0 ? 0 : 1);
4616 for (unsigned i = 0; i < NumElts; i += 2) {
4617 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4618 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4624 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4625 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4626 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4627 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4628 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4632 unsigned NumElts = VT.getVectorNumElements();
4633 WhichResult = (M[0] == 0 ? 0 : 1);
4634 for (unsigned i = 0; i < NumElts; i += 2) {
4635 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4636 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4642 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4643 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4647 unsigned NumElts = VT.getVectorNumElements();
4648 WhichResult = (M[0] == 0 ? 0 : 1);
4649 for (unsigned i = 0; i != NumElts; ++i) {
4650 if (M[i] < 0) continue; // ignore UNDEF indices
4651 if ((unsigned) M[i] != 2 * i + WhichResult)
4655 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4656 if (VT.is64BitVector() && EltSz == 32)
4662 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4663 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4664 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4665 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4666 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4670 unsigned Half = VT.getVectorNumElements() / 2;
4671 WhichResult = (M[0] == 0 ? 0 : 1);
4672 for (unsigned j = 0; j != 2; ++j) {
4673 unsigned Idx = WhichResult;
4674 for (unsigned i = 0; i != Half; ++i) {
4675 int MIdx = M[i + j * Half];
4676 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4682 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4683 if (VT.is64BitVector() && EltSz == 32)
4689 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4690 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4694 unsigned NumElts = VT.getVectorNumElements();
4695 WhichResult = (M[0] == 0 ? 0 : 1);
4696 unsigned Idx = WhichResult * NumElts / 2;
4697 for (unsigned i = 0; i != NumElts; i += 2) {
4698 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4699 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4704 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4705 if (VT.is64BitVector() && EltSz == 32)
4711 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4712 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4713 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4714 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4715 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4719 unsigned NumElts = VT.getVectorNumElements();
4720 WhichResult = (M[0] == 0 ? 0 : 1);
4721 unsigned Idx = WhichResult * NumElts / 2;
4722 for (unsigned i = 0; i != NumElts; i += 2) {
4723 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4724 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4729 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4730 if (VT.is64BitVector() && EltSz == 32)
4736 /// \return true if this is a reverse operation on an vector.
4737 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4738 unsigned NumElts = VT.getVectorNumElements();
4739 // Make sure the mask has the right size.
4740 if (NumElts != M.size())
4743 // Look for <15, ..., 3, -1, 1, 0>.
4744 for (unsigned i = 0; i != NumElts; ++i)
4745 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4751 // If N is an integer constant that can be moved into a register in one
4752 // instruction, return an SDValue of such a constant (will become a MOV
4753 // instruction). Otherwise return null.
4754 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4755 const ARMSubtarget *ST, SDLoc dl) {
4757 if (!isa<ConstantSDNode>(N))
4759 Val = cast<ConstantSDNode>(N)->getZExtValue();
4761 if (ST->isThumb1Only()) {
4762 if (Val <= 255 || ~Val <= 255)
4763 return DAG.getConstant(Val, MVT::i32);
4765 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4766 return DAG.getConstant(Val, MVT::i32);
4771 // If this is a case we can't handle, return null and let the default
4772 // expansion code take care of it.
4773 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4774 const ARMSubtarget *ST) const {
4775 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4777 EVT VT = Op.getValueType();
4779 APInt SplatBits, SplatUndef;
4780 unsigned SplatBitSize;
4782 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4783 if (SplatBitSize <= 64) {
4784 // Check if an immediate VMOV works.
4786 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4787 SplatUndef.getZExtValue(), SplatBitSize,
4788 DAG, VmovVT, VT.is128BitVector(),
4790 if (Val.getNode()) {
4791 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4792 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4795 // Try an immediate VMVN.
4796 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4797 Val = isNEONModifiedImm(NegatedImm,
4798 SplatUndef.getZExtValue(), SplatBitSize,
4799 DAG, VmovVT, VT.is128BitVector(),
4801 if (Val.getNode()) {
4802 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4803 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4806 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4807 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4808 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4810 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4811 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4817 // Scan through the operands to see if only one value is used.
4819 // As an optimisation, even if more than one value is used it may be more
4820 // profitable to splat with one value then change some lanes.
4822 // Heuristically we decide to do this if the vector has a "dominant" value,
4823 // defined as splatted to more than half of the lanes.
4824 unsigned NumElts = VT.getVectorNumElements();
4825 bool isOnlyLowElement = true;
4826 bool usesOnlyOneValue = true;
4827 bool hasDominantValue = false;
4828 bool isConstant = true;
4830 // Map of the number of times a particular SDValue appears in the
4832 DenseMap<SDValue, unsigned> ValueCounts;
4834 for (unsigned i = 0; i < NumElts; ++i) {
4835 SDValue V = Op.getOperand(i);
4836 if (V.getOpcode() == ISD::UNDEF)
4839 isOnlyLowElement = false;
4840 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4843 ValueCounts.insert(std::make_pair(V, 0));
4844 unsigned &Count = ValueCounts[V];
4846 // Is this value dominant? (takes up more than half of the lanes)
4847 if (++Count > (NumElts / 2)) {
4848 hasDominantValue = true;
4852 if (ValueCounts.size() != 1)
4853 usesOnlyOneValue = false;
4854 if (!Value.getNode() && ValueCounts.size() > 0)
4855 Value = ValueCounts.begin()->first;
4857 if (ValueCounts.size() == 0)
4858 return DAG.getUNDEF(VT);
4860 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4861 // Keep going if we are hitting this case.
4862 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4863 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4865 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4867 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4868 // i32 and try again.
4869 if (hasDominantValue && EltSize <= 32) {
4873 // If we are VDUPing a value that comes directly from a vector, that will
4874 // cause an unnecessary move to and from a GPR, where instead we could
4875 // just use VDUPLANE. We can only do this if the lane being extracted
4876 // is at a constant index, as the VDUP from lane instructions only have
4877 // constant-index forms.
4878 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4879 isa<ConstantSDNode>(Value->getOperand(1))) {
4880 // We need to create a new undef vector to use for the VDUPLANE if the
4881 // size of the vector from which we get the value is different than the
4882 // size of the vector that we need to create. We will insert the element
4883 // such that the register coalescer will remove unnecessary copies.
4884 if (VT != Value->getOperand(0).getValueType()) {
4885 ConstantSDNode *constIndex;
4886 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4887 assert(constIndex && "The index is not a constant!");
4888 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4889 VT.getVectorNumElements();
4890 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4891 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4892 Value, DAG.getConstant(index, MVT::i32)),
4893 DAG.getConstant(index, MVT::i32));
4895 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4896 Value->getOperand(0), Value->getOperand(1));
4898 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4900 if (!usesOnlyOneValue) {
4901 // The dominant value was splatted as 'N', but we now have to insert
4902 // all differing elements.
4903 for (unsigned I = 0; I < NumElts; ++I) {
4904 if (Op.getOperand(I) == Value)
4906 SmallVector<SDValue, 3> Ops;
4908 Ops.push_back(Op.getOperand(I));
4909 Ops.push_back(DAG.getConstant(I, MVT::i32));
4910 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
4915 if (VT.getVectorElementType().isFloatingPoint()) {
4916 SmallVector<SDValue, 8> Ops;
4917 for (unsigned i = 0; i < NumElts; ++i)
4918 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4920 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4921 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
4922 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4924 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4926 if (usesOnlyOneValue) {
4927 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4928 if (isConstant && Val.getNode())
4929 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4933 // If all elements are constants and the case above didn't get hit, fall back
4934 // to the default expansion, which will generate a load from the constant
4939 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4941 SDValue shuffle = ReconstructShuffle(Op, DAG);
4942 if (shuffle != SDValue())
4946 // Vectors with 32- or 64-bit elements can be built by directly assigning
4947 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4948 // will be legalized.
4949 if (EltSize >= 32) {
4950 // Do the expansion with floating-point types, since that is what the VFP
4951 // registers are defined to use, and since i64 is not legal.
4952 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4953 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4954 SmallVector<SDValue, 8> Ops;
4955 for (unsigned i = 0; i < NumElts; ++i)
4956 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4957 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
4958 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4961 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4962 // know the default expansion would otherwise fall back on something even
4963 // worse. For a vector with one or two non-undef values, that's
4964 // scalar_to_vector for the elements followed by a shuffle (provided the
4965 // shuffle is valid for the target) and materialization element by element
4966 // on the stack followed by a load for everything else.
4967 if (!isConstant && !usesOnlyOneValue) {
4968 SDValue Vec = DAG.getUNDEF(VT);
4969 for (unsigned i = 0 ; i < NumElts; ++i) {
4970 SDValue V = Op.getOperand(i);
4971 if (V.getOpcode() == ISD::UNDEF)
4973 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4974 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4982 // Gather data to see if the operation can be modelled as a
4983 // shuffle in combination with VEXTs.
4984 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4985 SelectionDAG &DAG) const {
4987 EVT VT = Op.getValueType();
4988 unsigned NumElts = VT.getVectorNumElements();
4990 SmallVector<SDValue, 2> SourceVecs;
4991 SmallVector<unsigned, 2> MinElts;
4992 SmallVector<unsigned, 2> MaxElts;
4994 for (unsigned i = 0; i < NumElts; ++i) {
4995 SDValue V = Op.getOperand(i);
4996 if (V.getOpcode() == ISD::UNDEF)
4998 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4999 // A shuffle can only come from building a vector from various
5000 // elements of other vectors.
5002 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5003 VT.getVectorElementType()) {
5004 // This code doesn't know how to handle shuffles where the vector
5005 // element types do not match (this happens because type legalization
5006 // promotes the return type of EXTRACT_VECTOR_ELT).
5007 // FIXME: It might be appropriate to extend this code to handle
5008 // mismatched types.
5012 // Record this extraction against the appropriate vector if possible...
5013 SDValue SourceVec = V.getOperand(0);
5014 // If the element number isn't a constant, we can't effectively
5015 // analyze what's going on.
5016 if (!isa<ConstantSDNode>(V.getOperand(1)))
5018 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5019 bool FoundSource = false;
5020 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5021 if (SourceVecs[j] == SourceVec) {
5022 if (MinElts[j] > EltNo)
5024 if (MaxElts[j] < EltNo)
5031 // Or record a new source if not...
5033 SourceVecs.push_back(SourceVec);
5034 MinElts.push_back(EltNo);
5035 MaxElts.push_back(EltNo);
5039 // Currently only do something sane when at most two source vectors
5041 if (SourceVecs.size() > 2)
5044 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5045 int VEXTOffsets[2] = {0, 0};
5047 // This loop extracts the usage patterns of the source vectors
5048 // and prepares appropriate SDValues for a shuffle if possible.
5049 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5050 if (SourceVecs[i].getValueType() == VT) {
5051 // No VEXT necessary
5052 ShuffleSrcs[i] = SourceVecs[i];
5055 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5056 // It probably isn't worth padding out a smaller vector just to
5057 // break it down again in a shuffle.
5061 // Since only 64-bit and 128-bit vectors are legal on ARM and
5062 // we've eliminated the other cases...
5063 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5064 "unexpected vector sizes in ReconstructShuffle");
5066 if (MaxElts[i] - MinElts[i] >= NumElts) {
5067 // Span too large for a VEXT to cope
5071 if (MinElts[i] >= NumElts) {
5072 // The extraction can just take the second half
5073 VEXTOffsets[i] = NumElts;
5074 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5076 DAG.getIntPtrConstant(NumElts));
5077 } else if (MaxElts[i] < NumElts) {
5078 // The extraction can just take the first half
5080 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5082 DAG.getIntPtrConstant(0));
5084 // An actual VEXT is needed
5085 VEXTOffsets[i] = MinElts[i];
5086 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5088 DAG.getIntPtrConstant(0));
5089 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5091 DAG.getIntPtrConstant(NumElts));
5092 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5093 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5097 SmallVector<int, 8> Mask;
5099 for (unsigned i = 0; i < NumElts; ++i) {
5100 SDValue Entry = Op.getOperand(i);
5101 if (Entry.getOpcode() == ISD::UNDEF) {
5106 SDValue ExtractVec = Entry.getOperand(0);
5107 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5108 .getOperand(1))->getSExtValue();
5109 if (ExtractVec == SourceVecs[0]) {
5110 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5112 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5116 // Final check before we try to produce nonsense...
5117 if (isShuffleMaskLegal(Mask, VT))
5118 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5124 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5125 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5126 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5127 /// are assumed to be legal.
5129 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5131 if (VT.getVectorNumElements() == 4 &&
5132 (VT.is128BitVector() || VT.is64BitVector())) {
5133 unsigned PFIndexes[4];
5134 for (unsigned i = 0; i != 4; ++i) {
5138 PFIndexes[i] = M[i];
5141 // Compute the index in the perfect shuffle table.
5142 unsigned PFTableIndex =
5143 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5144 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5145 unsigned Cost = (PFEntry >> 30);
5152 unsigned Imm, WhichResult;
5154 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5155 return (EltSize >= 32 ||
5156 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5157 isVREVMask(M, VT, 64) ||
5158 isVREVMask(M, VT, 32) ||
5159 isVREVMask(M, VT, 16) ||
5160 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5161 isVTBLMask(M, VT) ||
5162 isVTRNMask(M, VT, WhichResult) ||
5163 isVUZPMask(M, VT, WhichResult) ||
5164 isVZIPMask(M, VT, WhichResult) ||
5165 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5166 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5167 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5168 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5171 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5172 /// the specified operations to build the shuffle.
5173 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5174 SDValue RHS, SelectionDAG &DAG,
5176 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5177 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5178 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5181 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5190 OP_VUZPL, // VUZP, left result
5191 OP_VUZPR, // VUZP, right result
5192 OP_VZIPL, // VZIP, left result
5193 OP_VZIPR, // VZIP, right result
5194 OP_VTRNL, // VTRN, left result
5195 OP_VTRNR // VTRN, right result
5198 if (OpNum == OP_COPY) {
5199 if (LHSID == (1*9+2)*9+3) return LHS;
5200 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5204 SDValue OpLHS, OpRHS;
5205 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5206 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5207 EVT VT = OpLHS.getValueType();
5210 default: llvm_unreachable("Unknown shuffle opcode!");
5212 // VREV divides the vector in half and swaps within the half.
5213 if (VT.getVectorElementType() == MVT::i32 ||
5214 VT.getVectorElementType() == MVT::f32)
5215 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5216 // vrev <4 x i16> -> VREV32
5217 if (VT.getVectorElementType() == MVT::i16)
5218 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5219 // vrev <4 x i8> -> VREV16
5220 assert(VT.getVectorElementType() == MVT::i8);
5221 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5226 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5227 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5231 return DAG.getNode(ARMISD::VEXT, dl, VT,
5233 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5236 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5237 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5240 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5241 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5244 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5245 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5249 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5250 ArrayRef<int> ShuffleMask,
5251 SelectionDAG &DAG) {
5252 // Check to see if we can use the VTBL instruction.
5253 SDValue V1 = Op.getOperand(0);
5254 SDValue V2 = Op.getOperand(1);
5257 SmallVector<SDValue, 8> VTBLMask;
5258 for (ArrayRef<int>::iterator
5259 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5260 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5262 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5263 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5264 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5266 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5267 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5270 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5271 SelectionDAG &DAG) {
5273 SDValue OpLHS = Op.getOperand(0);
5274 EVT VT = OpLHS.getValueType();
5276 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5277 "Expect an v8i16/v16i8 type");
5278 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5279 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5280 // extract the first 8 bytes into the top double word and the last 8 bytes
5281 // into the bottom double word. The v8i16 case is similar.
5282 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5283 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5284 DAG.getConstant(ExtractNum, MVT::i32));
5287 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5288 SDValue V1 = Op.getOperand(0);
5289 SDValue V2 = Op.getOperand(1);
5291 EVT VT = Op.getValueType();
5292 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5294 // Convert shuffles that are directly supported on NEON to target-specific
5295 // DAG nodes, instead of keeping them as shuffles and matching them again
5296 // during code selection. This is more efficient and avoids the possibility
5297 // of inconsistencies between legalization and selection.
5298 // FIXME: floating-point vectors should be canonicalized to integer vectors
5299 // of the same time so that they get CSEd properly.
5300 ArrayRef<int> ShuffleMask = SVN->getMask();
5302 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5303 if (EltSize <= 32) {
5304 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5305 int Lane = SVN->getSplatIndex();
5306 // If this is undef splat, generate it via "just" vdup, if possible.
5307 if (Lane == -1) Lane = 0;
5309 // Test if V1 is a SCALAR_TO_VECTOR.
5310 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5311 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5313 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5314 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5316 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5317 !isa<ConstantSDNode>(V1.getOperand(0))) {
5318 bool IsScalarToVector = true;
5319 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5320 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5321 IsScalarToVector = false;
5324 if (IsScalarToVector)
5325 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5327 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5328 DAG.getConstant(Lane, MVT::i32));
5333 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5336 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5337 DAG.getConstant(Imm, MVT::i32));
5340 if (isVREVMask(ShuffleMask, VT, 64))
5341 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5342 if (isVREVMask(ShuffleMask, VT, 32))
5343 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5344 if (isVREVMask(ShuffleMask, VT, 16))
5345 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5347 if (V2->getOpcode() == ISD::UNDEF &&
5348 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5349 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5350 DAG.getConstant(Imm, MVT::i32));
5353 // Check for Neon shuffles that modify both input vectors in place.
5354 // If both results are used, i.e., if there are two shuffles with the same
5355 // source operands and with masks corresponding to both results of one of
5356 // these operations, DAG memoization will ensure that a single node is
5357 // used for both shuffles.
5358 unsigned WhichResult;
5359 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5360 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5361 V1, V2).getValue(WhichResult);
5362 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5363 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5364 V1, V2).getValue(WhichResult);
5365 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5366 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5367 V1, V2).getValue(WhichResult);
5369 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5370 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5371 V1, V1).getValue(WhichResult);
5372 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5373 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5374 V1, V1).getValue(WhichResult);
5375 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5376 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5377 V1, V1).getValue(WhichResult);
5380 // If the shuffle is not directly supported and it has 4 elements, use
5381 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5382 unsigned NumElts = VT.getVectorNumElements();
5384 unsigned PFIndexes[4];
5385 for (unsigned i = 0; i != 4; ++i) {
5386 if (ShuffleMask[i] < 0)
5389 PFIndexes[i] = ShuffleMask[i];
5392 // Compute the index in the perfect shuffle table.
5393 unsigned PFTableIndex =
5394 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5395 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5396 unsigned Cost = (PFEntry >> 30);
5399 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5402 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5403 if (EltSize >= 32) {
5404 // Do the expansion with floating-point types, since that is what the VFP
5405 // registers are defined to use, and since i64 is not legal.
5406 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5407 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5408 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5409 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5410 SmallVector<SDValue, 8> Ops;
5411 for (unsigned i = 0; i < NumElts; ++i) {
5412 if (ShuffleMask[i] < 0)
5413 Ops.push_back(DAG.getUNDEF(EltVT));
5415 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5416 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5417 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5420 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5421 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5424 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5425 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5427 if (VT == MVT::v8i8) {
5428 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5429 if (NewOp.getNode())
5436 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5437 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5438 SDValue Lane = Op.getOperand(2);
5439 if (!isa<ConstantSDNode>(Lane))
5445 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5446 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5447 SDValue Lane = Op.getOperand(1);
5448 if (!isa<ConstantSDNode>(Lane))
5451 SDValue Vec = Op.getOperand(0);
5452 if (Op.getValueType() == MVT::i32 &&
5453 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5455 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5461 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5462 // The only time a CONCAT_VECTORS operation can have legal types is when
5463 // two 64-bit vectors are concatenated to a 128-bit vector.
5464 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5465 "unexpected CONCAT_VECTORS");
5467 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5468 SDValue Op0 = Op.getOperand(0);
5469 SDValue Op1 = Op.getOperand(1);
5470 if (Op0.getOpcode() != ISD::UNDEF)
5471 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5472 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5473 DAG.getIntPtrConstant(0));
5474 if (Op1.getOpcode() != ISD::UNDEF)
5475 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5476 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5477 DAG.getIntPtrConstant(1));
5478 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5481 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5482 /// element has been zero/sign-extended, depending on the isSigned parameter,
5483 /// from an integer type half its size.
5484 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5486 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5487 EVT VT = N->getValueType(0);
5488 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5489 SDNode *BVN = N->getOperand(0).getNode();
5490 if (BVN->getValueType(0) != MVT::v4i32 ||
5491 BVN->getOpcode() != ISD::BUILD_VECTOR)
5493 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5494 unsigned HiElt = 1 - LoElt;
5495 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5496 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5497 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5498 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5499 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5502 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5503 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5506 if (Hi0->isNullValue() && Hi1->isNullValue())
5512 if (N->getOpcode() != ISD::BUILD_VECTOR)
5515 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5516 SDNode *Elt = N->getOperand(i).getNode();
5517 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5518 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5519 unsigned HalfSize = EltSize / 2;
5521 if (!isIntN(HalfSize, C->getSExtValue()))
5524 if (!isUIntN(HalfSize, C->getZExtValue()))
5535 /// isSignExtended - Check if a node is a vector value that is sign-extended
5536 /// or a constant BUILD_VECTOR with sign-extended elements.
5537 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5538 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5540 if (isExtendedBUILD_VECTOR(N, DAG, true))
5545 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5546 /// or a constant BUILD_VECTOR with zero-extended elements.
5547 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5548 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5550 if (isExtendedBUILD_VECTOR(N, DAG, false))
5555 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5556 if (OrigVT.getSizeInBits() >= 64)
5559 assert(OrigVT.isSimple() && "Expecting a simple value type");
5561 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5562 switch (OrigSimpleTy) {
5563 default: llvm_unreachable("Unexpected Vector Type");
5572 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5573 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5574 /// We insert the required extension here to get the vector to fill a D register.
5575 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5578 unsigned ExtOpcode) {
5579 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5580 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5581 // 64-bits we need to insert a new extension so that it will be 64-bits.
5582 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5583 if (OrigTy.getSizeInBits() >= 64)
5586 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5587 EVT NewVT = getExtensionTo64Bits(OrigTy);
5589 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5592 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5593 /// does not do any sign/zero extension. If the original vector is less
5594 /// than 64 bits, an appropriate extension will be added after the load to
5595 /// reach a total size of 64 bits. We have to add the extension separately
5596 /// because ARM does not have a sign/zero extending load for vectors.
5597 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5598 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5600 // The load already has the right type.
5601 if (ExtendedTy == LD->getMemoryVT())
5602 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5603 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5604 LD->isNonTemporal(), LD->isInvariant(),
5605 LD->getAlignment());
5607 // We need to create a zextload/sextload. We cannot just create a load
5608 // followed by a zext/zext node because LowerMUL is also run during normal
5609 // operation legalization where we can't create illegal types.
5610 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5611 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5612 LD->getMemoryVT(), LD->isVolatile(),
5613 LD->isNonTemporal(), LD->getAlignment());
5616 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5617 /// extending load, or BUILD_VECTOR with extended elements, return the
5618 /// unextended value. The unextended vector should be 64 bits so that it can
5619 /// be used as an operand to a VMULL instruction. If the original vector size
5620 /// before extension is less than 64 bits we add a an extension to resize
5621 /// the vector to 64 bits.
5622 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5623 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5624 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5625 N->getOperand(0)->getValueType(0),
5629 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5630 return SkipLoadExtensionForVMULL(LD, DAG);
5632 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5633 // have been legalized as a BITCAST from v4i32.
5634 if (N->getOpcode() == ISD::BITCAST) {
5635 SDNode *BVN = N->getOperand(0).getNode();
5636 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5637 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5638 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5639 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5640 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5642 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5643 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5644 EVT VT = N->getValueType(0);
5645 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5646 unsigned NumElts = VT.getVectorNumElements();
5647 MVT TruncVT = MVT::getIntegerVT(EltSize);
5648 SmallVector<SDValue, 8> Ops;
5649 for (unsigned i = 0; i != NumElts; ++i) {
5650 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5651 const APInt &CInt = C->getAPIntValue();
5652 // Element types smaller than 32 bits are not legal, so use i32 elements.
5653 // The values are implicitly truncated so sext vs. zext doesn't matter.
5654 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5656 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5657 MVT::getVectorVT(TruncVT, NumElts), Ops);
5660 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5661 unsigned Opcode = N->getOpcode();
5662 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5663 SDNode *N0 = N->getOperand(0).getNode();
5664 SDNode *N1 = N->getOperand(1).getNode();
5665 return N0->hasOneUse() && N1->hasOneUse() &&
5666 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5671 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5672 unsigned Opcode = N->getOpcode();
5673 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5674 SDNode *N0 = N->getOperand(0).getNode();
5675 SDNode *N1 = N->getOperand(1).getNode();
5676 return N0->hasOneUse() && N1->hasOneUse() &&
5677 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5682 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5683 // Multiplications are only custom-lowered for 128-bit vectors so that
5684 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5685 EVT VT = Op.getValueType();
5686 assert(VT.is128BitVector() && VT.isInteger() &&
5687 "unexpected type for custom-lowering ISD::MUL");
5688 SDNode *N0 = Op.getOperand(0).getNode();
5689 SDNode *N1 = Op.getOperand(1).getNode();
5690 unsigned NewOpc = 0;
5692 bool isN0SExt = isSignExtended(N0, DAG);
5693 bool isN1SExt = isSignExtended(N1, DAG);
5694 if (isN0SExt && isN1SExt)
5695 NewOpc = ARMISD::VMULLs;
5697 bool isN0ZExt = isZeroExtended(N0, DAG);
5698 bool isN1ZExt = isZeroExtended(N1, DAG);
5699 if (isN0ZExt && isN1ZExt)
5700 NewOpc = ARMISD::VMULLu;
5701 else if (isN1SExt || isN1ZExt) {
5702 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5703 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5704 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5705 NewOpc = ARMISD::VMULLs;
5707 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5708 NewOpc = ARMISD::VMULLu;
5710 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5712 NewOpc = ARMISD::VMULLu;
5718 if (VT == MVT::v2i64)
5719 // Fall through to expand this. It is not legal.
5722 // Other vector multiplications are legal.
5727 // Legalize to a VMULL instruction.
5730 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5732 Op0 = SkipExtensionForVMULL(N0, DAG);
5733 assert(Op0.getValueType().is64BitVector() &&
5734 Op1.getValueType().is64BitVector() &&
5735 "unexpected types for extended operands to VMULL");
5736 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5739 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5740 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5747 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5748 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5749 EVT Op1VT = Op1.getValueType();
5750 return DAG.getNode(N0->getOpcode(), DL, VT,
5751 DAG.getNode(NewOpc, DL, VT,
5752 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5753 DAG.getNode(NewOpc, DL, VT,
5754 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5758 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5760 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5761 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5762 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5763 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5764 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5765 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5766 // Get reciprocal estimate.
5767 // float4 recip = vrecpeq_f32(yf);
5768 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5769 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5770 // Because char has a smaller range than uchar, we can actually get away
5771 // without any newton steps. This requires that we use a weird bias
5772 // of 0xb000, however (again, this has been exhaustively tested).
5773 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5774 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5775 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5776 Y = DAG.getConstant(0xb000, MVT::i32);
5777 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5778 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5779 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5780 // Convert back to short.
5781 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5782 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5787 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5789 // Convert to float.
5790 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5791 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5792 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5793 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5794 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5795 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5797 // Use reciprocal estimate and one refinement step.
5798 // float4 recip = vrecpeq_f32(yf);
5799 // recip *= vrecpsq_f32(yf, recip);
5800 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5801 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5802 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5803 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5805 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5806 // Because short has a smaller range than ushort, we can actually get away
5807 // with only a single newton step. This requires that we use a weird bias
5808 // of 89, however (again, this has been exhaustively tested).
5809 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5810 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5811 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5812 N1 = DAG.getConstant(0x89, MVT::i32);
5813 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5814 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5815 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5816 // Convert back to integer and return.
5817 // return vmovn_s32(vcvt_s32_f32(result));
5818 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5819 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5823 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5824 EVT VT = Op.getValueType();
5825 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5826 "unexpected type for custom-lowering ISD::SDIV");
5829 SDValue N0 = Op.getOperand(0);
5830 SDValue N1 = Op.getOperand(1);
5833 if (VT == MVT::v8i8) {
5834 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5835 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5837 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5838 DAG.getIntPtrConstant(4));
5839 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5840 DAG.getIntPtrConstant(4));
5841 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5842 DAG.getIntPtrConstant(0));
5843 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5844 DAG.getIntPtrConstant(0));
5846 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5847 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5849 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5850 N0 = LowerCONCAT_VECTORS(N0, DAG);
5852 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5855 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5858 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5859 EVT VT = Op.getValueType();
5860 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5861 "unexpected type for custom-lowering ISD::UDIV");
5864 SDValue N0 = Op.getOperand(0);
5865 SDValue N1 = Op.getOperand(1);
5868 if (VT == MVT::v8i8) {
5869 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5870 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5872 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5873 DAG.getIntPtrConstant(4));
5874 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5875 DAG.getIntPtrConstant(4));
5876 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5877 DAG.getIntPtrConstant(0));
5878 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5879 DAG.getIntPtrConstant(0));
5881 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5882 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5884 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5885 N0 = LowerCONCAT_VECTORS(N0, DAG);
5887 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5888 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5893 // v4i16 sdiv ... Convert to float.
5894 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5895 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5896 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5897 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5898 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5899 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5901 // Use reciprocal estimate and two refinement steps.
5902 // float4 recip = vrecpeq_f32(yf);
5903 // recip *= vrecpsq_f32(yf, recip);
5904 // recip *= vrecpsq_f32(yf, recip);
5905 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5906 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5907 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5908 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5910 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5911 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5912 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5914 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5915 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5916 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5917 // and that it will never cause us to return an answer too large).
5918 // float4 result = as_float4(as_int4(xf*recip) + 2);
5919 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5920 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5921 N1 = DAG.getConstant(2, MVT::i32);
5922 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5923 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5924 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5925 // Convert back to integer and return.
5926 // return vmovn_u32(vcvt_s32_f32(result));
5927 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5928 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5932 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5933 EVT VT = Op.getNode()->getValueType(0);
5934 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5937 bool ExtraOp = false;
5938 switch (Op.getOpcode()) {
5939 default: llvm_unreachable("Invalid code");
5940 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5941 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5942 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5943 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5947 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5949 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5950 Op.getOperand(1), Op.getOperand(2));
5953 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5954 assert(Subtarget->isTargetDarwin());
5956 // For iOS, we want to call an alternative entry point: __sincos_stret,
5957 // return values are passed via sret.
5959 SDValue Arg = Op.getOperand(0);
5960 EVT ArgVT = Arg.getValueType();
5961 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5963 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5964 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5966 // Pair of floats / doubles used to pass the result.
5967 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5969 // Create stack object for sret.
5970 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5971 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5972 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5973 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5979 Entry.Ty = RetTy->getPointerTo();
5980 Entry.isSExt = false;
5981 Entry.isZExt = false;
5982 Entry.isSRet = true;
5983 Args.push_back(Entry);
5987 Entry.isSExt = false;
5988 Entry.isZExt = false;
5989 Args.push_back(Entry);
5991 const char *LibcallName = (ArgVT == MVT::f64)
5992 ? "__sincos_stret" : "__sincosf_stret";
5993 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5996 CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5997 false, false, false, false, 0,
5998 CallingConv::C, /*isTaillCall=*/false,
5999 /*doesNotRet=*/false, /*isReturnValueUsed*/false,
6000 Callee, Args, DAG, dl);
6001 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6003 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6004 MachinePointerInfo(), false, false, false, 0);
6006 // Address of cos field.
6007 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6008 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6009 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6010 MachinePointerInfo(), false, false, false, 0);
6012 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6013 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6014 LoadSin.getValue(0), LoadCos.getValue(0));
6017 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6018 // Monotonic load/store is legal for all targets
6019 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6022 // Acquire/Release load/store is not legal for targets without a
6023 // dmb or equivalent available.
6027 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6028 SmallVectorImpl<SDValue> &Results,
6030 const ARMSubtarget *Subtarget) {
6032 SDValue Cycles32, OutChain;
6034 if (Subtarget->hasPerfMon()) {
6035 // Under Power Management extensions, the cycle-count is:
6036 // mrc p15, #0, <Rt>, c9, c13, #0
6037 SDValue Ops[] = { N->getOperand(0), // Chain
6038 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6039 DAG.getConstant(15, MVT::i32),
6040 DAG.getConstant(0, MVT::i32),
6041 DAG.getConstant(9, MVT::i32),
6042 DAG.getConstant(13, MVT::i32),
6043 DAG.getConstant(0, MVT::i32)
6046 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6047 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6048 OutChain = Cycles32.getValue(1);
6050 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6051 // there are older ARM CPUs that have implementation-specific ways of
6052 // obtaining this information (FIXME!).
6053 Cycles32 = DAG.getConstant(0, MVT::i32);
6054 OutChain = DAG.getEntryNode();
6058 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6059 Cycles32, DAG.getConstant(0, MVT::i32));
6060 Results.push_back(Cycles64);
6061 Results.push_back(OutChain);
6064 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6065 switch (Op.getOpcode()) {
6066 default: llvm_unreachable("Don't know how to custom lower this!");
6067 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6068 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6069 case ISD::GlobalAddress:
6070 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6071 default: llvm_unreachable("unknown object format");
6073 return LowerGlobalAddressWindows(Op, DAG);
6075 return LowerGlobalAddressELF(Op, DAG);
6077 return LowerGlobalAddressDarwin(Op, DAG);
6079 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6080 case ISD::SELECT: return LowerSELECT(Op, DAG);
6081 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6082 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6083 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6084 case ISD::VASTART: return LowerVASTART(Op, DAG);
6085 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6086 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6087 case ISD::SINT_TO_FP:
6088 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6089 case ISD::FP_TO_SINT:
6090 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6091 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6092 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6093 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6094 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6095 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6096 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6097 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6099 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6102 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6103 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6104 case ISD::SRL_PARTS:
6105 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6106 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6107 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6108 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6109 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6110 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6111 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6112 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6113 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6114 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6115 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6116 case ISD::MUL: return LowerMUL(Op, DAG);
6117 case ISD::SDIV: return LowerSDIV(Op, DAG);
6118 case ISD::UDIV: return LowerUDIV(Op, DAG);
6122 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6123 case ISD::ATOMIC_LOAD:
6124 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6125 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6127 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6131 /// ReplaceNodeResults - Replace the results of node with an illegal result
6132 /// type with new values built out of custom code.
6133 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6134 SmallVectorImpl<SDValue>&Results,
6135 SelectionDAG &DAG) const {
6137 switch (N->getOpcode()) {
6139 llvm_unreachable("Don't know how to custom expand this!");
6141 Res = ExpandBITCAST(N, DAG);
6145 Res = Expand64BitShift(N, DAG, Subtarget);
6147 case ISD::READCYCLECOUNTER:
6148 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6152 Results.push_back(Res);
6155 //===----------------------------------------------------------------------===//
6156 // ARM Scheduler Hooks
6157 //===----------------------------------------------------------------------===//
6159 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6160 /// registers the function context.
6161 void ARMTargetLowering::
6162 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6163 MachineBasicBlock *DispatchBB, int FI) const {
6164 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6165 DebugLoc dl = MI->getDebugLoc();
6166 MachineFunction *MF = MBB->getParent();
6167 MachineRegisterInfo *MRI = &MF->getRegInfo();
6168 MachineConstantPool *MCP = MF->getConstantPool();
6169 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6170 const Function *F = MF->getFunction();
6172 bool isThumb = Subtarget->isThumb();
6173 bool isThumb2 = Subtarget->isThumb2();
6175 unsigned PCLabelId = AFI->createPICLabelUId();
6176 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6177 ARMConstantPoolValue *CPV =
6178 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6179 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6181 const TargetRegisterClass *TRC = isThumb ?
6182 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6183 (const TargetRegisterClass*)&ARM::GPRRegClass;
6185 // Grab constant pool and fixed stack memory operands.
6186 MachineMemOperand *CPMMO =
6187 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6188 MachineMemOperand::MOLoad, 4, 4);
6190 MachineMemOperand *FIMMOSt =
6191 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6192 MachineMemOperand::MOStore, 4, 4);
6194 // Load the address of the dispatch MBB into the jump buffer.
6196 // Incoming value: jbuf
6197 // ldr.n r5, LCPI1_1
6200 // str r5, [$jbuf, #+4] ; &jbuf[1]
6201 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6202 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6203 .addConstantPoolIndex(CPI)
6204 .addMemOperand(CPMMO));
6205 // Set the low bit because of thumb mode.
6206 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6208 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6209 .addReg(NewVReg1, RegState::Kill)
6211 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6212 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6213 .addReg(NewVReg2, RegState::Kill)
6215 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6216 .addReg(NewVReg3, RegState::Kill)
6218 .addImm(36) // &jbuf[1] :: pc
6219 .addMemOperand(FIMMOSt));
6220 } else if (isThumb) {
6221 // Incoming value: jbuf
6222 // ldr.n r1, LCPI1_4
6226 // add r2, $jbuf, #+4 ; &jbuf[1]
6228 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6229 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6230 .addConstantPoolIndex(CPI)
6231 .addMemOperand(CPMMO));
6232 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6233 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6234 .addReg(NewVReg1, RegState::Kill)
6236 // Set the low bit because of thumb mode.
6237 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6238 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6239 .addReg(ARM::CPSR, RegState::Define)
6241 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6242 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6243 .addReg(ARM::CPSR, RegState::Define)
6244 .addReg(NewVReg2, RegState::Kill)
6245 .addReg(NewVReg3, RegState::Kill));
6246 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6247 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6249 .addImm(36)); // &jbuf[1] :: pc
6250 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6251 .addReg(NewVReg4, RegState::Kill)
6252 .addReg(NewVReg5, RegState::Kill)
6254 .addMemOperand(FIMMOSt));
6256 // Incoming value: jbuf
6259 // str r1, [$jbuf, #+4] ; &jbuf[1]
6260 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6261 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6262 .addConstantPoolIndex(CPI)
6264 .addMemOperand(CPMMO));
6265 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6266 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6267 .addReg(NewVReg1, RegState::Kill)
6268 .addImm(PCLabelId));
6269 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6270 .addReg(NewVReg2, RegState::Kill)
6272 .addImm(36) // &jbuf[1] :: pc
6273 .addMemOperand(FIMMOSt));
6277 MachineBasicBlock *ARMTargetLowering::
6278 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6279 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6280 DebugLoc dl = MI->getDebugLoc();
6281 MachineFunction *MF = MBB->getParent();
6282 MachineRegisterInfo *MRI = &MF->getRegInfo();
6283 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6284 MachineFrameInfo *MFI = MF->getFrameInfo();
6285 int FI = MFI->getFunctionContextIndex();
6287 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6288 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6289 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6291 // Get a mapping of the call site numbers to all of the landing pads they're
6293 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6294 unsigned MaxCSNum = 0;
6295 MachineModuleInfo &MMI = MF->getMMI();
6296 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6298 if (!BB->isLandingPad()) continue;
6300 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6302 for (MachineBasicBlock::iterator
6303 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6304 if (!II->isEHLabel()) continue;
6306 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6307 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6309 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6310 for (SmallVectorImpl<unsigned>::iterator
6311 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6312 CSI != CSE; ++CSI) {
6313 CallSiteNumToLPad[*CSI].push_back(BB);
6314 MaxCSNum = std::max(MaxCSNum, *CSI);
6320 // Get an ordered list of the machine basic blocks for the jump table.
6321 std::vector<MachineBasicBlock*> LPadList;
6322 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6323 LPadList.reserve(CallSiteNumToLPad.size());
6324 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6325 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6326 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6327 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6328 LPadList.push_back(*II);
6329 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6333 assert(!LPadList.empty() &&
6334 "No landing pad destinations for the dispatch jump table!");
6336 // Create the jump table and associated information.
6337 MachineJumpTableInfo *JTI =
6338 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6339 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6340 unsigned UId = AFI->createJumpTableUId();
6341 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6343 // Create the MBBs for the dispatch code.
6345 // Shove the dispatch's address into the return slot in the function context.
6346 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6347 DispatchBB->setIsLandingPad();
6349 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6350 unsigned trap_opcode;
6351 if (Subtarget->isThumb())
6352 trap_opcode = ARM::tTRAP;
6354 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6356 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6357 DispatchBB->addSuccessor(TrapBB);
6359 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6360 DispatchBB->addSuccessor(DispContBB);
6363 MF->insert(MF->end(), DispatchBB);
6364 MF->insert(MF->end(), DispContBB);
6365 MF->insert(MF->end(), TrapBB);
6367 // Insert code into the entry block that creates and registers the function
6369 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6371 MachineMemOperand *FIMMOLd =
6372 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6373 MachineMemOperand::MOLoad |
6374 MachineMemOperand::MOVolatile, 4, 4);
6376 MachineInstrBuilder MIB;
6377 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6379 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6380 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6382 // Add a register mask with no preserved registers. This results in all
6383 // registers being marked as clobbered.
6384 MIB.addRegMask(RI.getNoPreservedMask());
6386 unsigned NumLPads = LPadList.size();
6387 if (Subtarget->isThumb2()) {
6388 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6389 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6392 .addMemOperand(FIMMOLd));
6394 if (NumLPads < 256) {
6395 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6397 .addImm(LPadList.size()));
6399 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6400 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6401 .addImm(NumLPads & 0xFFFF));
6403 unsigned VReg2 = VReg1;
6404 if ((NumLPads & 0xFFFF0000) != 0) {
6405 VReg2 = MRI->createVirtualRegister(TRC);
6406 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6408 .addImm(NumLPads >> 16));
6411 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6416 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6421 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6422 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6423 .addJumpTableIndex(MJTI)
6426 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6429 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6430 .addReg(NewVReg3, RegState::Kill)
6432 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6434 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6435 .addReg(NewVReg4, RegState::Kill)
6437 .addJumpTableIndex(MJTI)
6439 } else if (Subtarget->isThumb()) {
6440 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6441 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6444 .addMemOperand(FIMMOLd));
6446 if (NumLPads < 256) {
6447 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6451 MachineConstantPool *ConstantPool = MF->getConstantPool();
6452 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6453 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6455 // MachineConstantPool wants an explicit alignment.
6456 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6458 Align = getDataLayout()->getTypeAllocSize(C->getType());
6459 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6461 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6462 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6463 .addReg(VReg1, RegState::Define)
6464 .addConstantPoolIndex(Idx));
6465 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6470 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6475 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6476 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6477 .addReg(ARM::CPSR, RegState::Define)
6481 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6482 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6483 .addJumpTableIndex(MJTI)
6486 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6487 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6488 .addReg(ARM::CPSR, RegState::Define)
6489 .addReg(NewVReg2, RegState::Kill)
6492 MachineMemOperand *JTMMOLd =
6493 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6494 MachineMemOperand::MOLoad, 4, 4);
6496 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6497 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6498 .addReg(NewVReg4, RegState::Kill)
6500 .addMemOperand(JTMMOLd));
6502 unsigned NewVReg6 = NewVReg5;
6503 if (RelocM == Reloc::PIC_) {
6504 NewVReg6 = MRI->createVirtualRegister(TRC);
6505 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6506 .addReg(ARM::CPSR, RegState::Define)
6507 .addReg(NewVReg5, RegState::Kill)
6511 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6512 .addReg(NewVReg6, RegState::Kill)
6513 .addJumpTableIndex(MJTI)
6516 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6517 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6520 .addMemOperand(FIMMOLd));
6522 if (NumLPads < 256) {
6523 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6526 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6527 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6528 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6529 .addImm(NumLPads & 0xFFFF));
6531 unsigned VReg2 = VReg1;
6532 if ((NumLPads & 0xFFFF0000) != 0) {
6533 VReg2 = MRI->createVirtualRegister(TRC);
6534 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6536 .addImm(NumLPads >> 16));
6539 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6543 MachineConstantPool *ConstantPool = MF->getConstantPool();
6544 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6545 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6547 // MachineConstantPool wants an explicit alignment.
6548 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6550 Align = getDataLayout()->getTypeAllocSize(C->getType());
6551 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6553 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6554 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6555 .addReg(VReg1, RegState::Define)
6556 .addConstantPoolIndex(Idx)
6558 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6560 .addReg(VReg1, RegState::Kill));
6563 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6568 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6570 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6572 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6573 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6574 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6575 .addJumpTableIndex(MJTI)
6578 MachineMemOperand *JTMMOLd =
6579 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6580 MachineMemOperand::MOLoad, 4, 4);
6581 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6583 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6584 .addReg(NewVReg3, RegState::Kill)
6587 .addMemOperand(JTMMOLd));
6589 if (RelocM == Reloc::PIC_) {
6590 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6591 .addReg(NewVReg5, RegState::Kill)
6593 .addJumpTableIndex(MJTI)
6596 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6597 .addReg(NewVReg5, RegState::Kill)
6598 .addJumpTableIndex(MJTI)
6603 // Add the jump table entries as successors to the MBB.
6604 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6605 for (std::vector<MachineBasicBlock*>::iterator
6606 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6607 MachineBasicBlock *CurMBB = *I;
6608 if (SeenMBBs.insert(CurMBB))
6609 DispContBB->addSuccessor(CurMBB);
6612 // N.B. the order the invoke BBs are processed in doesn't matter here.
6613 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6614 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6615 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6616 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6617 MachineBasicBlock *BB = *I;
6619 // Remove the landing pad successor from the invoke block and replace it
6620 // with the new dispatch block.
6621 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6623 while (!Successors.empty()) {
6624 MachineBasicBlock *SMBB = Successors.pop_back_val();
6625 if (SMBB->isLandingPad()) {
6626 BB->removeSuccessor(SMBB);
6627 MBBLPads.push_back(SMBB);
6631 BB->addSuccessor(DispatchBB);
6633 // Find the invoke call and mark all of the callee-saved registers as
6634 // 'implicit defined' so that they're spilled. This prevents code from
6635 // moving instructions to before the EH block, where they will never be
6637 for (MachineBasicBlock::reverse_iterator
6638 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6639 if (!II->isCall()) continue;
6641 DenseMap<unsigned, bool> DefRegs;
6642 for (MachineInstr::mop_iterator
6643 OI = II->operands_begin(), OE = II->operands_end();
6645 if (!OI->isReg()) continue;
6646 DefRegs[OI->getReg()] = true;
6649 MachineInstrBuilder MIB(*MF, &*II);
6651 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6652 unsigned Reg = SavedRegs[i];
6653 if (Subtarget->isThumb2() &&
6654 !ARM::tGPRRegClass.contains(Reg) &&
6655 !ARM::hGPRRegClass.contains(Reg))
6657 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6659 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6662 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6669 // Mark all former landing pads as non-landing pads. The dispatch is the only
6671 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6672 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6673 (*I)->setIsLandingPad(false);
6675 // The instruction is gone now.
6676 MI->eraseFromParent();
6682 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6683 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6684 E = MBB->succ_end(); I != E; ++I)
6687 llvm_unreachable("Expecting a BB with two successors!");
6690 /// Return the load opcode for a given load size. If load size >= 8,
6691 /// neon opcode will be returned.
6692 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6694 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6695 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6697 return LdSize == 4 ? ARM::tLDRi
6698 : LdSize == 2 ? ARM::tLDRHi
6699 : LdSize == 1 ? ARM::tLDRBi : 0;
6701 return LdSize == 4 ? ARM::t2LDR_POST
6702 : LdSize == 2 ? ARM::t2LDRH_POST
6703 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6704 return LdSize == 4 ? ARM::LDR_POST_IMM
6705 : LdSize == 2 ? ARM::LDRH_POST
6706 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6709 /// Return the store opcode for a given store size. If store size >= 8,
6710 /// neon opcode will be returned.
6711 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6713 return StSize == 16 ? ARM::VST1q32wb_fixed
6714 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6716 return StSize == 4 ? ARM::tSTRi
6717 : StSize == 2 ? ARM::tSTRHi
6718 : StSize == 1 ? ARM::tSTRBi : 0;
6720 return StSize == 4 ? ARM::t2STR_POST
6721 : StSize == 2 ? ARM::t2STRH_POST
6722 : StSize == 1 ? ARM::t2STRB_POST : 0;
6723 return StSize == 4 ? ARM::STR_POST_IMM
6724 : StSize == 2 ? ARM::STRH_POST
6725 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6728 /// Emit a post-increment load operation with given size. The instructions
6729 /// will be added to BB at Pos.
6730 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6731 const TargetInstrInfo *TII, DebugLoc dl,
6732 unsigned LdSize, unsigned Data, unsigned AddrIn,
6733 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6734 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6735 assert(LdOpc != 0 && "Should have a load opcode");
6737 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6738 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6740 } else if (IsThumb1) {
6741 // load + update AddrIn
6742 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6743 .addReg(AddrIn).addImm(0));
6744 MachineInstrBuilder MIB =
6745 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6746 MIB = AddDefaultT1CC(MIB);
6747 MIB.addReg(AddrIn).addImm(LdSize);
6748 AddDefaultPred(MIB);
6749 } else if (IsThumb2) {
6750 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6751 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6754 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6755 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6756 .addReg(0).addImm(LdSize));
6760 /// Emit a post-increment store operation with given size. The instructions
6761 /// will be added to BB at Pos.
6762 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6763 const TargetInstrInfo *TII, DebugLoc dl,
6764 unsigned StSize, unsigned Data, unsigned AddrIn,
6765 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6766 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6767 assert(StOpc != 0 && "Should have a store opcode");
6769 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6770 .addReg(AddrIn).addImm(0).addReg(Data));
6771 } else if (IsThumb1) {
6772 // store + update AddrIn
6773 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6774 .addReg(AddrIn).addImm(0));
6775 MachineInstrBuilder MIB =
6776 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6777 MIB = AddDefaultT1CC(MIB);
6778 MIB.addReg(AddrIn).addImm(StSize);
6779 AddDefaultPred(MIB);
6780 } else if (IsThumb2) {
6781 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6782 .addReg(Data).addReg(AddrIn).addImm(StSize));
6784 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6785 .addReg(Data).addReg(AddrIn).addReg(0)
6791 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6792 MachineBasicBlock *BB) const {
6793 // This pseudo instruction has 3 operands: dst, src, size
6794 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6795 // Otherwise, we will generate unrolled scalar copies.
6796 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6797 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6798 MachineFunction::iterator It = BB;
6801 unsigned dest = MI->getOperand(0).getReg();
6802 unsigned src = MI->getOperand(1).getReg();
6803 unsigned SizeVal = MI->getOperand(2).getImm();
6804 unsigned Align = MI->getOperand(3).getImm();
6805 DebugLoc dl = MI->getDebugLoc();
6807 MachineFunction *MF = BB->getParent();
6808 MachineRegisterInfo &MRI = MF->getRegInfo();
6809 unsigned UnitSize = 0;
6810 const TargetRegisterClass *TRC = nullptr;
6811 const TargetRegisterClass *VecTRC = nullptr;
6813 bool IsThumb1 = Subtarget->isThumb1Only();
6814 bool IsThumb2 = Subtarget->isThumb2();
6818 } else if (Align & 2) {
6821 // Check whether we can use NEON instructions.
6822 if (!MF->getFunction()->getAttributes().
6823 hasAttribute(AttributeSet::FunctionIndex,
6824 Attribute::NoImplicitFloat) &&
6825 Subtarget->hasNEON()) {
6826 if ((Align % 16 == 0) && SizeVal >= 16)
6828 else if ((Align % 8 == 0) && SizeVal >= 8)
6831 // Can't use NEON instructions.
6836 // Select the correct opcode and register class for unit size load/store
6837 bool IsNeon = UnitSize >= 8;
6838 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6839 : (const TargetRegisterClass *)&ARM::GPRRegClass;
6841 VecTRC = UnitSize == 16
6842 ? (const TargetRegisterClass *)&ARM::DPairRegClass
6844 ? (const TargetRegisterClass *)&ARM::DPRRegClass
6847 unsigned BytesLeft = SizeVal % UnitSize;
6848 unsigned LoopSize = SizeVal - BytesLeft;
6850 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6851 // Use LDR and STR to copy.
6852 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6853 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6854 unsigned srcIn = src;
6855 unsigned destIn = dest;
6856 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6857 unsigned srcOut = MRI.createVirtualRegister(TRC);
6858 unsigned destOut = MRI.createVirtualRegister(TRC);
6859 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6860 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6861 IsThumb1, IsThumb2);
6862 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6863 IsThumb1, IsThumb2);
6868 // Handle the leftover bytes with LDRB and STRB.
6869 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6870 // [destOut] = STRB_POST(scratch, destIn, 1)
6871 for (unsigned i = 0; i < BytesLeft; i++) {
6872 unsigned srcOut = MRI.createVirtualRegister(TRC);
6873 unsigned destOut = MRI.createVirtualRegister(TRC);
6874 unsigned scratch = MRI.createVirtualRegister(TRC);
6875 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6876 IsThumb1, IsThumb2);
6877 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6878 IsThumb1, IsThumb2);
6882 MI->eraseFromParent(); // The instruction is gone now.
6886 // Expand the pseudo op to a loop.
6889 // movw varEnd, # --> with thumb2
6891 // ldrcp varEnd, idx --> without thumb2
6892 // fallthrough --> loopMBB
6894 // PHI varPhi, varEnd, varLoop
6895 // PHI srcPhi, src, srcLoop
6896 // PHI destPhi, dst, destLoop
6897 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6898 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6899 // subs varLoop, varPhi, #UnitSize
6901 // fallthrough --> exitMBB
6903 // epilogue to handle left-over bytes
6904 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6905 // [destOut] = STRB_POST(scratch, destLoop, 1)
6906 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6907 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6908 MF->insert(It, loopMBB);
6909 MF->insert(It, exitMBB);
6911 // Transfer the remainder of BB and its successor edges to exitMBB.
6912 exitMBB->splice(exitMBB->begin(), BB,
6913 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6914 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6916 // Load an immediate to varEnd.
6917 unsigned varEnd = MRI.createVirtualRegister(TRC);
6919 unsigned Vtmp = varEnd;
6920 if ((LoopSize & 0xFFFF0000) != 0)
6921 Vtmp = MRI.createVirtualRegister(TRC);
6922 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
6923 .addImm(LoopSize & 0xFFFF));
6925 if ((LoopSize & 0xFFFF0000) != 0)
6926 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6927 .addReg(Vtmp).addImm(LoopSize >> 16));
6929 MachineConstantPool *ConstantPool = MF->getConstantPool();
6930 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6931 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6933 // MachineConstantPool wants an explicit alignment.
6934 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6936 Align = getDataLayout()->getTypeAllocSize(C->getType());
6937 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6940 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
6941 varEnd, RegState::Define).addConstantPoolIndex(Idx));
6943 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
6944 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
6946 BB->addSuccessor(loopMBB);
6948 // Generate the loop body:
6949 // varPhi = PHI(varLoop, varEnd)
6950 // srcPhi = PHI(srcLoop, src)
6951 // destPhi = PHI(destLoop, dst)
6952 MachineBasicBlock *entryBB = BB;
6954 unsigned varLoop = MRI.createVirtualRegister(TRC);
6955 unsigned varPhi = MRI.createVirtualRegister(TRC);
6956 unsigned srcLoop = MRI.createVirtualRegister(TRC);
6957 unsigned srcPhi = MRI.createVirtualRegister(TRC);
6958 unsigned destLoop = MRI.createVirtualRegister(TRC);
6959 unsigned destPhi = MRI.createVirtualRegister(TRC);
6961 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6962 .addReg(varLoop).addMBB(loopMBB)
6963 .addReg(varEnd).addMBB(entryBB);
6964 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6965 .addReg(srcLoop).addMBB(loopMBB)
6966 .addReg(src).addMBB(entryBB);
6967 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6968 .addReg(destLoop).addMBB(loopMBB)
6969 .addReg(dest).addMBB(entryBB);
6971 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6972 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6973 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6974 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
6975 IsThumb1, IsThumb2);
6976 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
6977 IsThumb1, IsThumb2);
6979 // Decrement loop variable by UnitSize.
6981 MachineInstrBuilder MIB =
6982 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
6983 MIB = AddDefaultT1CC(MIB);
6984 MIB.addReg(varPhi).addImm(UnitSize);
6985 AddDefaultPred(MIB);
6987 MachineInstrBuilder MIB =
6988 BuildMI(*BB, BB->end(), dl,
6989 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6990 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6991 MIB->getOperand(5).setReg(ARM::CPSR);
6992 MIB->getOperand(5).setIsDef(true);
6994 BuildMI(*BB, BB->end(), dl,
6995 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
6996 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6998 // loopMBB can loop back to loopMBB or fall through to exitMBB.
6999 BB->addSuccessor(loopMBB);
7000 BB->addSuccessor(exitMBB);
7002 // Add epilogue to handle BytesLeft.
7004 MachineInstr *StartOfExit = exitMBB->begin();
7006 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7007 // [destOut] = STRB_POST(scratch, destLoop, 1)
7008 unsigned srcIn = srcLoop;
7009 unsigned destIn = destLoop;
7010 for (unsigned i = 0; i < BytesLeft; i++) {
7011 unsigned srcOut = MRI.createVirtualRegister(TRC);
7012 unsigned destOut = MRI.createVirtualRegister(TRC);
7013 unsigned scratch = MRI.createVirtualRegister(TRC);
7014 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7015 IsThumb1, IsThumb2);
7016 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7017 IsThumb1, IsThumb2);
7022 MI->eraseFromParent(); // The instruction is gone now.
7027 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7028 MachineBasicBlock *BB) const {
7029 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7030 DebugLoc dl = MI->getDebugLoc();
7031 bool isThumb2 = Subtarget->isThumb2();
7032 switch (MI->getOpcode()) {
7035 llvm_unreachable("Unexpected instr type to insert");
7037 // The Thumb2 pre-indexed stores have the same MI operands, they just
7038 // define them differently in the .td files from the isel patterns, so
7039 // they need pseudos.
7040 case ARM::t2STR_preidx:
7041 MI->setDesc(TII->get(ARM::t2STR_PRE));
7043 case ARM::t2STRB_preidx:
7044 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7046 case ARM::t2STRH_preidx:
7047 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7050 case ARM::STRi_preidx:
7051 case ARM::STRBi_preidx: {
7052 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7053 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7054 // Decode the offset.
7055 unsigned Offset = MI->getOperand(4).getImm();
7056 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7057 Offset = ARM_AM::getAM2Offset(Offset);
7061 MachineMemOperand *MMO = *MI->memoperands_begin();
7062 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7063 .addOperand(MI->getOperand(0)) // Rn_wb
7064 .addOperand(MI->getOperand(1)) // Rt
7065 .addOperand(MI->getOperand(2)) // Rn
7066 .addImm(Offset) // offset (skip GPR==zero_reg)
7067 .addOperand(MI->getOperand(5)) // pred
7068 .addOperand(MI->getOperand(6))
7069 .addMemOperand(MMO);
7070 MI->eraseFromParent();
7073 case ARM::STRr_preidx:
7074 case ARM::STRBr_preidx:
7075 case ARM::STRH_preidx: {
7077 switch (MI->getOpcode()) {
7078 default: llvm_unreachable("unexpected opcode!");
7079 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7080 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7081 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7083 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7084 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7085 MIB.addOperand(MI->getOperand(i));
7086 MI->eraseFromParent();
7090 case ARM::tMOVCCr_pseudo: {
7091 // To "insert" a SELECT_CC instruction, we actually have to insert the
7092 // diamond control-flow pattern. The incoming instruction knows the
7093 // destination vreg to set, the condition code register to branch on, the
7094 // true/false values to select between, and a branch opcode to use.
7095 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7096 MachineFunction::iterator It = BB;
7102 // cmpTY ccX, r1, r2
7104 // fallthrough --> copy0MBB
7105 MachineBasicBlock *thisMBB = BB;
7106 MachineFunction *F = BB->getParent();
7107 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7108 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7109 F->insert(It, copy0MBB);
7110 F->insert(It, sinkMBB);
7112 // Transfer the remainder of BB and its successor edges to sinkMBB.
7113 sinkMBB->splice(sinkMBB->begin(), BB,
7114 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7115 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7117 BB->addSuccessor(copy0MBB);
7118 BB->addSuccessor(sinkMBB);
7120 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7121 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7124 // %FalseValue = ...
7125 // # fallthrough to sinkMBB
7128 // Update machine-CFG edges
7129 BB->addSuccessor(sinkMBB);
7132 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7135 BuildMI(*BB, BB->begin(), dl,
7136 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7137 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7138 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7140 MI->eraseFromParent(); // The pseudo instruction is gone now.
7145 case ARM::BCCZi64: {
7146 // If there is an unconditional branch to the other successor, remove it.
7147 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7149 // Compare both parts that make up the double comparison separately for
7151 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7153 unsigned LHS1 = MI->getOperand(1).getReg();
7154 unsigned LHS2 = MI->getOperand(2).getReg();
7156 AddDefaultPred(BuildMI(BB, dl,
7157 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7158 .addReg(LHS1).addImm(0));
7159 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7160 .addReg(LHS2).addImm(0)
7161 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7163 unsigned RHS1 = MI->getOperand(3).getReg();
7164 unsigned RHS2 = MI->getOperand(4).getReg();
7165 AddDefaultPred(BuildMI(BB, dl,
7166 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7167 .addReg(LHS1).addReg(RHS1));
7168 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7169 .addReg(LHS2).addReg(RHS2)
7170 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7173 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7174 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7175 if (MI->getOperand(0).getImm() == ARMCC::NE)
7176 std::swap(destMBB, exitMBB);
7178 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7179 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7181 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7183 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7185 MI->eraseFromParent(); // The pseudo instruction is gone now.
7189 case ARM::Int_eh_sjlj_setjmp:
7190 case ARM::Int_eh_sjlj_setjmp_nofp:
7191 case ARM::tInt_eh_sjlj_setjmp:
7192 case ARM::t2Int_eh_sjlj_setjmp:
7193 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7194 EmitSjLjDispatchBlock(MI, BB);
7199 // To insert an ABS instruction, we have to insert the
7200 // diamond control-flow pattern. The incoming instruction knows the
7201 // source vreg to test against 0, the destination vreg to set,
7202 // the condition code register to branch on, the
7203 // true/false values to select between, and a branch opcode to use.
7208 // BCC (branch to SinkBB if V0 >= 0)
7209 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7210 // SinkBB: V1 = PHI(V2, V3)
7211 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7212 MachineFunction::iterator BBI = BB;
7214 MachineFunction *Fn = BB->getParent();
7215 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7216 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7217 Fn->insert(BBI, RSBBB);
7218 Fn->insert(BBI, SinkBB);
7220 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7221 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7222 bool isThumb2 = Subtarget->isThumb2();
7223 MachineRegisterInfo &MRI = Fn->getRegInfo();
7224 // In Thumb mode S must not be specified if source register is the SP or
7225 // PC and if destination register is the SP, so restrict register class
7226 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7227 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7228 (const TargetRegisterClass*)&ARM::GPRRegClass);
7230 // Transfer the remainder of BB and its successor edges to sinkMBB.
7231 SinkBB->splice(SinkBB->begin(), BB,
7232 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7233 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7235 BB->addSuccessor(RSBBB);
7236 BB->addSuccessor(SinkBB);
7238 // fall through to SinkMBB
7239 RSBBB->addSuccessor(SinkBB);
7241 // insert a cmp at the end of BB
7242 AddDefaultPred(BuildMI(BB, dl,
7243 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7244 .addReg(ABSSrcReg).addImm(0));
7246 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7248 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7249 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7251 // insert rsbri in RSBBB
7252 // Note: BCC and rsbri will be converted into predicated rsbmi
7253 // by if-conversion pass
7254 BuildMI(*RSBBB, RSBBB->begin(), dl,
7255 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7256 .addReg(ABSSrcReg, RegState::Kill)
7257 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7259 // insert PHI in SinkBB,
7260 // reuse ABSDstReg to not change uses of ABS instruction
7261 BuildMI(*SinkBB, SinkBB->begin(), dl,
7262 TII->get(ARM::PHI), ABSDstReg)
7263 .addReg(NewRsbDstReg).addMBB(RSBBB)
7264 .addReg(ABSSrcReg).addMBB(BB);
7266 // remove ABS instruction
7267 MI->eraseFromParent();
7269 // return last added BB
7272 case ARM::COPY_STRUCT_BYVAL_I32:
7274 return EmitStructByval(MI, BB);
7278 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7279 SDNode *Node) const {
7280 if (!MI->hasPostISelHook()) {
7281 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7282 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7286 const MCInstrDesc *MCID = &MI->getDesc();
7287 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7288 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7289 // operand is still set to noreg. If needed, set the optional operand's
7290 // register to CPSR, and remove the redundant implicit def.
7292 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7294 // Rename pseudo opcodes.
7295 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7297 const ARMBaseInstrInfo *TII =
7298 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7299 MCID = &TII->get(NewOpc);
7301 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7302 "converted opcode should be the same except for cc_out");
7306 // Add the optional cc_out operand
7307 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7309 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7311 // Any ARM instruction that sets the 's' bit should specify an optional
7312 // "cc_out" operand in the last operand position.
7313 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7314 assert(!NewOpc && "Optional cc_out operand required");
7317 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7318 // since we already have an optional CPSR def.
7319 bool definesCPSR = false;
7320 bool deadCPSR = false;
7321 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7323 const MachineOperand &MO = MI->getOperand(i);
7324 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7328 MI->RemoveOperand(i);
7333 assert(!NewOpc && "Optional cc_out operand required");
7336 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7338 assert(!MI->getOperand(ccOutIdx).getReg() &&
7339 "expect uninitialized optional cc_out operand");
7343 // If this instruction was defined with an optional CPSR def and its dag node
7344 // had a live implicit CPSR def, then activate the optional CPSR def.
7345 MachineOperand &MO = MI->getOperand(ccOutIdx);
7346 MO.setReg(ARM::CPSR);
7350 //===----------------------------------------------------------------------===//
7351 // ARM Optimization Hooks
7352 //===----------------------------------------------------------------------===//
7354 // Helper function that checks if N is a null or all ones constant.
7355 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7356 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7359 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7362 // Return true if N is conditionally 0 or all ones.
7363 // Detects these expressions where cc is an i1 value:
7365 // (select cc 0, y) [AllOnes=0]
7366 // (select cc y, 0) [AllOnes=0]
7367 // (zext cc) [AllOnes=0]
7368 // (sext cc) [AllOnes=0/1]
7369 // (select cc -1, y) [AllOnes=1]
7370 // (select cc y, -1) [AllOnes=1]
7372 // Invert is set when N is the null/all ones constant when CC is false.
7373 // OtherOp is set to the alternative value of N.
7374 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7375 SDValue &CC, bool &Invert,
7377 SelectionDAG &DAG) {
7378 switch (N->getOpcode()) {
7379 default: return false;
7381 CC = N->getOperand(0);
7382 SDValue N1 = N->getOperand(1);
7383 SDValue N2 = N->getOperand(2);
7384 if (isZeroOrAllOnes(N1, AllOnes)) {
7389 if (isZeroOrAllOnes(N2, AllOnes)) {
7396 case ISD::ZERO_EXTEND:
7397 // (zext cc) can never be the all ones value.
7401 case ISD::SIGN_EXTEND: {
7402 EVT VT = N->getValueType(0);
7403 CC = N->getOperand(0);
7404 if (CC.getValueType() != MVT::i1)
7408 // When looking for an AllOnes constant, N is an sext, and the 'other'
7410 OtherOp = DAG.getConstant(0, VT);
7411 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7412 // When looking for a 0 constant, N can be zext or sext.
7413 OtherOp = DAG.getConstant(1, VT);
7415 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7421 // Combine a constant select operand into its use:
7423 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7424 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7425 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7426 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7427 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7429 // The transform is rejected if the select doesn't have a constant operand that
7430 // is null, or all ones when AllOnes is set.
7432 // Also recognize sext/zext from i1:
7434 // (add (zext cc), x) -> (select cc (add x, 1), x)
7435 // (add (sext cc), x) -> (select cc (add x, -1), x)
7437 // These transformations eventually create predicated instructions.
7439 // @param N The node to transform.
7440 // @param Slct The N operand that is a select.
7441 // @param OtherOp The other N operand (x above).
7442 // @param DCI Context.
7443 // @param AllOnes Require the select constant to be all ones instead of null.
7444 // @returns The new node, or SDValue() on failure.
7446 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7447 TargetLowering::DAGCombinerInfo &DCI,
7448 bool AllOnes = false) {
7449 SelectionDAG &DAG = DCI.DAG;
7450 EVT VT = N->getValueType(0);
7451 SDValue NonConstantVal;
7454 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7455 NonConstantVal, DAG))
7458 // Slct is now know to be the desired identity constant when CC is true.
7459 SDValue TrueVal = OtherOp;
7460 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7461 OtherOp, NonConstantVal);
7462 // Unless SwapSelectOps says CC should be false.
7464 std::swap(TrueVal, FalseVal);
7466 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7467 CCOp, TrueVal, FalseVal);
7470 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7472 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7473 TargetLowering::DAGCombinerInfo &DCI) {
7474 SDValue N0 = N->getOperand(0);
7475 SDValue N1 = N->getOperand(1);
7476 if (N0.getNode()->hasOneUse()) {
7477 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7478 if (Result.getNode())
7481 if (N1.getNode()->hasOneUse()) {
7482 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7483 if (Result.getNode())
7489 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7490 // (only after legalization).
7491 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7492 TargetLowering::DAGCombinerInfo &DCI,
7493 const ARMSubtarget *Subtarget) {
7495 // Only perform optimization if after legalize, and if NEON is available. We
7496 // also expected both operands to be BUILD_VECTORs.
7497 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7498 || N0.getOpcode() != ISD::BUILD_VECTOR
7499 || N1.getOpcode() != ISD::BUILD_VECTOR)
7502 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7503 EVT VT = N->getValueType(0);
7504 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7507 // Check that the vector operands are of the right form.
7508 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7509 // operands, where N is the size of the formed vector.
7510 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7511 // index such that we have a pair wise add pattern.
7513 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7514 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7516 SDValue Vec = N0->getOperand(0)->getOperand(0);
7517 SDNode *V = Vec.getNode();
7518 unsigned nextIndex = 0;
7520 // For each operands to the ADD which are BUILD_VECTORs,
7521 // check to see if each of their operands are an EXTRACT_VECTOR with
7522 // the same vector and appropriate index.
7523 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7524 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7525 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7527 SDValue ExtVec0 = N0->getOperand(i);
7528 SDValue ExtVec1 = N1->getOperand(i);
7530 // First operand is the vector, verify its the same.
7531 if (V != ExtVec0->getOperand(0).getNode() ||
7532 V != ExtVec1->getOperand(0).getNode())
7535 // Second is the constant, verify its correct.
7536 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7537 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7539 // For the constant, we want to see all the even or all the odd.
7540 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7541 || C1->getZExtValue() != nextIndex+1)
7550 // Create VPADDL node.
7551 SelectionDAG &DAG = DCI.DAG;
7552 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7554 // Build operand list.
7555 SmallVector<SDValue, 8> Ops;
7556 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7557 TLI.getPointerTy()));
7559 // Input is the vector.
7562 // Get widened type and narrowed type.
7564 unsigned numElem = VT.getVectorNumElements();
7566 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7567 switch (inputLaneType.getSimpleVT().SimpleTy) {
7568 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7569 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7570 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7572 llvm_unreachable("Invalid vector element type for padd optimization.");
7575 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7576 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7577 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7580 static SDValue findMUL_LOHI(SDValue V) {
7581 if (V->getOpcode() == ISD::UMUL_LOHI ||
7582 V->getOpcode() == ISD::SMUL_LOHI)
7587 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7588 TargetLowering::DAGCombinerInfo &DCI,
7589 const ARMSubtarget *Subtarget) {
7591 if (Subtarget->isThumb1Only()) return SDValue();
7593 // Only perform the checks after legalize when the pattern is available.
7594 if (DCI.isBeforeLegalize()) return SDValue();
7596 // Look for multiply add opportunities.
7597 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7598 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7599 // a glue link from the first add to the second add.
7600 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7601 // a S/UMLAL instruction.
7604 // \ / \ [no multiline comment]
7610 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7611 SDValue AddcOp0 = AddcNode->getOperand(0);
7612 SDValue AddcOp1 = AddcNode->getOperand(1);
7614 // Check if the two operands are from the same mul_lohi node.
7615 if (AddcOp0.getNode() == AddcOp1.getNode())
7618 assert(AddcNode->getNumValues() == 2 &&
7619 AddcNode->getValueType(0) == MVT::i32 &&
7620 "Expect ADDC with two result values. First: i32");
7622 // Check that we have a glued ADDC node.
7623 if (AddcNode->getValueType(1) != MVT::Glue)
7626 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7627 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7628 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7629 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7630 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7633 // Look for the glued ADDE.
7634 SDNode* AddeNode = AddcNode->getGluedUser();
7638 // Make sure it is really an ADDE.
7639 if (AddeNode->getOpcode() != ISD::ADDE)
7642 assert(AddeNode->getNumOperands() == 3 &&
7643 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7644 "ADDE node has the wrong inputs");
7646 // Check for the triangle shape.
7647 SDValue AddeOp0 = AddeNode->getOperand(0);
7648 SDValue AddeOp1 = AddeNode->getOperand(1);
7650 // Make sure that the ADDE operands are not coming from the same node.
7651 if (AddeOp0.getNode() == AddeOp1.getNode())
7654 // Find the MUL_LOHI node walking up ADDE's operands.
7655 bool IsLeftOperandMUL = false;
7656 SDValue MULOp = findMUL_LOHI(AddeOp0);
7657 if (MULOp == SDValue())
7658 MULOp = findMUL_LOHI(AddeOp1);
7660 IsLeftOperandMUL = true;
7661 if (MULOp == SDValue())
7664 // Figure out the right opcode.
7665 unsigned Opc = MULOp->getOpcode();
7666 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7668 // Figure out the high and low input values to the MLAL node.
7669 SDValue* HiMul = &MULOp;
7670 SDValue* HiAdd = nullptr;
7671 SDValue* LoMul = nullptr;
7672 SDValue* LowAdd = nullptr;
7674 if (IsLeftOperandMUL)
7680 if (AddcOp0->getOpcode() == Opc) {
7684 if (AddcOp1->getOpcode() == Opc) {
7692 if (LoMul->getNode() != HiMul->getNode())
7695 // Create the merged node.
7696 SelectionDAG &DAG = DCI.DAG;
7698 // Build operand list.
7699 SmallVector<SDValue, 8> Ops;
7700 Ops.push_back(LoMul->getOperand(0));
7701 Ops.push_back(LoMul->getOperand(1));
7702 Ops.push_back(*LowAdd);
7703 Ops.push_back(*HiAdd);
7705 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7706 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7708 // Replace the ADDs' nodes uses by the MLA node's values.
7709 SDValue HiMLALResult(MLALNode.getNode(), 1);
7710 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7712 SDValue LoMLALResult(MLALNode.getNode(), 0);
7713 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7715 // Return original node to notify the driver to stop replacing.
7716 SDValue resNode(AddcNode, 0);
7720 /// PerformADDCCombine - Target-specific dag combine transform from
7721 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7722 static SDValue PerformADDCCombine(SDNode *N,
7723 TargetLowering::DAGCombinerInfo &DCI,
7724 const ARMSubtarget *Subtarget) {
7726 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7730 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7731 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7732 /// called with the default operands, and if that fails, with commuted
7734 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7735 TargetLowering::DAGCombinerInfo &DCI,
7736 const ARMSubtarget *Subtarget){
7738 // Attempt to create vpaddl for this add.
7739 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7740 if (Result.getNode())
7743 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7744 if (N0.getNode()->hasOneUse()) {
7745 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7746 if (Result.getNode()) return Result;
7751 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7753 static SDValue PerformADDCombine(SDNode *N,
7754 TargetLowering::DAGCombinerInfo &DCI,
7755 const ARMSubtarget *Subtarget) {
7756 SDValue N0 = N->getOperand(0);
7757 SDValue N1 = N->getOperand(1);
7759 // First try with the default operand order.
7760 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7761 if (Result.getNode())
7764 // If that didn't work, try again with the operands commuted.
7765 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7768 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7770 static SDValue PerformSUBCombine(SDNode *N,
7771 TargetLowering::DAGCombinerInfo &DCI) {
7772 SDValue N0 = N->getOperand(0);
7773 SDValue N1 = N->getOperand(1);
7775 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7776 if (N1.getNode()->hasOneUse()) {
7777 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7778 if (Result.getNode()) return Result;
7784 /// PerformVMULCombine
7785 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7786 /// special multiplier accumulator forwarding.
7792 // However, for (A + B) * (A + B),
7799 static SDValue PerformVMULCombine(SDNode *N,
7800 TargetLowering::DAGCombinerInfo &DCI,
7801 const ARMSubtarget *Subtarget) {
7802 if (!Subtarget->hasVMLxForwarding())
7805 SelectionDAG &DAG = DCI.DAG;
7806 SDValue N0 = N->getOperand(0);
7807 SDValue N1 = N->getOperand(1);
7808 unsigned Opcode = N0.getOpcode();
7809 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7810 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7811 Opcode = N1.getOpcode();
7812 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7813 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7821 EVT VT = N->getValueType(0);
7823 SDValue N00 = N0->getOperand(0);
7824 SDValue N01 = N0->getOperand(1);
7825 return DAG.getNode(Opcode, DL, VT,
7826 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7827 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7830 static SDValue PerformMULCombine(SDNode *N,
7831 TargetLowering::DAGCombinerInfo &DCI,
7832 const ARMSubtarget *Subtarget) {
7833 SelectionDAG &DAG = DCI.DAG;
7835 if (Subtarget->isThumb1Only())
7838 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7841 EVT VT = N->getValueType(0);
7842 if (VT.is64BitVector() || VT.is128BitVector())
7843 return PerformVMULCombine(N, DCI, Subtarget);
7847 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7851 int64_t MulAmt = C->getSExtValue();
7852 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7854 ShiftAmt = ShiftAmt & (32 - 1);
7855 SDValue V = N->getOperand(0);
7859 MulAmt >>= ShiftAmt;
7862 if (isPowerOf2_32(MulAmt - 1)) {
7863 // (mul x, 2^N + 1) => (add (shl x, N), x)
7864 Res = DAG.getNode(ISD::ADD, DL, VT,
7866 DAG.getNode(ISD::SHL, DL, VT,
7868 DAG.getConstant(Log2_32(MulAmt - 1),
7870 } else if (isPowerOf2_32(MulAmt + 1)) {
7871 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7872 Res = DAG.getNode(ISD::SUB, DL, VT,
7873 DAG.getNode(ISD::SHL, DL, VT,
7875 DAG.getConstant(Log2_32(MulAmt + 1),
7881 uint64_t MulAmtAbs = -MulAmt;
7882 if (isPowerOf2_32(MulAmtAbs + 1)) {
7883 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7884 Res = DAG.getNode(ISD::SUB, DL, VT,
7886 DAG.getNode(ISD::SHL, DL, VT,
7888 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7890 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7891 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7892 Res = DAG.getNode(ISD::ADD, DL, VT,
7894 DAG.getNode(ISD::SHL, DL, VT,
7896 DAG.getConstant(Log2_32(MulAmtAbs-1),
7898 Res = DAG.getNode(ISD::SUB, DL, VT,
7899 DAG.getConstant(0, MVT::i32),Res);
7906 Res = DAG.getNode(ISD::SHL, DL, VT,
7907 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7909 // Do not add new nodes to DAG combiner worklist.
7910 DCI.CombineTo(N, Res, false);
7914 static SDValue PerformANDCombine(SDNode *N,
7915 TargetLowering::DAGCombinerInfo &DCI,
7916 const ARMSubtarget *Subtarget) {
7918 // Attempt to use immediate-form VBIC
7919 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7921 EVT VT = N->getValueType(0);
7922 SelectionDAG &DAG = DCI.DAG;
7924 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7927 APInt SplatBits, SplatUndef;
7928 unsigned SplatBitSize;
7931 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7932 if (SplatBitSize <= 64) {
7934 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7935 SplatUndef.getZExtValue(), SplatBitSize,
7936 DAG, VbicVT, VT.is128BitVector(),
7938 if (Val.getNode()) {
7940 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7941 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7942 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7947 if (!Subtarget->isThumb1Only()) {
7948 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7949 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7950 if (Result.getNode())
7957 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7958 static SDValue PerformORCombine(SDNode *N,
7959 TargetLowering::DAGCombinerInfo &DCI,
7960 const ARMSubtarget *Subtarget) {
7961 // Attempt to use immediate-form VORR
7962 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7964 EVT VT = N->getValueType(0);
7965 SelectionDAG &DAG = DCI.DAG;
7967 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7970 APInt SplatBits, SplatUndef;
7971 unsigned SplatBitSize;
7973 if (BVN && Subtarget->hasNEON() &&
7974 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7975 if (SplatBitSize <= 64) {
7977 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7978 SplatUndef.getZExtValue(), SplatBitSize,
7979 DAG, VorrVT, VT.is128BitVector(),
7981 if (Val.getNode()) {
7983 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7984 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7985 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7990 if (!Subtarget->isThumb1Only()) {
7991 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7992 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7993 if (Result.getNode())
7997 // The code below optimizes (or (and X, Y), Z).
7998 // The AND operand needs to have a single user to make these optimizations
8000 SDValue N0 = N->getOperand(0);
8001 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8003 SDValue N1 = N->getOperand(1);
8005 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8006 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8007 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8009 unsigned SplatBitSize;
8012 APInt SplatBits0, SplatBits1;
8013 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8014 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8015 // Ensure that the second operand of both ands are constants
8016 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8017 HasAnyUndefs) && !HasAnyUndefs) {
8018 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8019 HasAnyUndefs) && !HasAnyUndefs) {
8020 // Ensure that the bit width of the constants are the same and that
8021 // the splat arguments are logical inverses as per the pattern we
8022 // are trying to simplify.
8023 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8024 SplatBits0 == ~SplatBits1) {
8025 // Canonicalize the vector type to make instruction selection
8027 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8028 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8032 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8038 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8041 // BFI is only available on V6T2+
8042 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8046 // 1) or (and A, mask), val => ARMbfi A, val, mask
8047 // iff (val & mask) == val
8049 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8050 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8051 // && mask == ~mask2
8052 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8053 // && ~mask == mask2
8054 // (i.e., copy a bitfield value into another bitfield of the same width)
8059 SDValue N00 = N0.getOperand(0);
8061 // The value and the mask need to be constants so we can verify this is
8062 // actually a bitfield set. If the mask is 0xffff, we can do better
8063 // via a movt instruction, so don't use BFI in that case.
8064 SDValue MaskOp = N0.getOperand(1);
8065 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8068 unsigned Mask = MaskC->getZExtValue();
8072 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8073 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8075 unsigned Val = N1C->getZExtValue();
8076 if ((Val & ~Mask) != Val)
8079 if (ARM::isBitFieldInvertedMask(Mask)) {
8080 Val >>= countTrailingZeros(~Mask);
8082 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8083 DAG.getConstant(Val, MVT::i32),
8084 DAG.getConstant(Mask, MVT::i32));
8086 // Do not add new nodes to DAG combiner worklist.
8087 DCI.CombineTo(N, Res, false);
8090 } else if (N1.getOpcode() == ISD::AND) {
8091 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8092 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8095 unsigned Mask2 = N11C->getZExtValue();
8097 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8099 if (ARM::isBitFieldInvertedMask(Mask) &&
8101 // The pack halfword instruction works better for masks that fit it,
8102 // so use that when it's available.
8103 if (Subtarget->hasT2ExtractPack() &&
8104 (Mask == 0xffff || Mask == 0xffff0000))
8107 unsigned amt = countTrailingZeros(Mask2);
8108 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8109 DAG.getConstant(amt, MVT::i32));
8110 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8111 DAG.getConstant(Mask, MVT::i32));
8112 // Do not add new nodes to DAG combiner worklist.
8113 DCI.CombineTo(N, Res, false);
8115 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8117 // The pack halfword instruction works better for masks that fit it,
8118 // so use that when it's available.
8119 if (Subtarget->hasT2ExtractPack() &&
8120 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8123 unsigned lsb = countTrailingZeros(Mask);
8124 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8125 DAG.getConstant(lsb, MVT::i32));
8126 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8127 DAG.getConstant(Mask2, MVT::i32));
8128 // Do not add new nodes to DAG combiner worklist.
8129 DCI.CombineTo(N, Res, false);
8134 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8135 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8136 ARM::isBitFieldInvertedMask(~Mask)) {
8137 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8138 // where lsb(mask) == #shamt and masked bits of B are known zero.
8139 SDValue ShAmt = N00.getOperand(1);
8140 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8141 unsigned LSB = countTrailingZeros(Mask);
8145 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8146 DAG.getConstant(~Mask, MVT::i32));
8148 // Do not add new nodes to DAG combiner worklist.
8149 DCI.CombineTo(N, Res, false);
8155 static SDValue PerformXORCombine(SDNode *N,
8156 TargetLowering::DAGCombinerInfo &DCI,
8157 const ARMSubtarget *Subtarget) {
8158 EVT VT = N->getValueType(0);
8159 SelectionDAG &DAG = DCI.DAG;
8161 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8164 if (!Subtarget->isThumb1Only()) {
8165 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8166 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8167 if (Result.getNode())
8174 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8175 /// the bits being cleared by the AND are not demanded by the BFI.
8176 static SDValue PerformBFICombine(SDNode *N,
8177 TargetLowering::DAGCombinerInfo &DCI) {
8178 SDValue N1 = N->getOperand(1);
8179 if (N1.getOpcode() == ISD::AND) {
8180 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8183 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8184 unsigned LSB = countTrailingZeros(~InvMask);
8185 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8186 unsigned Mask = (1 << Width)-1;
8187 unsigned Mask2 = N11C->getZExtValue();
8188 if ((Mask & (~Mask2)) == 0)
8189 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8190 N->getOperand(0), N1.getOperand(0),
8196 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8197 /// ARMISD::VMOVRRD.
8198 static SDValue PerformVMOVRRDCombine(SDNode *N,
8199 TargetLowering::DAGCombinerInfo &DCI) {
8200 // vmovrrd(vmovdrr x, y) -> x,y
8201 SDValue InDouble = N->getOperand(0);
8202 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8203 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8205 // vmovrrd(load f64) -> (load i32), (load i32)
8206 SDNode *InNode = InDouble.getNode();
8207 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8208 InNode->getValueType(0) == MVT::f64 &&
8209 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8210 !cast<LoadSDNode>(InNode)->isVolatile()) {
8211 // TODO: Should this be done for non-FrameIndex operands?
8212 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8214 SelectionDAG &DAG = DCI.DAG;
8216 SDValue BasePtr = LD->getBasePtr();
8217 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8218 LD->getPointerInfo(), LD->isVolatile(),
8219 LD->isNonTemporal(), LD->isInvariant(),
8220 LD->getAlignment());
8222 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8223 DAG.getConstant(4, MVT::i32));
8224 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8225 LD->getPointerInfo(), LD->isVolatile(),
8226 LD->isNonTemporal(), LD->isInvariant(),
8227 std::min(4U, LD->getAlignment() / 2));
8229 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8230 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8231 DCI.RemoveFromWorklist(LD);
8239 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8240 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8241 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8242 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8243 SDValue Op0 = N->getOperand(0);
8244 SDValue Op1 = N->getOperand(1);
8245 if (Op0.getOpcode() == ISD::BITCAST)
8246 Op0 = Op0.getOperand(0);
8247 if (Op1.getOpcode() == ISD::BITCAST)
8248 Op1 = Op1.getOperand(0);
8249 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8250 Op0.getNode() == Op1.getNode() &&
8251 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8252 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8253 N->getValueType(0), Op0.getOperand(0));
8257 /// PerformSTORECombine - Target-specific dag combine xforms for
8259 static SDValue PerformSTORECombine(SDNode *N,
8260 TargetLowering::DAGCombinerInfo &DCI) {
8261 StoreSDNode *St = cast<StoreSDNode>(N);
8262 if (St->isVolatile())
8265 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8266 // pack all of the elements in one place. Next, store to memory in fewer
8268 SDValue StVal = St->getValue();
8269 EVT VT = StVal.getValueType();
8270 if (St->isTruncatingStore() && VT.isVector()) {
8271 SelectionDAG &DAG = DCI.DAG;
8272 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8273 EVT StVT = St->getMemoryVT();
8274 unsigned NumElems = VT.getVectorNumElements();
8275 assert(StVT != VT && "Cannot truncate to the same type");
8276 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8277 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8279 // From, To sizes and ElemCount must be pow of two
8280 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8282 // We are going to use the original vector elt for storing.
8283 // Accumulated smaller vector elements must be a multiple of the store size.
8284 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8286 unsigned SizeRatio = FromEltSz / ToEltSz;
8287 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8289 // Create a type on which we perform the shuffle.
8290 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8291 NumElems*SizeRatio);
8292 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8295 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8296 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8297 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8299 // Can't shuffle using an illegal type.
8300 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8302 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8303 DAG.getUNDEF(WideVec.getValueType()),
8305 // At this point all of the data is stored at the bottom of the
8306 // register. We now need to save it to mem.
8308 // Find the largest store unit
8309 MVT StoreType = MVT::i8;
8310 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8311 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8312 MVT Tp = (MVT::SimpleValueType)tp;
8313 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8316 // Didn't find a legal store type.
8317 if (!TLI.isTypeLegal(StoreType))
8320 // Bitcast the original vector into a vector of store-size units
8321 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8322 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8323 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8324 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8325 SmallVector<SDValue, 8> Chains;
8326 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8327 TLI.getPointerTy());
8328 SDValue BasePtr = St->getBasePtr();
8330 // Perform one or more big stores into memory.
8331 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8332 for (unsigned I = 0; I < E; I++) {
8333 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8334 StoreType, ShuffWide,
8335 DAG.getIntPtrConstant(I));
8336 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8337 St->getPointerInfo(), St->isVolatile(),
8338 St->isNonTemporal(), St->getAlignment());
8339 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8341 Chains.push_back(Ch);
8343 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8346 if (!ISD::isNormalStore(St))
8349 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8350 // ARM stores of arguments in the same cache line.
8351 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8352 StVal.getNode()->hasOneUse()) {
8353 SelectionDAG &DAG = DCI.DAG;
8354 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8356 SDValue BasePtr = St->getBasePtr();
8357 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8358 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8359 BasePtr, St->getPointerInfo(), St->isVolatile(),
8360 St->isNonTemporal(), St->getAlignment());
8362 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8363 DAG.getConstant(4, MVT::i32));
8364 return DAG.getStore(NewST1.getValue(0), DL,
8365 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8366 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8367 St->isNonTemporal(),
8368 std::min(4U, St->getAlignment() / 2));
8371 if (StVal.getValueType() != MVT::i64 ||
8372 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8375 // Bitcast an i64 store extracted from a vector to f64.
8376 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8377 SelectionDAG &DAG = DCI.DAG;
8379 SDValue IntVec = StVal.getOperand(0);
8380 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8381 IntVec.getValueType().getVectorNumElements());
8382 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8383 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8384 Vec, StVal.getOperand(1));
8386 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8387 // Make the DAGCombiner fold the bitcasts.
8388 DCI.AddToWorklist(Vec.getNode());
8389 DCI.AddToWorklist(ExtElt.getNode());
8390 DCI.AddToWorklist(V.getNode());
8391 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8392 St->getPointerInfo(), St->isVolatile(),
8393 St->isNonTemporal(), St->getAlignment(),
8397 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8398 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8399 /// i64 vector to have f64 elements, since the value can then be loaded
8400 /// directly into a VFP register.
8401 static bool hasNormalLoadOperand(SDNode *N) {
8402 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8403 for (unsigned i = 0; i < NumElts; ++i) {
8404 SDNode *Elt = N->getOperand(i).getNode();
8405 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8411 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8412 /// ISD::BUILD_VECTOR.
8413 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8414 TargetLowering::DAGCombinerInfo &DCI){
8415 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8416 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8417 // into a pair of GPRs, which is fine when the value is used as a scalar,
8418 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8419 SelectionDAG &DAG = DCI.DAG;
8420 if (N->getNumOperands() == 2) {
8421 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8426 // Load i64 elements as f64 values so that type legalization does not split
8427 // them up into i32 values.
8428 EVT VT = N->getValueType(0);
8429 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8432 SmallVector<SDValue, 8> Ops;
8433 unsigned NumElts = VT.getVectorNumElements();
8434 for (unsigned i = 0; i < NumElts; ++i) {
8435 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8437 // Make the DAGCombiner fold the bitcast.
8438 DCI.AddToWorklist(V.getNode());
8440 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8441 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8442 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8445 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8447 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8448 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8449 // At that time, we may have inserted bitcasts from integer to float.
8450 // If these bitcasts have survived DAGCombine, change the lowering of this
8451 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8452 // force to use floating point types.
8454 // Make sure we can change the type of the vector.
8455 // This is possible iff:
8456 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8457 // 1.1. Vector is used only once.
8458 // 1.2. Use is a bit convert to an integer type.
8459 // 2. The size of its operands are 32-bits (64-bits are not legal).
8460 EVT VT = N->getValueType(0);
8461 EVT EltVT = VT.getVectorElementType();
8463 // Check 1.1. and 2.
8464 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8467 // By construction, the input type must be float.
8468 assert(EltVT == MVT::f32 && "Unexpected type!");
8471 SDNode *Use = *N->use_begin();
8472 if (Use->getOpcode() != ISD::BITCAST ||
8473 Use->getValueType(0).isFloatingPoint())
8476 // Check profitability.
8477 // Model is, if more than half of the relevant operands are bitcast from
8478 // i32, turn the build_vector into a sequence of insert_vector_elt.
8479 // Relevant operands are everything that is not statically
8480 // (i.e., at compile time) bitcasted.
8481 unsigned NumOfBitCastedElts = 0;
8482 unsigned NumElts = VT.getVectorNumElements();
8483 unsigned NumOfRelevantElts = NumElts;
8484 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8485 SDValue Elt = N->getOperand(Idx);
8486 if (Elt->getOpcode() == ISD::BITCAST) {
8487 // Assume only bit cast to i32 will go away.
8488 if (Elt->getOperand(0).getValueType() == MVT::i32)
8489 ++NumOfBitCastedElts;
8490 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8491 // Constants are statically casted, thus do not count them as
8492 // relevant operands.
8493 --NumOfRelevantElts;
8496 // Check if more than half of the elements require a non-free bitcast.
8497 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8500 SelectionDAG &DAG = DCI.DAG;
8501 // Create the new vector type.
8502 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8503 // Check if the type is legal.
8504 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8505 if (!TLI.isTypeLegal(VecVT))
8509 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8510 // => BITCAST INSERT_VECTOR_ELT
8511 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8513 SDValue Vec = DAG.getUNDEF(VecVT);
8515 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8516 SDValue V = N->getOperand(Idx);
8517 if (V.getOpcode() == ISD::UNDEF)
8519 if (V.getOpcode() == ISD::BITCAST &&
8520 V->getOperand(0).getValueType() == MVT::i32)
8521 // Fold obvious case.
8522 V = V.getOperand(0);
8524 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8525 // Make the DAGCombiner fold the bitcasts.
8526 DCI.AddToWorklist(V.getNode());
8528 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8529 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8531 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8532 // Make the DAGCombiner fold the bitcasts.
8533 DCI.AddToWorklist(Vec.getNode());
8537 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8538 /// ISD::INSERT_VECTOR_ELT.
8539 static SDValue PerformInsertEltCombine(SDNode *N,
8540 TargetLowering::DAGCombinerInfo &DCI) {
8541 // Bitcast an i64 load inserted into a vector to f64.
8542 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8543 EVT VT = N->getValueType(0);
8544 SDNode *Elt = N->getOperand(1).getNode();
8545 if (VT.getVectorElementType() != MVT::i64 ||
8546 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8549 SelectionDAG &DAG = DCI.DAG;
8551 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8552 VT.getVectorNumElements());
8553 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8554 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8555 // Make the DAGCombiner fold the bitcasts.
8556 DCI.AddToWorklist(Vec.getNode());
8557 DCI.AddToWorklist(V.getNode());
8558 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8559 Vec, V, N->getOperand(2));
8560 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8563 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8564 /// ISD::VECTOR_SHUFFLE.
8565 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8566 // The LLVM shufflevector instruction does not require the shuffle mask
8567 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8568 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8569 // operands do not match the mask length, they are extended by concatenating
8570 // them with undef vectors. That is probably the right thing for other
8571 // targets, but for NEON it is better to concatenate two double-register
8572 // size vector operands into a single quad-register size vector. Do that
8573 // transformation here:
8574 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8575 // shuffle(concat(v1, v2), undef)
8576 SDValue Op0 = N->getOperand(0);
8577 SDValue Op1 = N->getOperand(1);
8578 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8579 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8580 Op0.getNumOperands() != 2 ||
8581 Op1.getNumOperands() != 2)
8583 SDValue Concat0Op1 = Op0.getOperand(1);
8584 SDValue Concat1Op1 = Op1.getOperand(1);
8585 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8586 Concat1Op1.getOpcode() != ISD::UNDEF)
8588 // Skip the transformation if any of the types are illegal.
8589 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8590 EVT VT = N->getValueType(0);
8591 if (!TLI.isTypeLegal(VT) ||
8592 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8593 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8596 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8597 Op0.getOperand(0), Op1.getOperand(0));
8598 // Translate the shuffle mask.
8599 SmallVector<int, 16> NewMask;
8600 unsigned NumElts = VT.getVectorNumElements();
8601 unsigned HalfElts = NumElts/2;
8602 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8603 for (unsigned n = 0; n < NumElts; ++n) {
8604 int MaskElt = SVN->getMaskElt(n);
8606 if (MaskElt < (int)HalfElts)
8608 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8609 NewElt = HalfElts + MaskElt - NumElts;
8610 NewMask.push_back(NewElt);
8612 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8613 DAG.getUNDEF(VT), NewMask.data());
8616 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8617 /// NEON load/store intrinsics to merge base address updates.
8618 static SDValue CombineBaseUpdate(SDNode *N,
8619 TargetLowering::DAGCombinerInfo &DCI) {
8620 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8623 SelectionDAG &DAG = DCI.DAG;
8624 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8625 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8626 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8627 SDValue Addr = N->getOperand(AddrOpIdx);
8629 // Search for a use of the address operand that is an increment.
8630 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8631 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8633 if (User->getOpcode() != ISD::ADD ||
8634 UI.getUse().getResNo() != Addr.getResNo())
8637 // Check that the add is independent of the load/store. Otherwise, folding
8638 // it would create a cycle.
8639 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8642 // Find the new opcode for the updating load/store.
8644 bool isLaneOp = false;
8645 unsigned NewOpc = 0;
8646 unsigned NumVecs = 0;
8648 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8650 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8651 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8653 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8655 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8657 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8659 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8660 NumVecs = 2; isLaneOp = true; break;
8661 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8662 NumVecs = 3; isLaneOp = true; break;
8663 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8664 NumVecs = 4; isLaneOp = true; break;
8665 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8666 NumVecs = 1; isLoad = false; break;
8667 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8668 NumVecs = 2; isLoad = false; break;
8669 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8670 NumVecs = 3; isLoad = false; break;
8671 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8672 NumVecs = 4; isLoad = false; break;
8673 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8674 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8675 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8676 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8677 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8678 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8682 switch (N->getOpcode()) {
8683 default: llvm_unreachable("unexpected opcode for Neon base update");
8684 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8685 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8686 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8690 // Find the size of memory referenced by the load/store.
8693 VecTy = N->getValueType(0);
8695 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8696 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8698 NumBytes /= VecTy.getVectorNumElements();
8700 // If the increment is a constant, it must match the memory ref size.
8701 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8702 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8703 uint64_t IncVal = CInc->getZExtValue();
8704 if (IncVal != NumBytes)
8706 } else if (NumBytes >= 3 * 16) {
8707 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8708 // separate instructions that make it harder to use a non-constant update.
8712 // Create the new updating load/store node.
8714 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8716 for (n = 0; n < NumResultVecs; ++n)
8718 Tys[n++] = MVT::i32;
8719 Tys[n] = MVT::Other;
8720 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8721 SmallVector<SDValue, 8> Ops;
8722 Ops.push_back(N->getOperand(0)); // incoming chain
8723 Ops.push_back(N->getOperand(AddrOpIdx));
8725 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8726 Ops.push_back(N->getOperand(i));
8728 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8729 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8730 Ops, MemInt->getMemoryVT(),
8731 MemInt->getMemOperand());
8734 std::vector<SDValue> NewResults;
8735 for (unsigned i = 0; i < NumResultVecs; ++i) {
8736 NewResults.push_back(SDValue(UpdN.getNode(), i));
8738 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8739 DCI.CombineTo(N, NewResults);
8740 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8747 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8748 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8749 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8751 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8752 SelectionDAG &DAG = DCI.DAG;
8753 EVT VT = N->getValueType(0);
8754 // vldN-dup instructions only support 64-bit vectors for N > 1.
8755 if (!VT.is64BitVector())
8758 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8759 SDNode *VLD = N->getOperand(0).getNode();
8760 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8762 unsigned NumVecs = 0;
8763 unsigned NewOpc = 0;
8764 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8765 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8767 NewOpc = ARMISD::VLD2DUP;
8768 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8770 NewOpc = ARMISD::VLD3DUP;
8771 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8773 NewOpc = ARMISD::VLD4DUP;
8778 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8779 // numbers match the load.
8780 unsigned VLDLaneNo =
8781 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8782 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8784 // Ignore uses of the chain result.
8785 if (UI.getUse().getResNo() == NumVecs)
8788 if (User->getOpcode() != ARMISD::VDUPLANE ||
8789 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8793 // Create the vldN-dup node.
8796 for (n = 0; n < NumVecs; ++n)
8798 Tys[n] = MVT::Other;
8799 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8800 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8801 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8802 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8803 Ops, VLDMemInt->getMemoryVT(),
8804 VLDMemInt->getMemOperand());
8807 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8809 unsigned ResNo = UI.getUse().getResNo();
8810 // Ignore uses of the chain result.
8811 if (ResNo == NumVecs)
8814 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8817 // Now the vldN-lane intrinsic is dead except for its chain result.
8818 // Update uses of the chain.
8819 std::vector<SDValue> VLDDupResults;
8820 for (unsigned n = 0; n < NumVecs; ++n)
8821 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8822 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8823 DCI.CombineTo(VLD, VLDDupResults);
8828 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8829 /// ARMISD::VDUPLANE.
8830 static SDValue PerformVDUPLANECombine(SDNode *N,
8831 TargetLowering::DAGCombinerInfo &DCI) {
8832 SDValue Op = N->getOperand(0);
8834 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8835 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8836 if (CombineVLDDUP(N, DCI))
8837 return SDValue(N, 0);
8839 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8840 // redundant. Ignore bit_converts for now; element sizes are checked below.
8841 while (Op.getOpcode() == ISD::BITCAST)
8842 Op = Op.getOperand(0);
8843 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8846 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8847 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8848 // The canonical VMOV for a zero vector uses a 32-bit element size.
8849 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8851 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8853 EVT VT = N->getValueType(0);
8854 if (EltSize > VT.getVectorElementType().getSizeInBits())
8857 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8860 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8861 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8862 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8866 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8868 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8873 APFloat APF = C->getValueAPF();
8874 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8875 != APFloat::opOK || !isExact)
8878 c0 = (I == 0) ? cN : c0;
8879 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8886 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8887 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8888 /// when the VMUL has a constant operand that is a power of 2.
8890 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8891 /// vmul.f32 d16, d17, d16
8892 /// vcvt.s32.f32 d16, d16
8894 /// vcvt.s32.f32 d16, d16, #3
8895 static SDValue PerformVCVTCombine(SDNode *N,
8896 TargetLowering::DAGCombinerInfo &DCI,
8897 const ARMSubtarget *Subtarget) {
8898 SelectionDAG &DAG = DCI.DAG;
8899 SDValue Op = N->getOperand(0);
8901 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8902 Op.getOpcode() != ISD::FMUL)
8906 SDValue N0 = Op->getOperand(0);
8907 SDValue ConstVec = Op->getOperand(1);
8908 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8910 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8911 !isConstVecPow2(ConstVec, isSigned, C))
8914 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8915 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8916 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
8917 // These instructions only exist converting from f32 to i32. We can handle
8918 // smaller integers by generating an extra truncate, but larger ones would
8923 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8924 Intrinsic::arm_neon_vcvtfp2fxu;
8925 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8926 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8927 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
8928 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8929 DAG.getConstant(Log2_64(C), MVT::i32));
8931 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
8932 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
8937 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8938 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8939 /// when the VDIV has a constant operand that is a power of 2.
8941 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8942 /// vcvt.f32.s32 d16, d16
8943 /// vdiv.f32 d16, d17, d16
8945 /// vcvt.f32.s32 d16, d16, #3
8946 static SDValue PerformVDIVCombine(SDNode *N,
8947 TargetLowering::DAGCombinerInfo &DCI,
8948 const ARMSubtarget *Subtarget) {
8949 SelectionDAG &DAG = DCI.DAG;
8950 SDValue Op = N->getOperand(0);
8951 unsigned OpOpcode = Op.getNode()->getOpcode();
8953 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8954 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8958 SDValue ConstVec = N->getOperand(1);
8959 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8961 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8962 !isConstVecPow2(ConstVec, isSigned, C))
8965 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8966 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8967 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
8968 // These instructions only exist converting from i32 to f32. We can handle
8969 // smaller integers by generating an extra extend, but larger ones would
8974 SDValue ConvInput = Op.getOperand(0);
8975 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8976 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
8977 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8978 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
8981 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8982 Intrinsic::arm_neon_vcvtfxu2fp;
8983 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8985 DAG.getConstant(IntrinsicOpcode, MVT::i32),
8986 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
8989 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8990 /// operand of a vector shift operation, where all the elements of the
8991 /// build_vector must have the same constant integer value.
8992 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8993 // Ignore bit_converts.
8994 while (Op.getOpcode() == ISD::BITCAST)
8995 Op = Op.getOperand(0);
8996 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8997 APInt SplatBits, SplatUndef;
8998 unsigned SplatBitSize;
9000 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9001 HasAnyUndefs, ElementBits) ||
9002 SplatBitSize > ElementBits)
9004 Cnt = SplatBits.getSExtValue();
9008 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9009 /// operand of a vector shift left operation. That value must be in the range:
9010 /// 0 <= Value < ElementBits for a left shift; or
9011 /// 0 <= Value <= ElementBits for a long left shift.
9012 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9013 assert(VT.isVector() && "vector shift count is not a vector type");
9014 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9015 if (! getVShiftImm(Op, ElementBits, Cnt))
9017 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9020 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9021 /// operand of a vector shift right operation. For a shift opcode, the value
9022 /// is positive, but for an intrinsic the value count must be negative. The
9023 /// absolute value must be in the range:
9024 /// 1 <= |Value| <= ElementBits for a right shift; or
9025 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9026 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9028 assert(VT.isVector() && "vector shift count is not a vector type");
9029 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9030 if (! getVShiftImm(Op, ElementBits, Cnt))
9034 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9037 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9038 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9039 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9042 // Don't do anything for most intrinsics.
9045 // Vector shifts: check for immediate versions and lower them.
9046 // Note: This is done during DAG combining instead of DAG legalizing because
9047 // the build_vectors for 64-bit vector element shift counts are generally
9048 // not legal, and it is hard to see their values after they get legalized to
9049 // loads from a constant pool.
9050 case Intrinsic::arm_neon_vshifts:
9051 case Intrinsic::arm_neon_vshiftu:
9052 case Intrinsic::arm_neon_vrshifts:
9053 case Intrinsic::arm_neon_vrshiftu:
9054 case Intrinsic::arm_neon_vrshiftn:
9055 case Intrinsic::arm_neon_vqshifts:
9056 case Intrinsic::arm_neon_vqshiftu:
9057 case Intrinsic::arm_neon_vqshiftsu:
9058 case Intrinsic::arm_neon_vqshiftns:
9059 case Intrinsic::arm_neon_vqshiftnu:
9060 case Intrinsic::arm_neon_vqshiftnsu:
9061 case Intrinsic::arm_neon_vqrshiftns:
9062 case Intrinsic::arm_neon_vqrshiftnu:
9063 case Intrinsic::arm_neon_vqrshiftnsu: {
9064 EVT VT = N->getOperand(1).getValueType();
9066 unsigned VShiftOpc = 0;
9069 case Intrinsic::arm_neon_vshifts:
9070 case Intrinsic::arm_neon_vshiftu:
9071 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9072 VShiftOpc = ARMISD::VSHL;
9075 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9076 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9077 ARMISD::VSHRs : ARMISD::VSHRu);
9082 case Intrinsic::arm_neon_vrshifts:
9083 case Intrinsic::arm_neon_vrshiftu:
9084 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9088 case Intrinsic::arm_neon_vqshifts:
9089 case Intrinsic::arm_neon_vqshiftu:
9090 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9094 case Intrinsic::arm_neon_vqshiftsu:
9095 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9097 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9099 case Intrinsic::arm_neon_vrshiftn:
9100 case Intrinsic::arm_neon_vqshiftns:
9101 case Intrinsic::arm_neon_vqshiftnu:
9102 case Intrinsic::arm_neon_vqshiftnsu:
9103 case Intrinsic::arm_neon_vqrshiftns:
9104 case Intrinsic::arm_neon_vqrshiftnu:
9105 case Intrinsic::arm_neon_vqrshiftnsu:
9106 // Narrowing shifts require an immediate right shift.
9107 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9109 llvm_unreachable("invalid shift count for narrowing vector shift "
9113 llvm_unreachable("unhandled vector shift");
9117 case Intrinsic::arm_neon_vshifts:
9118 case Intrinsic::arm_neon_vshiftu:
9119 // Opcode already set above.
9121 case Intrinsic::arm_neon_vrshifts:
9122 VShiftOpc = ARMISD::VRSHRs; break;
9123 case Intrinsic::arm_neon_vrshiftu:
9124 VShiftOpc = ARMISD::VRSHRu; break;
9125 case Intrinsic::arm_neon_vrshiftn:
9126 VShiftOpc = ARMISD::VRSHRN; break;
9127 case Intrinsic::arm_neon_vqshifts:
9128 VShiftOpc = ARMISD::VQSHLs; break;
9129 case Intrinsic::arm_neon_vqshiftu:
9130 VShiftOpc = ARMISD::VQSHLu; break;
9131 case Intrinsic::arm_neon_vqshiftsu:
9132 VShiftOpc = ARMISD::VQSHLsu; break;
9133 case Intrinsic::arm_neon_vqshiftns:
9134 VShiftOpc = ARMISD::VQSHRNs; break;
9135 case Intrinsic::arm_neon_vqshiftnu:
9136 VShiftOpc = ARMISD::VQSHRNu; break;
9137 case Intrinsic::arm_neon_vqshiftnsu:
9138 VShiftOpc = ARMISD::VQSHRNsu; break;
9139 case Intrinsic::arm_neon_vqrshiftns:
9140 VShiftOpc = ARMISD::VQRSHRNs; break;
9141 case Intrinsic::arm_neon_vqrshiftnu:
9142 VShiftOpc = ARMISD::VQRSHRNu; break;
9143 case Intrinsic::arm_neon_vqrshiftnsu:
9144 VShiftOpc = ARMISD::VQRSHRNsu; break;
9147 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9148 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9151 case Intrinsic::arm_neon_vshiftins: {
9152 EVT VT = N->getOperand(1).getValueType();
9154 unsigned VShiftOpc = 0;
9156 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9157 VShiftOpc = ARMISD::VSLI;
9158 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9159 VShiftOpc = ARMISD::VSRI;
9161 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9164 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9165 N->getOperand(1), N->getOperand(2),
9166 DAG.getConstant(Cnt, MVT::i32));
9169 case Intrinsic::arm_neon_vqrshifts:
9170 case Intrinsic::arm_neon_vqrshiftu:
9171 // No immediate versions of these to check for.
9178 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9179 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9180 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9181 /// vector element shift counts are generally not legal, and it is hard to see
9182 /// their values after they get legalized to loads from a constant pool.
9183 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9184 const ARMSubtarget *ST) {
9185 EVT VT = N->getValueType(0);
9186 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9187 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9188 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9189 SDValue N1 = N->getOperand(1);
9190 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9191 SDValue N0 = N->getOperand(0);
9192 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9193 DAG.MaskedValueIsZero(N0.getOperand(0),
9194 APInt::getHighBitsSet(32, 16)))
9195 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9199 // Nothing to be done for scalar shifts.
9200 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9201 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9204 assert(ST->hasNEON() && "unexpected vector shift");
9207 switch (N->getOpcode()) {
9208 default: llvm_unreachable("unexpected shift opcode");
9211 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9212 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9213 DAG.getConstant(Cnt, MVT::i32));
9218 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9219 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9220 ARMISD::VSHRs : ARMISD::VSHRu);
9221 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9222 DAG.getConstant(Cnt, MVT::i32));
9228 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9229 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9230 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9231 const ARMSubtarget *ST) {
9232 SDValue N0 = N->getOperand(0);
9234 // Check for sign- and zero-extensions of vector extract operations of 8-
9235 // and 16-bit vector elements. NEON supports these directly. They are
9236 // handled during DAG combining because type legalization will promote them
9237 // to 32-bit types and it is messy to recognize the operations after that.
9238 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9239 SDValue Vec = N0.getOperand(0);
9240 SDValue Lane = N0.getOperand(1);
9241 EVT VT = N->getValueType(0);
9242 EVT EltVT = N0.getValueType();
9243 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9245 if (VT == MVT::i32 &&
9246 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9247 TLI.isTypeLegal(Vec.getValueType()) &&
9248 isa<ConstantSDNode>(Lane)) {
9251 switch (N->getOpcode()) {
9252 default: llvm_unreachable("unexpected opcode");
9253 case ISD::SIGN_EXTEND:
9254 Opc = ARMISD::VGETLANEs;
9256 case ISD::ZERO_EXTEND:
9257 case ISD::ANY_EXTEND:
9258 Opc = ARMISD::VGETLANEu;
9261 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9268 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9269 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9270 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9271 const ARMSubtarget *ST) {
9272 // If the target supports NEON, try to use vmax/vmin instructions for f32
9273 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9274 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9275 // a NaN; only do the transformation when it matches that behavior.
9277 // For now only do this when using NEON for FP operations; if using VFP, it
9278 // is not obvious that the benefit outweighs the cost of switching to the
9280 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9281 N->getValueType(0) != MVT::f32)
9284 SDValue CondLHS = N->getOperand(0);
9285 SDValue CondRHS = N->getOperand(1);
9286 SDValue LHS = N->getOperand(2);
9287 SDValue RHS = N->getOperand(3);
9288 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9290 unsigned Opcode = 0;
9292 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9293 IsReversed = false; // x CC y ? x : y
9294 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9295 IsReversed = true ; // x CC y ? y : x
9309 // If LHS is NaN, an ordered comparison will be false and the result will
9310 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9311 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9312 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9313 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9315 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9316 // will return -0, so vmin can only be used for unsafe math or if one of
9317 // the operands is known to be nonzero.
9318 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9319 !DAG.getTarget().Options.UnsafeFPMath &&
9320 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9322 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9331 // If LHS is NaN, an ordered comparison will be false and the result will
9332 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9333 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9334 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9335 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9337 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9338 // will return +0, so vmax can only be used for unsafe math or if one of
9339 // the operands is known to be nonzero.
9340 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9341 !DAG.getTarget().Options.UnsafeFPMath &&
9342 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9344 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9350 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9353 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9355 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9356 SDValue Cmp = N->getOperand(4);
9357 if (Cmp.getOpcode() != ARMISD::CMPZ)
9358 // Only looking at EQ and NE cases.
9361 EVT VT = N->getValueType(0);
9363 SDValue LHS = Cmp.getOperand(0);
9364 SDValue RHS = Cmp.getOperand(1);
9365 SDValue FalseVal = N->getOperand(0);
9366 SDValue TrueVal = N->getOperand(1);
9367 SDValue ARMcc = N->getOperand(2);
9368 ARMCC::CondCodes CC =
9369 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9387 /// FIXME: Turn this into a target neutral optimization?
9389 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9390 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9391 N->getOperand(3), Cmp);
9392 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9394 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9395 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9396 N->getOperand(3), NewCmp);
9399 if (Res.getNode()) {
9400 APInt KnownZero, KnownOne;
9401 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9402 // Capture demanded bits information that would be otherwise lost.
9403 if (KnownZero == 0xfffffffe)
9404 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9405 DAG.getValueType(MVT::i1));
9406 else if (KnownZero == 0xffffff00)
9407 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9408 DAG.getValueType(MVT::i8));
9409 else if (KnownZero == 0xffff0000)
9410 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9411 DAG.getValueType(MVT::i16));
9417 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9418 DAGCombinerInfo &DCI) const {
9419 switch (N->getOpcode()) {
9421 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9422 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9423 case ISD::SUB: return PerformSUBCombine(N, DCI);
9424 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9425 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9426 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9427 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9428 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9429 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9430 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9431 case ISD::STORE: return PerformSTORECombine(N, DCI);
9432 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9433 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9434 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9435 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9436 case ISD::FP_TO_SINT:
9437 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9438 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9439 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9442 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9443 case ISD::SIGN_EXTEND:
9444 case ISD::ZERO_EXTEND:
9445 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9446 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9447 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9448 case ARMISD::VLD2DUP:
9449 case ARMISD::VLD3DUP:
9450 case ARMISD::VLD4DUP:
9451 return CombineBaseUpdate(N, DCI);
9452 case ARMISD::BUILD_VECTOR:
9453 return PerformARMBUILD_VECTORCombine(N, DCI);
9454 case ISD::INTRINSIC_VOID:
9455 case ISD::INTRINSIC_W_CHAIN:
9456 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9457 case Intrinsic::arm_neon_vld1:
9458 case Intrinsic::arm_neon_vld2:
9459 case Intrinsic::arm_neon_vld3:
9460 case Intrinsic::arm_neon_vld4:
9461 case Intrinsic::arm_neon_vld2lane:
9462 case Intrinsic::arm_neon_vld3lane:
9463 case Intrinsic::arm_neon_vld4lane:
9464 case Intrinsic::arm_neon_vst1:
9465 case Intrinsic::arm_neon_vst2:
9466 case Intrinsic::arm_neon_vst3:
9467 case Intrinsic::arm_neon_vst4:
9468 case Intrinsic::arm_neon_vst2lane:
9469 case Intrinsic::arm_neon_vst3lane:
9470 case Intrinsic::arm_neon_vst4lane:
9471 return CombineBaseUpdate(N, DCI);
9479 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9481 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9484 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9486 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9487 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9489 switch (VT.getSimpleVT().SimpleTy) {
9495 // Unaligned access can use (for example) LRDB, LRDH, LDR
9496 if (AllowsUnaligned) {
9498 *Fast = Subtarget->hasV7Ops();
9505 // For any little-endian targets with neon, we can support unaligned ld/st
9506 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9507 // A big-endian target may also explicitly support unaligned accesses
9508 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9518 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9519 unsigned AlignCheck) {
9520 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9521 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9524 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9525 unsigned DstAlign, unsigned SrcAlign,
9526 bool IsMemset, bool ZeroMemset,
9528 MachineFunction &MF) const {
9529 const Function *F = MF.getFunction();
9531 // See if we can use NEON instructions for this...
9532 if ((!IsMemset || ZeroMemset) &&
9533 Subtarget->hasNEON() &&
9534 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9535 Attribute::NoImplicitFloat)) {
9538 (memOpAlign(SrcAlign, DstAlign, 16) ||
9539 (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9541 } else if (Size >= 8 &&
9542 (memOpAlign(SrcAlign, DstAlign, 8) ||
9543 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9548 // Lowering to i32/i16 if the size permits.
9554 // Let the target-independent logic figure it out.
9558 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9559 if (Val.getOpcode() != ISD::LOAD)
9562 EVT VT1 = Val.getValueType();
9563 if (!VT1.isSimple() || !VT1.isInteger() ||
9564 !VT2.isSimple() || !VT2.isInteger())
9567 switch (VT1.getSimpleVT().SimpleTy) {
9572 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9579 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9580 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9583 if (!isTypeLegal(EVT::getEVT(Ty1)))
9586 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9588 // Assuming the caller doesn't have a zeroext or signext return parameter,
9589 // truncation all the way down to i1 is valid.
9594 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9599 switch (VT.getSimpleVT().SimpleTy) {
9600 default: return false;
9615 if ((V & (Scale - 1)) != 0)
9618 return V == (V & ((1LL << 5) - 1));
9621 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9622 const ARMSubtarget *Subtarget) {
9629 switch (VT.getSimpleVT().SimpleTy) {
9630 default: return false;
9635 // + imm12 or - imm8
9637 return V == (V & ((1LL << 8) - 1));
9638 return V == (V & ((1LL << 12) - 1));
9641 // Same as ARM mode. FIXME: NEON?
9642 if (!Subtarget->hasVFP2())
9647 return V == (V & ((1LL << 8) - 1));
9651 /// isLegalAddressImmediate - Return true if the integer value can be used
9652 /// as the offset of the target addressing mode for load / store of the
9654 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9655 const ARMSubtarget *Subtarget) {
9662 if (Subtarget->isThumb1Only())
9663 return isLegalT1AddressImmediate(V, VT);
9664 else if (Subtarget->isThumb2())
9665 return isLegalT2AddressImmediate(V, VT, Subtarget);
9670 switch (VT.getSimpleVT().SimpleTy) {
9671 default: return false;
9676 return V == (V & ((1LL << 12) - 1));
9679 return V == (V & ((1LL << 8) - 1));
9682 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9687 return V == (V & ((1LL << 8) - 1));
9691 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9693 int Scale = AM.Scale;
9697 switch (VT.getSimpleVT().SimpleTy) {
9698 default: return false;
9707 return Scale == 2 || Scale == 4 || Scale == 8;
9710 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9714 // Note, we allow "void" uses (basically, uses that aren't loads or
9715 // stores), because arm allows folding a scale into many arithmetic
9716 // operations. This should be made more precise and revisited later.
9718 // Allow r << imm, but the imm has to be a multiple of two.
9719 if (Scale & 1) return false;
9720 return isPowerOf2_32(Scale);
9724 /// isLegalAddressingMode - Return true if the addressing mode represented
9725 /// by AM is legal for this target, for a load/store of the specified type.
9726 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9728 EVT VT = getValueType(Ty, true);
9729 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9732 // Can never fold addr of global into load/store.
9737 case 0: // no scale reg, must be "r+i" or "r", or "i".
9740 if (Subtarget->isThumb1Only())
9744 // ARM doesn't support any R+R*scale+imm addr modes.
9751 if (Subtarget->isThumb2())
9752 return isLegalT2ScaledAddressingMode(AM, VT);
9754 int Scale = AM.Scale;
9755 switch (VT.getSimpleVT().SimpleTy) {
9756 default: return false;
9760 if (Scale < 0) Scale = -Scale;
9764 return isPowerOf2_32(Scale & ~1);
9768 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9773 // Note, we allow "void" uses (basically, uses that aren't loads or
9774 // stores), because arm allows folding a scale into many arithmetic
9775 // operations. This should be made more precise and revisited later.
9777 // Allow r << imm, but the imm has to be a multiple of two.
9778 if (Scale & 1) return false;
9779 return isPowerOf2_32(Scale);
9785 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9786 /// icmp immediate, that is the target has icmp instructions which can compare
9787 /// a register against the immediate without having to materialize the
9788 /// immediate into a register.
9789 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9790 // Thumb2 and ARM modes can use cmn for negative immediates.
9791 if (!Subtarget->isThumb())
9792 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9793 if (Subtarget->isThumb2())
9794 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9795 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9796 return Imm >= 0 && Imm <= 255;
9799 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9800 /// *or sub* immediate, that is the target has add or sub instructions which can
9801 /// add a register with the immediate without having to materialize the
9802 /// immediate into a register.
9803 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9804 // Same encoding for add/sub, just flip the sign.
9805 int64_t AbsImm = llvm::abs64(Imm);
9806 if (!Subtarget->isThumb())
9807 return ARM_AM::getSOImmVal(AbsImm) != -1;
9808 if (Subtarget->isThumb2())
9809 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9810 // Thumb1 only has 8-bit unsigned immediate.
9811 return AbsImm >= 0 && AbsImm <= 255;
9814 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9815 bool isSEXTLoad, SDValue &Base,
9816 SDValue &Offset, bool &isInc,
9817 SelectionDAG &DAG) {
9818 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9821 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9823 Base = Ptr->getOperand(0);
9824 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9825 int RHSC = (int)RHS->getZExtValue();
9826 if (RHSC < 0 && RHSC > -256) {
9827 assert(Ptr->getOpcode() == ISD::ADD);
9829 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9833 isInc = (Ptr->getOpcode() == ISD::ADD);
9834 Offset = Ptr->getOperand(1);
9836 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9838 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9839 int RHSC = (int)RHS->getZExtValue();
9840 if (RHSC < 0 && RHSC > -0x1000) {
9841 assert(Ptr->getOpcode() == ISD::ADD);
9843 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9844 Base = Ptr->getOperand(0);
9849 if (Ptr->getOpcode() == ISD::ADD) {
9851 ARM_AM::ShiftOpc ShOpcVal=
9852 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9853 if (ShOpcVal != ARM_AM::no_shift) {
9854 Base = Ptr->getOperand(1);
9855 Offset = Ptr->getOperand(0);
9857 Base = Ptr->getOperand(0);
9858 Offset = Ptr->getOperand(1);
9863 isInc = (Ptr->getOpcode() == ISD::ADD);
9864 Base = Ptr->getOperand(0);
9865 Offset = Ptr->getOperand(1);
9869 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9873 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9874 bool isSEXTLoad, SDValue &Base,
9875 SDValue &Offset, bool &isInc,
9876 SelectionDAG &DAG) {
9877 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9880 Base = Ptr->getOperand(0);
9881 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9882 int RHSC = (int)RHS->getZExtValue();
9883 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9884 assert(Ptr->getOpcode() == ISD::ADD);
9886 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9888 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9889 isInc = Ptr->getOpcode() == ISD::ADD;
9890 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9898 /// getPreIndexedAddressParts - returns true by value, base pointer and
9899 /// offset pointer and addressing mode by reference if the node's address
9900 /// can be legally represented as pre-indexed load / store address.
9902 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9904 ISD::MemIndexedMode &AM,
9905 SelectionDAG &DAG) const {
9906 if (Subtarget->isThumb1Only())
9911 bool isSEXTLoad = false;
9912 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9913 Ptr = LD->getBasePtr();
9914 VT = LD->getMemoryVT();
9915 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9916 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9917 Ptr = ST->getBasePtr();
9918 VT = ST->getMemoryVT();
9923 bool isLegal = false;
9924 if (Subtarget->isThumb2())
9925 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9926 Offset, isInc, DAG);
9928 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9929 Offset, isInc, DAG);
9933 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9937 /// getPostIndexedAddressParts - returns true by value, base pointer and
9938 /// offset pointer and addressing mode by reference if this node can be
9939 /// combined with a load / store to form a post-indexed load / store.
9940 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9943 ISD::MemIndexedMode &AM,
9944 SelectionDAG &DAG) const {
9945 if (Subtarget->isThumb1Only())
9950 bool isSEXTLoad = false;
9951 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9952 VT = LD->getMemoryVT();
9953 Ptr = LD->getBasePtr();
9954 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9955 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9956 VT = ST->getMemoryVT();
9957 Ptr = ST->getBasePtr();
9962 bool isLegal = false;
9963 if (Subtarget->isThumb2())
9964 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9967 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9973 // Swap base ptr and offset to catch more post-index load / store when
9974 // it's legal. In Thumb2 mode, offset must be an immediate.
9975 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9976 !Subtarget->isThumb2())
9977 std::swap(Base, Offset);
9979 // Post-indexed load / store update the base pointer.
9984 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9988 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9991 const SelectionDAG &DAG,
9992 unsigned Depth) const {
9993 unsigned BitWidth = KnownOne.getBitWidth();
9994 KnownZero = KnownOne = APInt(BitWidth, 0);
9995 switch (Op.getOpcode()) {
10001 // These nodes' second result is a boolean
10002 if (Op.getResNo() == 0)
10004 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10006 case ARMISD::CMOV: {
10007 // Bits are known zero/one if known on the LHS and RHS.
10008 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10009 if (KnownZero == 0 && KnownOne == 0) return;
10011 APInt KnownZeroRHS, KnownOneRHS;
10012 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10013 KnownZero &= KnownZeroRHS;
10014 KnownOne &= KnownOneRHS;
10017 case ISD::INTRINSIC_W_CHAIN: {
10018 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10019 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10022 case Intrinsic::arm_ldaex:
10023 case Intrinsic::arm_ldrex: {
10024 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10025 unsigned MemBits = VT.getScalarType().getSizeInBits();
10026 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10034 //===----------------------------------------------------------------------===//
10035 // ARM Inline Assembly Support
10036 //===----------------------------------------------------------------------===//
10038 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10039 // Looking for "rev" which is V6+.
10040 if (!Subtarget->hasV6Ops())
10043 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10044 std::string AsmStr = IA->getAsmString();
10045 SmallVector<StringRef, 4> AsmPieces;
10046 SplitString(AsmStr, AsmPieces, ";\n");
10048 switch (AsmPieces.size()) {
10049 default: return false;
10051 AsmStr = AsmPieces[0];
10053 SplitString(AsmStr, AsmPieces, " \t,");
10056 if (AsmPieces.size() == 3 &&
10057 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10058 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10059 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10060 if (Ty && Ty->getBitWidth() == 32)
10061 return IntrinsicLowering::LowerToByteSwap(CI);
10069 /// getConstraintType - Given a constraint letter, return the type of
10070 /// constraint it is for this target.
10071 ARMTargetLowering::ConstraintType
10072 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10073 if (Constraint.size() == 1) {
10074 switch (Constraint[0]) {
10076 case 'l': return C_RegisterClass;
10077 case 'w': return C_RegisterClass;
10078 case 'h': return C_RegisterClass;
10079 case 'x': return C_RegisterClass;
10080 case 't': return C_RegisterClass;
10081 case 'j': return C_Other; // Constant for movw.
10082 // An address with a single base register. Due to the way we
10083 // currently handle addresses it is the same as an 'r' memory constraint.
10084 case 'Q': return C_Memory;
10086 } else if (Constraint.size() == 2) {
10087 switch (Constraint[0]) {
10089 // All 'U+' constraints are addresses.
10090 case 'U': return C_Memory;
10093 return TargetLowering::getConstraintType(Constraint);
10096 /// Examine constraint type and operand type and determine a weight value.
10097 /// This object must already have been set up with the operand type
10098 /// and the current alternative constraint selected.
10099 TargetLowering::ConstraintWeight
10100 ARMTargetLowering::getSingleConstraintMatchWeight(
10101 AsmOperandInfo &info, const char *constraint) const {
10102 ConstraintWeight weight = CW_Invalid;
10103 Value *CallOperandVal = info.CallOperandVal;
10104 // If we don't have a value, we can't do a match,
10105 // but allow it at the lowest weight.
10106 if (!CallOperandVal)
10108 Type *type = CallOperandVal->getType();
10109 // Look at the constraint type.
10110 switch (*constraint) {
10112 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10115 if (type->isIntegerTy()) {
10116 if (Subtarget->isThumb())
10117 weight = CW_SpecificReg;
10119 weight = CW_Register;
10123 if (type->isFloatingPointTy())
10124 weight = CW_Register;
10130 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10132 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10134 if (Constraint.size() == 1) {
10135 // GCC ARM Constraint Letters
10136 switch (Constraint[0]) {
10137 case 'l': // Low regs or general regs.
10138 if (Subtarget->isThumb())
10139 return RCPair(0U, &ARM::tGPRRegClass);
10140 return RCPair(0U, &ARM::GPRRegClass);
10141 case 'h': // High regs or no regs.
10142 if (Subtarget->isThumb())
10143 return RCPair(0U, &ARM::hGPRRegClass);
10146 return RCPair(0U, &ARM::GPRRegClass);
10148 if (VT == MVT::Other)
10150 if (VT == MVT::f32)
10151 return RCPair(0U, &ARM::SPRRegClass);
10152 if (VT.getSizeInBits() == 64)
10153 return RCPair(0U, &ARM::DPRRegClass);
10154 if (VT.getSizeInBits() == 128)
10155 return RCPair(0U, &ARM::QPRRegClass);
10158 if (VT == MVT::Other)
10160 if (VT == MVT::f32)
10161 return RCPair(0U, &ARM::SPR_8RegClass);
10162 if (VT.getSizeInBits() == 64)
10163 return RCPair(0U, &ARM::DPR_8RegClass);
10164 if (VT.getSizeInBits() == 128)
10165 return RCPair(0U, &ARM::QPR_8RegClass);
10168 if (VT == MVT::f32)
10169 return RCPair(0U, &ARM::SPRRegClass);
10173 if (StringRef("{cc}").equals_lower(Constraint))
10174 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10176 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10179 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10180 /// vector. If it is invalid, don't add anything to Ops.
10181 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10182 std::string &Constraint,
10183 std::vector<SDValue>&Ops,
10184 SelectionDAG &DAG) const {
10187 // Currently only support length 1 constraints.
10188 if (Constraint.length() != 1) return;
10190 char ConstraintLetter = Constraint[0];
10191 switch (ConstraintLetter) {
10194 case 'I': case 'J': case 'K': case 'L':
10195 case 'M': case 'N': case 'O':
10196 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10200 int64_t CVal64 = C->getSExtValue();
10201 int CVal = (int) CVal64;
10202 // None of these constraints allow values larger than 32 bits. Check
10203 // that the value fits in an int.
10204 if (CVal != CVal64)
10207 switch (ConstraintLetter) {
10209 // Constant suitable for movw, must be between 0 and
10211 if (Subtarget->hasV6T2Ops())
10212 if (CVal >= 0 && CVal <= 65535)
10216 if (Subtarget->isThumb1Only()) {
10217 // This must be a constant between 0 and 255, for ADD
10219 if (CVal >= 0 && CVal <= 255)
10221 } else if (Subtarget->isThumb2()) {
10222 // A constant that can be used as an immediate value in a
10223 // data-processing instruction.
10224 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10227 // A constant that can be used as an immediate value in a
10228 // data-processing instruction.
10229 if (ARM_AM::getSOImmVal(CVal) != -1)
10235 if (Subtarget->isThumb()) { // FIXME thumb2
10236 // This must be a constant between -255 and -1, for negated ADD
10237 // immediates. This can be used in GCC with an "n" modifier that
10238 // prints the negated value, for use with SUB instructions. It is
10239 // not useful otherwise but is implemented for compatibility.
10240 if (CVal >= -255 && CVal <= -1)
10243 // This must be a constant between -4095 and 4095. It is not clear
10244 // what this constraint is intended for. Implemented for
10245 // compatibility with GCC.
10246 if (CVal >= -4095 && CVal <= 4095)
10252 if (Subtarget->isThumb1Only()) {
10253 // A 32-bit value where only one byte has a nonzero value. Exclude
10254 // zero to match GCC. This constraint is used by GCC internally for
10255 // constants that can be loaded with a move/shift combination.
10256 // It is not useful otherwise but is implemented for compatibility.
10257 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10259 } else if (Subtarget->isThumb2()) {
10260 // A constant whose bitwise inverse can be used as an immediate
10261 // value in a data-processing instruction. This can be used in GCC
10262 // with a "B" modifier that prints the inverted value, for use with
10263 // BIC and MVN instructions. It is not useful otherwise but is
10264 // implemented for compatibility.
10265 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10268 // A constant whose bitwise inverse can be used as an immediate
10269 // value in a data-processing instruction. This can be used in GCC
10270 // with a "B" modifier that prints the inverted value, for use with
10271 // BIC and MVN instructions. It is not useful otherwise but is
10272 // implemented for compatibility.
10273 if (ARM_AM::getSOImmVal(~CVal) != -1)
10279 if (Subtarget->isThumb1Only()) {
10280 // This must be a constant between -7 and 7,
10281 // for 3-operand ADD/SUB immediate instructions.
10282 if (CVal >= -7 && CVal < 7)
10284 } else if (Subtarget->isThumb2()) {
10285 // A constant whose negation can be used as an immediate value in a
10286 // data-processing instruction. This can be used in GCC with an "n"
10287 // modifier that prints the negated value, for use with SUB
10288 // instructions. It is not useful otherwise but is implemented for
10290 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10293 // A constant whose negation can be used as an immediate value in a
10294 // data-processing instruction. This can be used in GCC with an "n"
10295 // modifier that prints the negated value, for use with SUB
10296 // instructions. It is not useful otherwise but is implemented for
10298 if (ARM_AM::getSOImmVal(-CVal) != -1)
10304 if (Subtarget->isThumb()) { // FIXME thumb2
10305 // This must be a multiple of 4 between 0 and 1020, for
10306 // ADD sp + immediate.
10307 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10310 // A power of two or a constant between 0 and 32. This is used in
10311 // GCC for the shift amount on shifted register operands, but it is
10312 // useful in general for any shift amounts.
10313 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10319 if (Subtarget->isThumb()) { // FIXME thumb2
10320 // This must be a constant between 0 and 31, for shift amounts.
10321 if (CVal >= 0 && CVal <= 31)
10327 if (Subtarget->isThumb()) { // FIXME thumb2
10328 // This must be a multiple of 4 between -508 and 508, for
10329 // ADD/SUB sp = sp + immediate.
10330 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10335 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10339 if (Result.getNode()) {
10340 Ops.push_back(Result);
10343 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10346 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10347 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10348 unsigned Opcode = Op->getOpcode();
10349 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10350 "Invalid opcode for Div/Rem lowering");
10351 bool isSigned = (Opcode == ISD::SDIVREM);
10352 EVT VT = Op->getValueType(0);
10353 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10356 switch (VT.getSimpleVT().SimpleTy) {
10357 default: llvm_unreachable("Unexpected request for libcall!");
10358 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10359 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10360 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10361 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10364 SDValue InChain = DAG.getEntryNode();
10366 TargetLowering::ArgListTy Args;
10367 TargetLowering::ArgListEntry Entry;
10368 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10369 EVT ArgVT = Op->getOperand(i).getValueType();
10370 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10371 Entry.Node = Op->getOperand(i);
10373 Entry.isSExt = isSigned;
10374 Entry.isZExt = !isSigned;
10375 Args.push_back(Entry);
10378 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10381 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10385 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10386 0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10387 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10388 Callee, Args, DAG, dl);
10389 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10391 return CallInfo.first;
10395 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10396 // The ARM target isn't yet aware of offsets.
10400 bool ARM::isBitFieldInvertedMask(unsigned v) {
10401 if (v == 0xffffffff)
10404 // there can be 1's on either or both "outsides", all the "inside"
10405 // bits must be 0's
10406 unsigned TO = CountTrailingOnes_32(v);
10407 unsigned LO = CountLeadingOnes_32(v);
10408 v = (v >> TO) << TO;
10409 v = (v << LO) >> LO;
10413 /// isFPImmLegal - Returns true if the target can instruction select the
10414 /// specified FP immediate natively. If false, the legalizer will
10415 /// materialize the FP immediate as a load from a constant pool.
10416 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10417 if (!Subtarget->hasVFP3())
10419 if (VT == MVT::f32)
10420 return ARM_AM::getFP32Imm(Imm) != -1;
10421 if (VT == MVT::f64)
10422 return ARM_AM::getFP64Imm(Imm) != -1;
10426 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10427 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10428 /// specified in the intrinsic calls.
10429 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10431 unsigned Intrinsic) const {
10432 switch (Intrinsic) {
10433 case Intrinsic::arm_neon_vld1:
10434 case Intrinsic::arm_neon_vld2:
10435 case Intrinsic::arm_neon_vld3:
10436 case Intrinsic::arm_neon_vld4:
10437 case Intrinsic::arm_neon_vld2lane:
10438 case Intrinsic::arm_neon_vld3lane:
10439 case Intrinsic::arm_neon_vld4lane: {
10440 Info.opc = ISD::INTRINSIC_W_CHAIN;
10441 // Conservatively set memVT to the entire set of vectors loaded.
10442 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10443 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10444 Info.ptrVal = I.getArgOperand(0);
10446 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10447 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10448 Info.vol = false; // volatile loads with NEON intrinsics not supported
10449 Info.readMem = true;
10450 Info.writeMem = false;
10453 case Intrinsic::arm_neon_vst1:
10454 case Intrinsic::arm_neon_vst2:
10455 case Intrinsic::arm_neon_vst3:
10456 case Intrinsic::arm_neon_vst4:
10457 case Intrinsic::arm_neon_vst2lane:
10458 case Intrinsic::arm_neon_vst3lane:
10459 case Intrinsic::arm_neon_vst4lane: {
10460 Info.opc = ISD::INTRINSIC_VOID;
10461 // Conservatively set memVT to the entire set of vectors stored.
10462 unsigned NumElts = 0;
10463 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10464 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10465 if (!ArgTy->isVectorTy())
10467 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10469 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10470 Info.ptrVal = I.getArgOperand(0);
10472 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10473 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10474 Info.vol = false; // volatile stores with NEON intrinsics not supported
10475 Info.readMem = false;
10476 Info.writeMem = true;
10479 case Intrinsic::arm_ldaex:
10480 case Intrinsic::arm_ldrex: {
10481 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10482 Info.opc = ISD::INTRINSIC_W_CHAIN;
10483 Info.memVT = MVT::getVT(PtrTy->getElementType());
10484 Info.ptrVal = I.getArgOperand(0);
10486 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10488 Info.readMem = true;
10489 Info.writeMem = false;
10492 case Intrinsic::arm_stlex:
10493 case Intrinsic::arm_strex: {
10494 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10495 Info.opc = ISD::INTRINSIC_W_CHAIN;
10496 Info.memVT = MVT::getVT(PtrTy->getElementType());
10497 Info.ptrVal = I.getArgOperand(1);
10499 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10501 Info.readMem = false;
10502 Info.writeMem = true;
10505 case Intrinsic::arm_stlexd:
10506 case Intrinsic::arm_strexd: {
10507 Info.opc = ISD::INTRINSIC_W_CHAIN;
10508 Info.memVT = MVT::i64;
10509 Info.ptrVal = I.getArgOperand(2);
10513 Info.readMem = false;
10514 Info.writeMem = true;
10517 case Intrinsic::arm_ldaexd:
10518 case Intrinsic::arm_ldrexd: {
10519 Info.opc = ISD::INTRINSIC_W_CHAIN;
10520 Info.memVT = MVT::i64;
10521 Info.ptrVal = I.getArgOperand(0);
10525 Info.readMem = true;
10526 Info.writeMem = false;
10536 /// \brief Returns true if it is beneficial to convert a load of a constant
10537 /// to just the constant itself.
10538 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10540 assert(Ty->isIntegerTy());
10542 unsigned Bits = Ty->getPrimitiveSizeInBits();
10543 if (Bits == 0 || Bits > 32)
10548 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10549 // Loads and stores less than 64-bits are already atomic; ones above that
10550 // are doomed anyway, so defer to the default libcall and blame the OS when
10551 // things go wrong:
10552 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10553 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10554 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10555 return LI->getType()->getPrimitiveSizeInBits() == 64;
10557 // For the real atomic operations, we have ldrex/strex up to 64 bits.
10558 return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10561 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10562 AtomicOrdering Ord) const {
10563 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10564 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10566 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10568 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10569 // intrinsic must return {i32, i32} and we have to recombine them into a
10570 // single i64 here.
10571 if (ValTy->getPrimitiveSizeInBits() == 64) {
10572 Intrinsic::ID Int =
10573 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10574 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10576 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10577 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10579 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10580 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10581 if (!Subtarget->isLittle())
10582 std::swap (Lo, Hi);
10583 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10584 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10585 return Builder.CreateOr(
10586 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10589 Type *Tys[] = { Addr->getType() };
10590 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10591 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10593 return Builder.CreateTruncOrBitCast(
10594 Builder.CreateCall(Ldrex, Addr),
10595 cast<PointerType>(Addr->getType())->getElementType());
10598 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10600 AtomicOrdering Ord) const {
10601 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10603 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10605 // Since the intrinsics must have legal type, the i64 intrinsics take two
10606 // parameters: "i32, i32". We must marshal Val into the appropriate form
10607 // before the call.
10608 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10609 Intrinsic::ID Int =
10610 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10611 Function *Strex = Intrinsic::getDeclaration(M, Int);
10612 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10614 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10615 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10616 if (!Subtarget->isLittle())
10617 std::swap (Lo, Hi);
10618 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10619 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10622 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10623 Type *Tys[] = { Addr->getType() };
10624 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10626 return Builder.CreateCall2(
10627 Strex, Builder.CreateZExtOrBitCast(
10628 Val, Strex->getFunctionType()->getParamType(0)),