1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57 // This option should go away when tail calls fully work.
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65 cl::desc("Generate calls via indirect call instructions"),
69 ARMInterworking("arm-interworking", cl::Hidden,
70 cl::desc("Enable / disable ARM interworking (for debugging only)"),
74 class ARMCCState : public CCState {
76 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
78 LLVMContext &C, ParmContext PC)
79 : CCState(CC, isVarArg, MF, TM, locs, C) {
80 assert(((PC == Call) || (PC == Prologue)) &&
81 "ARMCCState users must specify whether their context is call"
82 "or prologue generation.");
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90 ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94 MVT PromotedBitwiseVT) {
95 if (VT != PromotedLdStVT) {
96 setOperationAction(ISD::LOAD, VT, Promote);
97 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
99 setOperationAction(ISD::STORE, VT, Promote);
100 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
103 MVT ElemTy = VT.getVectorElementType();
104 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105 setOperationAction(ISD::SETCC, VT, Custom);
106 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108 if (ElemTy == MVT::i32) {
109 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
114 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
119 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
120 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
121 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
122 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123 setOperationAction(ISD::SELECT, VT, Expand);
124 setOperationAction(ISD::SELECT_CC, VT, Expand);
125 setOperationAction(ISD::VSELECT, VT, Expand);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127 if (VT.isInteger()) {
128 setOperationAction(ISD::SHL, VT, Custom);
129 setOperationAction(ISD::SRA, VT, Custom);
130 setOperationAction(ISD::SRL, VT, Custom);
133 // Promote all bit-wise operations.
134 if (VT.isInteger() && VT != PromotedBitwiseVT) {
135 setOperationAction(ISD::AND, VT, Promote);
136 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137 setOperationAction(ISD::OR, VT, Promote);
138 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
139 setOperationAction(ISD::XOR, VT, Promote);
140 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
143 // Neon does not support vector divide/remainder operations.
144 setOperationAction(ISD::SDIV, VT, Expand);
145 setOperationAction(ISD::UDIV, VT, Expand);
146 setOperationAction(ISD::FDIV, VT, Expand);
147 setOperationAction(ISD::SREM, VT, Expand);
148 setOperationAction(ISD::UREM, VT, Expand);
149 setOperationAction(ISD::FREM, VT, Expand);
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153 addRegisterClass(VT, &ARM::DPRRegClass);
154 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::QPRRegClass);
159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164 return new TargetLoweringObjectFileMachO();
166 return new ARMElfTargetObjectFile();
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170 : TargetLowering(TM, createTLOF(TM)) {
171 Subtarget = &TM.getSubtarget<ARMSubtarget>();
172 RegInfo = TM.getRegisterInfo();
173 Itins = TM.getInstrItineraryData();
175 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
177 if (Subtarget->isTargetDarwin()) {
178 // Uses VFP for Thumb libfuncs if available.
179 if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180 // Single-precision floating-point arithmetic.
181 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
186 // Double-precision floating-point arithmetic.
187 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
192 // Single-precision comparisons.
193 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
200 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
202 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
209 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
211 // Double-precision comparisons.
212 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
219 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
221 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
228 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
230 // Floating-point to integer conversions.
231 // i64 conversions are done via library routines even when generating VFP
232 // instructions, so use the same ones.
233 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
238 // Conversions between floating types.
239 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
242 // Integer to floating-point conversions.
243 // i64 conversions are done via library routines even when generating VFP
244 // instructions, so use the same ones.
245 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246 // e.g., __floatunsidf vs. __floatunssidfvfp.
247 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
254 // These libcalls are not available in 32-bit.
255 setLibcallName(RTLIB::SHL_I128, 0);
256 setLibcallName(RTLIB::SRL_I128, 0);
257 setLibcallName(RTLIB::SRA_I128, 0);
259 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260 // Double-precision floating-point arithmetic helper functions
261 // RTABI chapter 4.1.2, Table 2
262 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
271 // Double-precision floating-point comparison helper functions
272 // RTABI chapter 4.1.2, Table 3
273 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
286 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
287 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
288 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
289 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
298 // Single-precision floating-point arithmetic helper functions
299 // RTABI chapter 4.1.2, Table 4
300 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
309 // Single-precision floating-point comparison helper functions
310 // RTABI chapter 4.1.2, Table 5
311 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
324 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
325 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
326 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
327 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
336 // Floating-point to integer conversions.
337 // RTABI chapter 4.1.2, Table 6
338 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
355 // Conversions between floating types.
356 // RTABI chapter 4.1.2, Table 7
357 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
359 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
362 // Integer to floating-point conversions.
363 // RTABI chapter 4.1.2, Table 8
364 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
381 // Long long helper functions
382 // RTABI chapter 4.2, Table 9
383 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
384 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
394 // Integer division functions
395 // RTABI chapter 4.3.1
396 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
397 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
401 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
414 // RTABI chapter 4.3.4
415 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
416 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
418 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
423 // Use divmod compiler-rt calls for iOS 5.0 and later.
424 if (Subtarget->getTargetTriple().isiOS() &&
425 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
430 if (Subtarget->isThumb1Only())
431 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
433 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435 !Subtarget->isThumb1Only()) {
436 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437 if (!Subtarget->isFPOnlySP())
438 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
440 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
443 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447 setTruncStoreAction((MVT::SimpleValueType)VT,
448 (MVT::SimpleValueType)InnerVT, Expand);
449 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
454 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
457 if (Subtarget->hasNEON()) {
458 addDRTypeForNEON(MVT::v2f32);
459 addDRTypeForNEON(MVT::v8i8);
460 addDRTypeForNEON(MVT::v4i16);
461 addDRTypeForNEON(MVT::v2i32);
462 addDRTypeForNEON(MVT::v1i64);
464 addQRTypeForNEON(MVT::v4f32);
465 addQRTypeForNEON(MVT::v2f64);
466 addQRTypeForNEON(MVT::v16i8);
467 addQRTypeForNEON(MVT::v8i16);
468 addQRTypeForNEON(MVT::v4i32);
469 addQRTypeForNEON(MVT::v2i64);
471 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
472 // neither Neon nor VFP support any arithmetic operations on it.
473 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
474 // supported for v4f32.
475 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
476 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
477 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
478 // FIXME: Code duplication: FDIV and FREM are expanded always, see
479 // ARMTargetLowering::addTypeForNEON method for details.
480 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
481 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
482 // FIXME: Create unittest.
483 // In another words, find a way when "copysign" appears in DAG with vector
485 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
486 // FIXME: Code duplication: SETCC has custom operation action, see
487 // ARMTargetLowering::addTypeForNEON method for details.
488 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
489 // FIXME: Create unittest for FNEG and for FABS.
490 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
491 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
492 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
493 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
494 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
495 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
496 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
497 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
498 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
499 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
500 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
501 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
502 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
503 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
504 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
505 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
506 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
507 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
508 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
510 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
511 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
512 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
513 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
514 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
515 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
516 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
517 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
518 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
519 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
520 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
521 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
522 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
523 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
524 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
526 // Mark v2f32 intrinsics.
527 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
528 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
529 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
530 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
531 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
532 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
533 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
534 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
535 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
536 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
537 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
538 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
539 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
540 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
541 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
543 // Neon does not support some operations on v1i64 and v2i64 types.
544 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
545 // Custom handling for some quad-vector types to detect VMULL.
546 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
547 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
548 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
549 // Custom handling for some vector types to avoid expensive expansions
550 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
551 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
552 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
553 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
554 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
555 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
556 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
557 // a destination type that is wider than the source, and nor does
558 // it have a FP_TO_[SU]INT instruction with a narrower destination than
560 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
561 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
562 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
563 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
565 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
566 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
568 // Custom expand long extensions to vectors.
569 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
570 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
571 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
572 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
573 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
574 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
575 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
576 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
578 // NEON does not have single instruction CTPOP for vectors with element
579 // types wider than 8-bits. However, custom lowering can leverage the
580 // v8i8/v16i8 vcnt instruction.
581 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
582 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
583 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
584 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
586 // NEON only has FMA instructions as of VFP4.
587 if (!Subtarget->hasVFP4()) {
588 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
589 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
592 setTargetDAGCombine(ISD::INTRINSIC_VOID);
593 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
594 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
595 setTargetDAGCombine(ISD::SHL);
596 setTargetDAGCombine(ISD::SRL);
597 setTargetDAGCombine(ISD::SRA);
598 setTargetDAGCombine(ISD::SIGN_EXTEND);
599 setTargetDAGCombine(ISD::ZERO_EXTEND);
600 setTargetDAGCombine(ISD::ANY_EXTEND);
601 setTargetDAGCombine(ISD::SELECT_CC);
602 setTargetDAGCombine(ISD::BUILD_VECTOR);
603 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
604 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
605 setTargetDAGCombine(ISD::STORE);
606 setTargetDAGCombine(ISD::FP_TO_SINT);
607 setTargetDAGCombine(ISD::FP_TO_UINT);
608 setTargetDAGCombine(ISD::FDIV);
610 // It is legal to extload from v4i8 to v4i16 or v4i32.
611 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
612 MVT::v4i16, MVT::v2i16,
614 for (unsigned i = 0; i < 6; ++i) {
615 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
616 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
617 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
621 // ARM and Thumb2 support UMLAL/SMLAL.
622 if (!Subtarget->isThumb1Only())
623 setTargetDAGCombine(ISD::ADDC);
626 computeRegisterProperties();
628 // ARM does not have f32 extending load.
629 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
631 // ARM does not have i1 sign extending load.
632 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
634 // ARM supports all 4 flavors of integer indexed load / store.
635 if (!Subtarget->isThumb1Only()) {
636 for (unsigned im = (unsigned)ISD::PRE_INC;
637 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
638 setIndexedLoadAction(im, MVT::i1, Legal);
639 setIndexedLoadAction(im, MVT::i8, Legal);
640 setIndexedLoadAction(im, MVT::i16, Legal);
641 setIndexedLoadAction(im, MVT::i32, Legal);
642 setIndexedStoreAction(im, MVT::i1, Legal);
643 setIndexedStoreAction(im, MVT::i8, Legal);
644 setIndexedStoreAction(im, MVT::i16, Legal);
645 setIndexedStoreAction(im, MVT::i32, Legal);
649 // i64 operation support.
650 setOperationAction(ISD::MUL, MVT::i64, Expand);
651 setOperationAction(ISD::MULHU, MVT::i32, Expand);
652 if (Subtarget->isThumb1Only()) {
653 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
654 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
656 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
657 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
658 setOperationAction(ISD::MULHS, MVT::i32, Expand);
660 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
661 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
662 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
663 setOperationAction(ISD::SRL, MVT::i64, Custom);
664 setOperationAction(ISD::SRA, MVT::i64, Custom);
666 if (!Subtarget->isThumb1Only()) {
667 // FIXME: We should do this for Thumb1 as well.
668 setOperationAction(ISD::ADDC, MVT::i32, Custom);
669 setOperationAction(ISD::ADDE, MVT::i32, Custom);
670 setOperationAction(ISD::SUBC, MVT::i32, Custom);
671 setOperationAction(ISD::SUBE, MVT::i32, Custom);
674 // ARM does not have ROTL.
675 setOperationAction(ISD::ROTL, MVT::i32, Expand);
676 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
677 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
678 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
679 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
681 // These just redirect to CTTZ and CTLZ on ARM.
682 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
683 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
685 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
687 // Only ARMv6 has BSWAP.
688 if (!Subtarget->hasV6Ops())
689 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
691 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
692 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
693 // These are expanded into libcalls if the cpu doesn't have HW divider.
694 setOperationAction(ISD::SDIV, MVT::i32, Expand);
695 setOperationAction(ISD::UDIV, MVT::i32, Expand);
698 // FIXME: Also set divmod for SREM on EABI
699 setOperationAction(ISD::SREM, MVT::i32, Expand);
700 setOperationAction(ISD::UREM, MVT::i32, Expand);
701 // Register based DivRem for AEABI (RTABI 4.2)
702 if (Subtarget->isTargetAEABI()) {
703 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
704 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
705 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
706 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
707 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
708 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
709 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
710 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
712 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
713 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
714 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
715 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
716 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
717 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
718 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
719 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
721 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
722 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
724 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
725 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
728 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
729 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
730 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
731 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
732 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
734 setOperationAction(ISD::TRAP, MVT::Other, Legal);
736 // Use the default implementation.
737 setOperationAction(ISD::VASTART, MVT::Other, Custom);
738 setOperationAction(ISD::VAARG, MVT::Other, Expand);
739 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
740 setOperationAction(ISD::VAEND, MVT::Other, Expand);
741 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
742 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
744 if (!Subtarget->isTargetDarwin()) {
745 // Non-Darwin platforms may return values in these registers via the
746 // personality function.
747 setExceptionPointerRegister(ARM::R0);
748 setExceptionSelectorRegister(ARM::R1);
751 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
752 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
753 // the default expansion.
754 // FIXME: This should be checking for v6k, not just v6.
755 if (Subtarget->hasDataBarrier() ||
756 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
757 // membarrier needs custom lowering; the rest are legal and handled
759 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
760 // Custom lowering for 64-bit ops
761 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
762 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
763 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
764 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
765 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
766 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
767 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
768 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
769 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
770 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
771 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
772 // On v8, we have particularly efficient implementations of atomic fences
773 // if they can be combined with nearby atomic loads and stores.
774 if (!Subtarget->hasV8Ops()) {
775 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
776 setInsertFencesForAtomic(true);
778 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
779 //setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Custom);
781 // Set them all for expansion, which will force libcalls.
782 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
783 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
784 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
785 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
786 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
787 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
788 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
789 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
790 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
791 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
792 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
793 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
794 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
795 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
796 // Unordered/Monotonic case.
797 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
798 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
801 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
803 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
804 if (!Subtarget->hasV6Ops()) {
805 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
806 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
808 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
810 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
811 !Subtarget->isThumb1Only()) {
812 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
813 // iff target supports vfp2.
814 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
815 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
818 // We want to custom lower some of our intrinsics.
819 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
820 if (Subtarget->isTargetDarwin()) {
821 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
822 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
823 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
826 setOperationAction(ISD::SETCC, MVT::i32, Expand);
827 setOperationAction(ISD::SETCC, MVT::f32, Expand);
828 setOperationAction(ISD::SETCC, MVT::f64, Expand);
829 setOperationAction(ISD::SELECT, MVT::i32, Custom);
830 setOperationAction(ISD::SELECT, MVT::f32, Custom);
831 setOperationAction(ISD::SELECT, MVT::f64, Custom);
832 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
833 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
834 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
836 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
837 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
838 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
839 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
840 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
842 // We don't support sin/cos/fmod/copysign/pow
843 setOperationAction(ISD::FSIN, MVT::f64, Expand);
844 setOperationAction(ISD::FSIN, MVT::f32, Expand);
845 setOperationAction(ISD::FCOS, MVT::f32, Expand);
846 setOperationAction(ISD::FCOS, MVT::f64, Expand);
847 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
848 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
849 setOperationAction(ISD::FREM, MVT::f64, Expand);
850 setOperationAction(ISD::FREM, MVT::f32, Expand);
851 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
852 !Subtarget->isThumb1Only()) {
853 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
854 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
856 setOperationAction(ISD::FPOW, MVT::f64, Expand);
857 setOperationAction(ISD::FPOW, MVT::f32, Expand);
859 if (!Subtarget->hasVFP4()) {
860 setOperationAction(ISD::FMA, MVT::f64, Expand);
861 setOperationAction(ISD::FMA, MVT::f32, Expand);
864 // Various VFP goodness
865 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
866 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
867 if (Subtarget->hasVFP2()) {
868 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
869 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
870 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
871 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
873 // Special handling for half-precision FP.
874 if (!Subtarget->hasFP16()) {
875 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
876 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
880 // We have target-specific dag combine patterns for the following nodes:
881 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
882 setTargetDAGCombine(ISD::ADD);
883 setTargetDAGCombine(ISD::SUB);
884 setTargetDAGCombine(ISD::MUL);
885 setTargetDAGCombine(ISD::AND);
886 setTargetDAGCombine(ISD::OR);
887 setTargetDAGCombine(ISD::XOR);
889 if (Subtarget->hasV6Ops())
890 setTargetDAGCombine(ISD::SRL);
892 setStackPointerRegisterToSaveRestore(ARM::SP);
894 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
895 !Subtarget->hasVFP2())
896 setSchedulingPreference(Sched::RegPressure);
898 setSchedulingPreference(Sched::Hybrid);
900 //// temporary - rewrite interface to use type
901 MaxStoresPerMemset = 8;
902 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
903 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
904 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
905 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
906 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
908 // On ARM arguments smaller than 4 bytes are extended, so all arguments
909 // are at least 4 bytes aligned.
910 setMinStackArgumentAlignment(4);
912 // Prefer likely predicted branches to selects on out-of-order cores.
913 PredictableSelectIsExpensive = Subtarget->isLikeA9();
915 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
918 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
919 bool isThumb2, unsigned &LdrOpc,
921 static const unsigned LoadBares[4][2] = {{ARM::LDREXB, ARM::t2LDREXB},
922 {ARM::LDREXH, ARM::t2LDREXH},
923 {ARM::LDREX, ARM::t2LDREX},
924 {ARM::LDREXD, ARM::t2LDREXD}};
925 static const unsigned LoadAcqs[4][2] = {{ARM::LDAEXB, ARM::t2LDAEXB},
926 {ARM::LDAEXH, ARM::t2LDAEXH},
927 {ARM::LDAEX, ARM::t2LDAEX},
928 {ARM::LDAEXD, ARM::t2LDAEXD}};
929 static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
930 {ARM::STREXH, ARM::t2STREXH},
931 {ARM::STREX, ARM::t2STREX},
932 {ARM::STREXD, ARM::t2STREXD}};
933 static const unsigned StoreRels[4][2] = {{ARM::STLEXB, ARM::t2STLEXB},
934 {ARM::STLEXH, ARM::t2STLEXH},
935 {ARM::STLEX, ARM::t2STLEX},
936 {ARM::STLEXD, ARM::t2STLEXD}};
938 const unsigned (*LoadOps)[2], (*StoreOps)[2];
939 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
944 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
945 StoreOps = StoreRels;
947 StoreOps = StoreBares;
949 assert(isPowerOf2_32(Size) && Size <= 8 &&
950 "unsupported size for atomic binary op!");
952 LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
953 StrOpc = StoreOps[Log2_32(Size)][isThumb2];
956 // FIXME: It might make sense to define the representative register class as the
957 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
958 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
959 // SPR's representative would be DPR_VFP2. This should work well if register
960 // pressure tracking were modified such that a register use would increment the
961 // pressure of the register class's representative and all of it's super
962 // classes' representatives transitively. We have not implemented this because
963 // of the difficulty prior to coalescing of modeling operand register classes
964 // due to the common occurrence of cross class copies and subregister insertions
966 std::pair<const TargetRegisterClass*, uint8_t>
967 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
968 const TargetRegisterClass *RRC = 0;
970 switch (VT.SimpleTy) {
972 return TargetLowering::findRepresentativeClass(VT);
973 // Use DPR as representative register class for all floating point
974 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
975 // the cost is 1 for both f32 and f64.
976 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
977 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
978 RRC = &ARM::DPRRegClass;
979 // When NEON is used for SP, only half of the register file is available
980 // because operations that define both SP and DP results will be constrained
981 // to the VFP2 class (D0-D15). We currently model this constraint prior to
982 // coalescing by double-counting the SP regs. See the FIXME above.
983 if (Subtarget->useNEONForSinglePrecisionFP())
986 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
987 case MVT::v4f32: case MVT::v2f64:
988 RRC = &ARM::DPRRegClass;
992 RRC = &ARM::DPRRegClass;
996 RRC = &ARM::DPRRegClass;
1000 return std::make_pair(RRC, Cost);
1003 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1006 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1007 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
1008 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1009 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1010 case ARMISD::CALL: return "ARMISD::CALL";
1011 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1012 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1013 case ARMISD::tCALL: return "ARMISD::tCALL";
1014 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1015 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1016 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1017 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1018 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1019 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1020 case ARMISD::CMP: return "ARMISD::CMP";
1021 case ARMISD::CMN: return "ARMISD::CMN";
1022 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1023 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1024 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1025 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1026 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1028 case ARMISD::CMOV: return "ARMISD::CMOV";
1030 case ARMISD::RBIT: return "ARMISD::RBIT";
1032 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1033 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1034 case ARMISD::SITOF: return "ARMISD::SITOF";
1035 case ARMISD::UITOF: return "ARMISD::UITOF";
1037 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1038 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1039 case ARMISD::RRX: return "ARMISD::RRX";
1041 case ARMISD::ADDC: return "ARMISD::ADDC";
1042 case ARMISD::ADDE: return "ARMISD::ADDE";
1043 case ARMISD::SUBC: return "ARMISD::SUBC";
1044 case ARMISD::SUBE: return "ARMISD::SUBE";
1046 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1047 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1049 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1050 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1052 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1054 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1056 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1058 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1060 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1062 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1063 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1064 case ARMISD::VCGE: return "ARMISD::VCGE";
1065 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1066 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1067 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1068 case ARMISD::VCGT: return "ARMISD::VCGT";
1069 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1070 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1071 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1072 case ARMISD::VTST: return "ARMISD::VTST";
1074 case ARMISD::VSHL: return "ARMISD::VSHL";
1075 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1076 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1077 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
1078 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
1079 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
1080 case ARMISD::VSHRN: return "ARMISD::VSHRN";
1081 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1082 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1083 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1084 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1085 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1086 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1087 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1088 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1089 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1090 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1091 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1092 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1093 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1094 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1095 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1096 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1097 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1098 case ARMISD::VDUP: return "ARMISD::VDUP";
1099 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1100 case ARMISD::VEXT: return "ARMISD::VEXT";
1101 case ARMISD::VREV64: return "ARMISD::VREV64";
1102 case ARMISD::VREV32: return "ARMISD::VREV32";
1103 case ARMISD::VREV16: return "ARMISD::VREV16";
1104 case ARMISD::VZIP: return "ARMISD::VZIP";
1105 case ARMISD::VUZP: return "ARMISD::VUZP";
1106 case ARMISD::VTRN: return "ARMISD::VTRN";
1107 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1108 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1109 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1110 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1111 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1112 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1113 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1114 case ARMISD::FMAX: return "ARMISD::FMAX";
1115 case ARMISD::FMIN: return "ARMISD::FMIN";
1116 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1117 case ARMISD::VMINNM: return "ARMISD::VMIN";
1118 case ARMISD::BFI: return "ARMISD::BFI";
1119 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1120 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1121 case ARMISD::VBSL: return "ARMISD::VBSL";
1122 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1123 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1124 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1125 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1126 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1127 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1128 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1129 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1130 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1131 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1132 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1133 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1134 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1135 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1136 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1137 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1138 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1139 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1140 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1141 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1145 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1146 if (!VT.isVector()) return getPointerTy();
1147 return VT.changeVectorElementTypeToInteger();
1150 /// getRegClassFor - Return the register class that should be used for the
1151 /// specified value type.
1152 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1153 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1154 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1155 // load / store 4 to 8 consecutive D registers.
1156 if (Subtarget->hasNEON()) {
1157 if (VT == MVT::v4i64)
1158 return &ARM::QQPRRegClass;
1159 if (VT == MVT::v8i64)
1160 return &ARM::QQQQPRRegClass;
1162 return TargetLowering::getRegClassFor(VT);
1165 // Create a fast isel object.
1167 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1168 const TargetLibraryInfo *libInfo) const {
1169 return ARM::createFastISel(funcInfo, libInfo);
1172 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1173 /// be used for loads / stores from the global.
1174 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1175 return (Subtarget->isThumb1Only() ? 127 : 4095);
1178 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1179 unsigned NumVals = N->getNumValues();
1181 return Sched::RegPressure;
1183 for (unsigned i = 0; i != NumVals; ++i) {
1184 EVT VT = N->getValueType(i);
1185 if (VT == MVT::Glue || VT == MVT::Other)
1187 if (VT.isFloatingPoint() || VT.isVector())
1191 if (!N->isMachineOpcode())
1192 return Sched::RegPressure;
1194 // Load are scheduled for latency even if there instruction itinerary
1195 // is not available.
1196 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1197 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1199 if (MCID.getNumDefs() == 0)
1200 return Sched::RegPressure;
1201 if (!Itins->isEmpty() &&
1202 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1205 return Sched::RegPressure;
1208 //===----------------------------------------------------------------------===//
1210 //===----------------------------------------------------------------------===//
1212 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1213 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1215 default: llvm_unreachable("Unknown condition code!");
1216 case ISD::SETNE: return ARMCC::NE;
1217 case ISD::SETEQ: return ARMCC::EQ;
1218 case ISD::SETGT: return ARMCC::GT;
1219 case ISD::SETGE: return ARMCC::GE;
1220 case ISD::SETLT: return ARMCC::LT;
1221 case ISD::SETLE: return ARMCC::LE;
1222 case ISD::SETUGT: return ARMCC::HI;
1223 case ISD::SETUGE: return ARMCC::HS;
1224 case ISD::SETULT: return ARMCC::LO;
1225 case ISD::SETULE: return ARMCC::LS;
1229 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1230 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1231 ARMCC::CondCodes &CondCode2) {
1232 CondCode2 = ARMCC::AL;
1234 default: llvm_unreachable("Unknown FP condition!");
1236 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1238 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1240 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1241 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1242 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1243 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1244 case ISD::SETO: CondCode = ARMCC::VC; break;
1245 case ISD::SETUO: CondCode = ARMCC::VS; break;
1246 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1247 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1248 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1250 case ISD::SETULT: CondCode = ARMCC::LT; break;
1252 case ISD::SETULE: CondCode = ARMCC::LE; break;
1254 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1258 //===----------------------------------------------------------------------===//
1259 // Calling Convention Implementation
1260 //===----------------------------------------------------------------------===//
1262 #include "ARMGenCallingConv.inc"
1264 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1265 /// given CallingConvention value.
1266 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1268 bool isVarArg) const {
1271 llvm_unreachable("Unsupported calling convention");
1272 case CallingConv::Fast:
1273 if (Subtarget->hasVFP2() && !isVarArg) {
1274 if (!Subtarget->isAAPCS_ABI())
1275 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1276 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1277 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1280 case CallingConv::C: {
1281 // Use target triple & subtarget features to do actual dispatch.
1282 if (!Subtarget->isAAPCS_ABI())
1283 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1284 else if (Subtarget->hasVFP2() &&
1285 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1287 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1288 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1290 case CallingConv::ARM_AAPCS_VFP:
1292 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1294 case CallingConv::ARM_AAPCS:
1295 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1296 case CallingConv::ARM_APCS:
1297 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1298 case CallingConv::GHC:
1299 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1303 /// LowerCallResult - Lower the result values of a call into the
1304 /// appropriate copies out of appropriate physical registers.
1306 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1307 CallingConv::ID CallConv, bool isVarArg,
1308 const SmallVectorImpl<ISD::InputArg> &Ins,
1309 SDLoc dl, SelectionDAG &DAG,
1310 SmallVectorImpl<SDValue> &InVals,
1311 bool isThisReturn, SDValue ThisVal) const {
1313 // Assign locations to each value returned by this call.
1314 SmallVector<CCValAssign, 16> RVLocs;
1315 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1316 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1317 CCInfo.AnalyzeCallResult(Ins,
1318 CCAssignFnForNode(CallConv, /* Return*/ true,
1321 // Copy all of the result registers out of their specified physreg.
1322 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1323 CCValAssign VA = RVLocs[i];
1325 // Pass 'this' value directly from the argument to return value, to avoid
1326 // reg unit interference
1327 if (i == 0 && isThisReturn) {
1328 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1329 "unexpected return calling convention register assignment");
1330 InVals.push_back(ThisVal);
1335 if (VA.needsCustom()) {
1336 // Handle f64 or half of a v2f64.
1337 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1339 Chain = Lo.getValue(1);
1340 InFlag = Lo.getValue(2);
1341 VA = RVLocs[++i]; // skip ahead to next loc
1342 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1344 Chain = Hi.getValue(1);
1345 InFlag = Hi.getValue(2);
1346 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1348 if (VA.getLocVT() == MVT::v2f64) {
1349 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1350 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1351 DAG.getConstant(0, MVT::i32));
1353 VA = RVLocs[++i]; // skip ahead to next loc
1354 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1355 Chain = Lo.getValue(1);
1356 InFlag = Lo.getValue(2);
1357 VA = RVLocs[++i]; // skip ahead to next loc
1358 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1359 Chain = Hi.getValue(1);
1360 InFlag = Hi.getValue(2);
1361 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1362 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1363 DAG.getConstant(1, MVT::i32));
1366 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1368 Chain = Val.getValue(1);
1369 InFlag = Val.getValue(2);
1372 switch (VA.getLocInfo()) {
1373 default: llvm_unreachable("Unknown loc info!");
1374 case CCValAssign::Full: break;
1375 case CCValAssign::BCvt:
1376 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1380 InVals.push_back(Val);
1386 /// LowerMemOpCallTo - Store the argument to the stack.
1388 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1389 SDValue StackPtr, SDValue Arg,
1390 SDLoc dl, SelectionDAG &DAG,
1391 const CCValAssign &VA,
1392 ISD::ArgFlagsTy Flags) const {
1393 unsigned LocMemOffset = VA.getLocMemOffset();
1394 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1395 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1396 return DAG.getStore(Chain, dl, Arg, PtrOff,
1397 MachinePointerInfo::getStack(LocMemOffset),
1401 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1402 SDValue Chain, SDValue &Arg,
1403 RegsToPassVector &RegsToPass,
1404 CCValAssign &VA, CCValAssign &NextVA,
1406 SmallVectorImpl<SDValue> &MemOpChains,
1407 ISD::ArgFlagsTy Flags) const {
1409 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1410 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1411 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1413 if (NextVA.isRegLoc())
1414 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1416 assert(NextVA.isMemLoc());
1417 if (StackPtr.getNode() == 0)
1418 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1420 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1426 /// LowerCall - Lowering a call into a callseq_start <-
1427 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1430 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1431 SmallVectorImpl<SDValue> &InVals) const {
1432 SelectionDAG &DAG = CLI.DAG;
1434 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1435 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1436 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1437 SDValue Chain = CLI.Chain;
1438 SDValue Callee = CLI.Callee;
1439 bool &isTailCall = CLI.IsTailCall;
1440 CallingConv::ID CallConv = CLI.CallConv;
1441 bool doesNotRet = CLI.DoesNotReturn;
1442 bool isVarArg = CLI.IsVarArg;
1444 MachineFunction &MF = DAG.getMachineFunction();
1445 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1446 bool isThisReturn = false;
1447 bool isSibCall = false;
1448 // Disable tail calls if they're not supported.
1449 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1452 // Check if it's really possible to do a tail call.
1453 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1454 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1455 Outs, OutVals, Ins, DAG);
1456 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1457 // detected sibcalls.
1464 // Analyze operands of the call, assigning locations to each operand.
1465 SmallVector<CCValAssign, 16> ArgLocs;
1466 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1467 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1468 CCInfo.AnalyzeCallOperands(Outs,
1469 CCAssignFnForNode(CallConv, /* Return*/ false,
1472 // Get a count of how many bytes are to be pushed on the stack.
1473 unsigned NumBytes = CCInfo.getNextStackOffset();
1475 // For tail calls, memory operands are available in our caller's stack.
1479 // Adjust the stack pointer for the new arguments...
1480 // These operations are automatically eliminated by the prolog/epilog pass
1482 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1485 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1487 RegsToPassVector RegsToPass;
1488 SmallVector<SDValue, 8> MemOpChains;
1490 // Walk the register/memloc assignments, inserting copies/loads. In the case
1491 // of tail call optimization, arguments are handled later.
1492 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1494 ++i, ++realArgIdx) {
1495 CCValAssign &VA = ArgLocs[i];
1496 SDValue Arg = OutVals[realArgIdx];
1497 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1498 bool isByVal = Flags.isByVal();
1500 // Promote the value if needed.
1501 switch (VA.getLocInfo()) {
1502 default: llvm_unreachable("Unknown loc info!");
1503 case CCValAssign::Full: break;
1504 case CCValAssign::SExt:
1505 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1507 case CCValAssign::ZExt:
1508 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1510 case CCValAssign::AExt:
1511 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1513 case CCValAssign::BCvt:
1514 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1518 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1519 if (VA.needsCustom()) {
1520 if (VA.getLocVT() == MVT::v2f64) {
1521 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1522 DAG.getConstant(0, MVT::i32));
1523 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1524 DAG.getConstant(1, MVT::i32));
1526 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1527 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1529 VA = ArgLocs[++i]; // skip ahead to next loc
1530 if (VA.isRegLoc()) {
1531 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1532 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1534 assert(VA.isMemLoc());
1536 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1537 dl, DAG, VA, Flags));
1540 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1541 StackPtr, MemOpChains, Flags);
1543 } else if (VA.isRegLoc()) {
1544 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1545 assert(VA.getLocVT() == MVT::i32 &&
1546 "unexpected calling convention register assignment");
1547 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1548 "unexpected use of 'returned'");
1549 isThisReturn = true;
1551 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1552 } else if (isByVal) {
1553 assert(VA.isMemLoc());
1554 unsigned offset = 0;
1556 // True if this byval aggregate will be split between registers
1558 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1559 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1561 if (CurByValIdx < ByValArgsCount) {
1563 unsigned RegBegin, RegEnd;
1564 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1566 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1568 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1569 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1570 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1571 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1572 MachinePointerInfo(),
1573 false, false, false, 0);
1574 MemOpChains.push_back(Load.getValue(1));
1575 RegsToPass.push_back(std::make_pair(j, Load));
1578 // If parameter size outsides register area, "offset" value
1579 // helps us to calculate stack slot for remained part properly.
1580 offset = RegEnd - RegBegin;
1582 CCInfo.nextInRegsParam();
1585 if (Flags.getByValSize() > 4*offset) {
1586 unsigned LocMemOffset = VA.getLocMemOffset();
1587 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1588 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1590 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1591 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1592 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1594 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1596 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1597 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1598 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1599 Ops, array_lengthof(Ops)));
1601 } else if (!isSibCall) {
1602 assert(VA.isMemLoc());
1604 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1605 dl, DAG, VA, Flags));
1609 if (!MemOpChains.empty())
1610 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1611 &MemOpChains[0], MemOpChains.size());
1613 // Build a sequence of copy-to-reg nodes chained together with token chain
1614 // and flag operands which copy the outgoing args into the appropriate regs.
1616 // Tail call byval lowering might overwrite argument registers so in case of
1617 // tail call optimization the copies to registers are lowered later.
1619 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1620 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1621 RegsToPass[i].second, InFlag);
1622 InFlag = Chain.getValue(1);
1625 // For tail calls lower the arguments to the 'real' stack slot.
1627 // Force all the incoming stack arguments to be loaded from the stack
1628 // before any new outgoing arguments are stored to the stack, because the
1629 // outgoing stack slots may alias the incoming argument stack slots, and
1630 // the alias isn't otherwise explicit. This is slightly more conservative
1631 // than necessary, because it means that each store effectively depends
1632 // on every argument instead of just those arguments it would clobber.
1634 // Do not flag preceding copytoreg stuff together with the following stuff.
1636 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1637 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1638 RegsToPass[i].second, InFlag);
1639 InFlag = Chain.getValue(1);
1644 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1645 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1646 // node so that legalize doesn't hack it.
1647 bool isDirect = false;
1648 bool isARMFunc = false;
1649 bool isLocalARMFunc = false;
1650 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1652 if (EnableARMLongCalls) {
1653 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1654 && "long-calls with non-static relocation model!");
1655 // Handle a global address or an external symbol. If it's not one of
1656 // those, the target's already in a register, so we don't need to do
1658 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1659 const GlobalValue *GV = G->getGlobal();
1660 // Create a constant pool entry for the callee address
1661 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1662 ARMConstantPoolValue *CPV =
1663 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1665 // Get the address of the callee into a register
1666 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1667 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1668 Callee = DAG.getLoad(getPointerTy(), dl,
1669 DAG.getEntryNode(), CPAddr,
1670 MachinePointerInfo::getConstantPool(),
1671 false, false, false, 0);
1672 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1673 const char *Sym = S->getSymbol();
1675 // Create a constant pool entry for the callee address
1676 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1677 ARMConstantPoolValue *CPV =
1678 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1679 ARMPCLabelIndex, 0);
1680 // Get the address of the callee into a register
1681 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1682 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1683 Callee = DAG.getLoad(getPointerTy(), dl,
1684 DAG.getEntryNode(), CPAddr,
1685 MachinePointerInfo::getConstantPool(),
1686 false, false, false, 0);
1688 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1689 const GlobalValue *GV = G->getGlobal();
1691 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1692 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1693 getTargetMachine().getRelocationModel() != Reloc::Static;
1694 isARMFunc = !Subtarget->isThumb() || isStub;
1695 // ARM call to a local ARM function is predicable.
1696 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1697 // tBX takes a register source operand.
1698 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1699 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1700 ARMConstantPoolValue *CPV =
1701 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1702 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1703 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1704 Callee = DAG.getLoad(getPointerTy(), dl,
1705 DAG.getEntryNode(), CPAddr,
1706 MachinePointerInfo::getConstantPool(),
1707 false, false, false, 0);
1708 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1709 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1710 getPointerTy(), Callee, PICLabel);
1712 // On ELF targets for PIC code, direct calls should go through the PLT
1713 unsigned OpFlags = 0;
1714 if (Subtarget->isTargetELF() &&
1715 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1716 OpFlags = ARMII::MO_PLT;
1717 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1719 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1721 bool isStub = Subtarget->isTargetDarwin() &&
1722 getTargetMachine().getRelocationModel() != Reloc::Static;
1723 isARMFunc = !Subtarget->isThumb() || isStub;
1724 // tBX takes a register source operand.
1725 const char *Sym = S->getSymbol();
1726 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1727 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1728 ARMConstantPoolValue *CPV =
1729 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1730 ARMPCLabelIndex, 4);
1731 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1732 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1733 Callee = DAG.getLoad(getPointerTy(), dl,
1734 DAG.getEntryNode(), CPAddr,
1735 MachinePointerInfo::getConstantPool(),
1736 false, false, false, 0);
1737 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1738 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1739 getPointerTy(), Callee, PICLabel);
1741 unsigned OpFlags = 0;
1742 // On ELF targets for PIC code, direct calls should go through the PLT
1743 if (Subtarget->isTargetELF() &&
1744 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1745 OpFlags = ARMII::MO_PLT;
1746 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1750 // FIXME: handle tail calls differently.
1752 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1753 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1754 if (Subtarget->isThumb()) {
1755 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1756 CallOpc = ARMISD::CALL_NOLINK;
1758 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1760 if (!isDirect && !Subtarget->hasV5TOps())
1761 CallOpc = ARMISD::CALL_NOLINK;
1762 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1763 // Emit regular call when code size is the priority
1765 // "mov lr, pc; b _foo" to avoid confusing the RSP
1766 CallOpc = ARMISD::CALL_NOLINK;
1768 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1771 std::vector<SDValue> Ops;
1772 Ops.push_back(Chain);
1773 Ops.push_back(Callee);
1775 // Add argument registers to the end of the list so that they are known live
1777 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1778 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1779 RegsToPass[i].second.getValueType()));
1781 // Add a register mask operand representing the call-preserved registers.
1782 const uint32_t *Mask;
1783 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1784 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1786 // For 'this' returns, use the R0-preserving mask if applicable
1787 Mask = ARI->getThisReturnPreservedMask(CallConv);
1789 // Set isThisReturn to false if the calling convention is not one that
1790 // allows 'returned' to be modeled in this way, so LowerCallResult does
1791 // not try to pass 'this' straight through
1792 isThisReturn = false;
1793 Mask = ARI->getCallPreservedMask(CallConv);
1796 Mask = ARI->getCallPreservedMask(CallConv);
1798 assert(Mask && "Missing call preserved mask for calling convention");
1799 Ops.push_back(DAG.getRegisterMask(Mask));
1801 if (InFlag.getNode())
1802 Ops.push_back(InFlag);
1804 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1806 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1808 // Returns a chain and a flag for retval copy to use.
1809 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1810 InFlag = Chain.getValue(1);
1812 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1813 DAG.getIntPtrConstant(0, true), InFlag, dl);
1815 InFlag = Chain.getValue(1);
1817 // Handle result values, copying them out of physregs into vregs that we
1819 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1820 InVals, isThisReturn,
1821 isThisReturn ? OutVals[0] : SDValue());
1824 /// HandleByVal - Every parameter *after* a byval parameter is passed
1825 /// on the stack. Remember the next parameter register to allocate,
1826 /// and then confiscate the rest of the parameter registers to insure
1829 ARMTargetLowering::HandleByVal(
1830 CCState *State, unsigned &size, unsigned Align) const {
1831 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1832 assert((State->getCallOrPrologue() == Prologue ||
1833 State->getCallOrPrologue() == Call) &&
1834 "unhandled ParmContext");
1836 // For in-prologue parameters handling, we also introduce stack offset
1837 // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1838 // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1839 // NSAA should be evaluted (NSAA means "next stacked argument address").
1840 // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1841 // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1842 unsigned NSAAOffset = State->getNextStackOffset();
1843 if (State->getCallOrPrologue() != Call) {
1844 for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1846 State->getInRegsParamInfo(i, RB, RE);
1847 assert(NSAAOffset >= (RE-RB)*4 &&
1848 "Stack offset for byval regs doesn't introduced anymore?");
1849 NSAAOffset -= (RE-RB)*4;
1852 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1853 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1854 unsigned AlignInRegs = Align / 4;
1855 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1856 for (unsigned i = 0; i < Waste; ++i)
1857 reg = State->AllocateReg(GPRArgRegs, 4);
1860 unsigned excess = 4 * (ARM::R4 - reg);
1862 // Special case when NSAA != SP and parameter size greater than size of
1863 // all remained GPR regs. In that case we can't split parameter, we must
1864 // send it to stack. We also must set NCRN to R4, so waste all
1865 // remained registers.
1866 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1867 while (State->AllocateReg(GPRArgRegs, 4))
1872 // First register for byval parameter is the first register that wasn't
1873 // allocated before this method call, so it would be "reg".
1874 // If parameter is small enough to be saved in range [reg, r4), then
1875 // the end (first after last) register would be reg + param-size-in-regs,
1876 // else parameter would be splitted between registers and stack,
1877 // end register would be r4 in this case.
1878 unsigned ByValRegBegin = reg;
1879 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1880 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1881 // Note, first register is allocated in the beginning of function already,
1882 // allocate remained amount of registers we need.
1883 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1884 State->AllocateReg(GPRArgRegs, 4);
1885 // At a call site, a byval parameter that is split between
1886 // registers and memory needs its size truncated here. In a
1887 // function prologue, such byval parameters are reassembled in
1888 // memory, and are not truncated.
1889 if (State->getCallOrPrologue() == Call) {
1890 // Make remained size equal to 0 in case, when
1891 // the whole structure may be stored into registers.
1901 /// MatchingStackOffset - Return true if the given stack call argument is
1902 /// already available in the same position (relatively) of the caller's
1903 /// incoming argument stack.
1905 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1906 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1907 const TargetInstrInfo *TII) {
1908 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1910 if (Arg.getOpcode() == ISD::CopyFromReg) {
1911 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1912 if (!TargetRegisterInfo::isVirtualRegister(VR))
1914 MachineInstr *Def = MRI->getVRegDef(VR);
1917 if (!Flags.isByVal()) {
1918 if (!TII->isLoadFromStackSlot(Def, FI))
1923 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1924 if (Flags.isByVal())
1925 // ByVal argument is passed in as a pointer but it's now being
1926 // dereferenced. e.g.
1927 // define @foo(%struct.X* %A) {
1928 // tail call @bar(%struct.X* byval %A)
1931 SDValue Ptr = Ld->getBasePtr();
1932 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1935 FI = FINode->getIndex();
1939 assert(FI != INT_MAX);
1940 if (!MFI->isFixedObjectIndex(FI))
1942 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1945 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1946 /// for tail call optimization. Targets which want to do tail call
1947 /// optimization should implement this function.
1949 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1950 CallingConv::ID CalleeCC,
1952 bool isCalleeStructRet,
1953 bool isCallerStructRet,
1954 const SmallVectorImpl<ISD::OutputArg> &Outs,
1955 const SmallVectorImpl<SDValue> &OutVals,
1956 const SmallVectorImpl<ISD::InputArg> &Ins,
1957 SelectionDAG& DAG) const {
1958 const Function *CallerF = DAG.getMachineFunction().getFunction();
1959 CallingConv::ID CallerCC = CallerF->getCallingConv();
1960 bool CCMatch = CallerCC == CalleeCC;
1962 // Look for obvious safe cases to perform tail call optimization that do not
1963 // require ABI changes. This is what gcc calls sibcall.
1965 // Do not sibcall optimize vararg calls unless the call site is not passing
1967 if (isVarArg && !Outs.empty())
1970 // Exception-handling functions need a special set of instructions to indicate
1971 // a return to the hardware. Tail-calling another function would probably
1973 if (CallerF->hasFnAttribute("interrupt"))
1976 // Also avoid sibcall optimization if either caller or callee uses struct
1977 // return semantics.
1978 if (isCalleeStructRet || isCallerStructRet)
1981 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1982 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1983 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1984 // support in the assembler and linker to be used. This would need to be
1985 // fixed to fully support tail calls in Thumb1.
1987 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1988 // LR. This means if we need to reload LR, it takes an extra instructions,
1989 // which outweighs the value of the tail call; but here we don't know yet
1990 // whether LR is going to be used. Probably the right approach is to
1991 // generate the tail call here and turn it back into CALL/RET in
1992 // emitEpilogue if LR is used.
1994 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1995 // but we need to make sure there are enough registers; the only valid
1996 // registers are the 4 used for parameters. We don't currently do this
1998 if (Subtarget->isThumb1Only())
2001 // If the calling conventions do not match, then we'd better make sure the
2002 // results are returned in the same way as what the caller expects.
2004 SmallVector<CCValAssign, 16> RVLocs1;
2005 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2006 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2007 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2009 SmallVector<CCValAssign, 16> RVLocs2;
2010 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2011 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2012 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2014 if (RVLocs1.size() != RVLocs2.size())
2016 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2017 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2019 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2021 if (RVLocs1[i].isRegLoc()) {
2022 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2025 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2031 // If Caller's vararg or byval argument has been split between registers and
2032 // stack, do not perform tail call, since part of the argument is in caller's
2034 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2035 getInfo<ARMFunctionInfo>();
2036 if (AFI_Caller->getArgRegsSaveSize())
2039 // If the callee takes no arguments then go on to check the results of the
2041 if (!Outs.empty()) {
2042 // Check if stack adjustment is needed. For now, do not do this if any
2043 // argument is passed on the stack.
2044 SmallVector<CCValAssign, 16> ArgLocs;
2045 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2046 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2047 CCInfo.AnalyzeCallOperands(Outs,
2048 CCAssignFnForNode(CalleeCC, false, isVarArg));
2049 if (CCInfo.getNextStackOffset()) {
2050 MachineFunction &MF = DAG.getMachineFunction();
2052 // Check if the arguments are already laid out in the right way as
2053 // the caller's fixed stack objects.
2054 MachineFrameInfo *MFI = MF.getFrameInfo();
2055 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2056 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2057 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2059 ++i, ++realArgIdx) {
2060 CCValAssign &VA = ArgLocs[i];
2061 EVT RegVT = VA.getLocVT();
2062 SDValue Arg = OutVals[realArgIdx];
2063 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2064 if (VA.getLocInfo() == CCValAssign::Indirect)
2066 if (VA.needsCustom()) {
2067 // f64 and vector types are split into multiple registers or
2068 // register/stack-slot combinations. The types will not match
2069 // the registers; give up on memory f64 refs until we figure
2070 // out what to do about this.
2073 if (!ArgLocs[++i].isRegLoc())
2075 if (RegVT == MVT::v2f64) {
2076 if (!ArgLocs[++i].isRegLoc())
2078 if (!ArgLocs[++i].isRegLoc())
2081 } else if (!VA.isRegLoc()) {
2082 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2094 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2095 MachineFunction &MF, bool isVarArg,
2096 const SmallVectorImpl<ISD::OutputArg> &Outs,
2097 LLVMContext &Context) const {
2098 SmallVector<CCValAssign, 16> RVLocs;
2099 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2100 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2104 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2105 SDLoc DL, SelectionDAG &DAG) {
2106 const MachineFunction &MF = DAG.getMachineFunction();
2107 const Function *F = MF.getFunction();
2109 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2111 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2112 // version of the "preferred return address". These offsets affect the return
2113 // instruction if this is a return from PL1 without hypervisor extensions.
2114 // IRQ/FIQ: +4 "subs pc, lr, #4"
2115 // SWI: 0 "subs pc, lr, #0"
2116 // ABORT: +4 "subs pc, lr, #4"
2117 // UNDEF: +4/+2 "subs pc, lr, #0"
2118 // UNDEF varies depending on where the exception came from ARM or Thumb
2119 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2122 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2125 else if (IntKind == "SWI" || IntKind == "UNDEF")
2128 report_fatal_error("Unsupported interrupt attribute. If present, value "
2129 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2131 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2133 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2134 RetOps.data(), RetOps.size());
2138 ARMTargetLowering::LowerReturn(SDValue Chain,
2139 CallingConv::ID CallConv, bool isVarArg,
2140 const SmallVectorImpl<ISD::OutputArg> &Outs,
2141 const SmallVectorImpl<SDValue> &OutVals,
2142 SDLoc dl, SelectionDAG &DAG) const {
2144 // CCValAssign - represent the assignment of the return value to a location.
2145 SmallVector<CCValAssign, 16> RVLocs;
2147 // CCState - Info about the registers and stack slots.
2148 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2149 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2151 // Analyze outgoing return values.
2152 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2156 SmallVector<SDValue, 4> RetOps;
2157 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2159 // Copy the result values into the output registers.
2160 for (unsigned i = 0, realRVLocIdx = 0;
2162 ++i, ++realRVLocIdx) {
2163 CCValAssign &VA = RVLocs[i];
2164 assert(VA.isRegLoc() && "Can only return in registers!");
2166 SDValue Arg = OutVals[realRVLocIdx];
2168 switch (VA.getLocInfo()) {
2169 default: llvm_unreachable("Unknown loc info!");
2170 case CCValAssign::Full: break;
2171 case CCValAssign::BCvt:
2172 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2176 if (VA.needsCustom()) {
2177 if (VA.getLocVT() == MVT::v2f64) {
2178 // Extract the first half and return it in two registers.
2179 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2180 DAG.getConstant(0, MVT::i32));
2181 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2182 DAG.getVTList(MVT::i32, MVT::i32), Half);
2184 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2185 Flag = Chain.getValue(1);
2186 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2187 VA = RVLocs[++i]; // skip ahead to next loc
2188 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2189 HalfGPRs.getValue(1), Flag);
2190 Flag = Chain.getValue(1);
2191 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2192 VA = RVLocs[++i]; // skip ahead to next loc
2194 // Extract the 2nd half and fall through to handle it as an f64 value.
2195 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2196 DAG.getConstant(1, MVT::i32));
2198 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2200 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2201 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2202 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2203 Flag = Chain.getValue(1);
2204 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2205 VA = RVLocs[++i]; // skip ahead to next loc
2206 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2209 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2211 // Guarantee that all emitted copies are
2212 // stuck together, avoiding something bad.
2213 Flag = Chain.getValue(1);
2214 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2217 // Update chain and glue.
2220 RetOps.push_back(Flag);
2222 // CPUs which aren't M-class use a special sequence to return from
2223 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2224 // though we use "subs pc, lr, #N").
2226 // M-class CPUs actually use a normal return sequence with a special
2227 // (hardware-provided) value in LR, so the normal code path works.
2228 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2229 !Subtarget->isMClass()) {
2230 if (Subtarget->isThumb1Only())
2231 report_fatal_error("interrupt attribute is not supported in Thumb1");
2232 return LowerInterruptReturn(RetOps, dl, DAG);
2235 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2236 RetOps.data(), RetOps.size());
2239 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2240 if (N->getNumValues() != 1)
2242 if (!N->hasNUsesOfValue(1, 0))
2245 SDValue TCChain = Chain;
2246 SDNode *Copy = *N->use_begin();
2247 if (Copy->getOpcode() == ISD::CopyToReg) {
2248 // If the copy has a glue operand, we conservatively assume it isn't safe to
2249 // perform a tail call.
2250 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2252 TCChain = Copy->getOperand(0);
2253 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2254 SDNode *VMov = Copy;
2255 // f64 returned in a pair of GPRs.
2256 SmallPtrSet<SDNode*, 2> Copies;
2257 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2259 if (UI->getOpcode() != ISD::CopyToReg)
2263 if (Copies.size() > 2)
2266 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2268 SDValue UseChain = UI->getOperand(0);
2269 if (Copies.count(UseChain.getNode()))
2276 } else if (Copy->getOpcode() == ISD::BITCAST) {
2277 // f32 returned in a single GPR.
2278 if (!Copy->hasOneUse())
2280 Copy = *Copy->use_begin();
2281 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2283 TCChain = Copy->getOperand(0);
2288 bool HasRet = false;
2289 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2291 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2292 UI->getOpcode() != ARMISD::INTRET_FLAG)
2304 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2305 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2308 if (!CI->isTailCall())
2311 return !Subtarget->isThumb1Only();
2314 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2315 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2316 // one of the above mentioned nodes. It has to be wrapped because otherwise
2317 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2318 // be used to form addressing mode. These wrapped nodes will be selected
2320 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2321 EVT PtrVT = Op.getValueType();
2322 // FIXME there is no actual debug info here
2324 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2326 if (CP->isMachineConstantPoolEntry())
2327 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2328 CP->getAlignment());
2330 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2331 CP->getAlignment());
2332 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2335 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2336 return MachineJumpTableInfo::EK_Inline;
2339 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2340 SelectionDAG &DAG) const {
2341 MachineFunction &MF = DAG.getMachineFunction();
2342 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2343 unsigned ARMPCLabelIndex = 0;
2345 EVT PtrVT = getPointerTy();
2346 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2347 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2349 if (RelocM == Reloc::Static) {
2350 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2352 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2353 ARMPCLabelIndex = AFI->createPICLabelUId();
2354 ARMConstantPoolValue *CPV =
2355 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2356 ARMCP::CPBlockAddress, PCAdj);
2357 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2359 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2360 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2361 MachinePointerInfo::getConstantPool(),
2362 false, false, false, 0);
2363 if (RelocM == Reloc::Static)
2365 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2366 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2369 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2371 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2372 SelectionDAG &DAG) const {
2374 EVT PtrVT = getPointerTy();
2375 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2376 MachineFunction &MF = DAG.getMachineFunction();
2377 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2378 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2379 ARMConstantPoolValue *CPV =
2380 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2381 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2382 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2383 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2384 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2385 MachinePointerInfo::getConstantPool(),
2386 false, false, false, 0);
2387 SDValue Chain = Argument.getValue(1);
2389 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2390 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2392 // call __tls_get_addr.
2395 Entry.Node = Argument;
2396 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2397 Args.push_back(Entry);
2398 // FIXME: is there useful debug info available here?
2399 TargetLowering::CallLoweringInfo CLI(Chain,
2400 (Type *) Type::getInt32Ty(*DAG.getContext()),
2401 false, false, false, false,
2402 0, CallingConv::C, /*isTailCall=*/false,
2403 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2404 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2405 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2406 return CallResult.first;
2409 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2410 // "local exec" model.
2412 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2414 TLSModel::Model model) const {
2415 const GlobalValue *GV = GA->getGlobal();
2418 SDValue Chain = DAG.getEntryNode();
2419 EVT PtrVT = getPointerTy();
2420 // Get the Thread Pointer
2421 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2423 if (model == TLSModel::InitialExec) {
2424 MachineFunction &MF = DAG.getMachineFunction();
2425 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2426 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2427 // Initial exec model.
2428 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2429 ARMConstantPoolValue *CPV =
2430 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2431 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2433 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2434 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2435 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2436 MachinePointerInfo::getConstantPool(),
2437 false, false, false, 0);
2438 Chain = Offset.getValue(1);
2440 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2441 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2443 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2444 MachinePointerInfo::getConstantPool(),
2445 false, false, false, 0);
2448 assert(model == TLSModel::LocalExec);
2449 ARMConstantPoolValue *CPV =
2450 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2451 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2452 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2453 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2454 MachinePointerInfo::getConstantPool(),
2455 false, false, false, 0);
2458 // The address of the thread local variable is the add of the thread
2459 // pointer with the offset of the variable.
2460 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2464 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2465 // TODO: implement the "local dynamic" model
2466 assert(Subtarget->isTargetELF() &&
2467 "TLS not implemented for non-ELF targets");
2468 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2470 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2473 case TLSModel::GeneralDynamic:
2474 case TLSModel::LocalDynamic:
2475 return LowerToTLSGeneralDynamicModel(GA, DAG);
2476 case TLSModel::InitialExec:
2477 case TLSModel::LocalExec:
2478 return LowerToTLSExecModels(GA, DAG, model);
2480 llvm_unreachable("bogus TLS model");
2483 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2484 SelectionDAG &DAG) const {
2485 EVT PtrVT = getPointerTy();
2487 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2488 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2489 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2490 ARMConstantPoolValue *CPV =
2491 ARMConstantPoolConstant::Create(GV,
2492 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2493 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2494 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2495 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2497 MachinePointerInfo::getConstantPool(),
2498 false, false, false, 0);
2499 SDValue Chain = Result.getValue(1);
2500 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2501 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2503 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2504 MachinePointerInfo::getGOT(),
2505 false, false, false, 0);
2509 // If we have T2 ops, we can materialize the address directly via movt/movw
2510 // pair. This is always cheaper.
2511 if (Subtarget->useMovt()) {
2513 // FIXME: Once remat is capable of dealing with instructions with register
2514 // operands, expand this into two nodes.
2515 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2516 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2518 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2519 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2520 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2521 MachinePointerInfo::getConstantPool(),
2522 false, false, false, 0);
2526 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2527 SelectionDAG &DAG) const {
2528 EVT PtrVT = getPointerTy();
2530 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2531 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2533 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2534 // update ARMFastISel::ARMMaterializeGV.
2535 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2537 // FIXME: Once remat is capable of dealing with instructions with register
2538 // operands, expand this into two nodes.
2539 if (RelocM == Reloc::Static)
2540 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2541 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2543 unsigned Wrapper = (RelocM == Reloc::PIC_)
2544 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2545 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2546 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2547 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2548 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2549 MachinePointerInfo::getGOT(),
2550 false, false, false, 0);
2554 unsigned ARMPCLabelIndex = 0;
2556 if (RelocM == Reloc::Static) {
2557 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2559 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2560 ARMPCLabelIndex = AFI->createPICLabelUId();
2561 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2562 ARMConstantPoolValue *CPV =
2563 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2565 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2567 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2569 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2570 MachinePointerInfo::getConstantPool(),
2571 false, false, false, 0);
2572 SDValue Chain = Result.getValue(1);
2574 if (RelocM == Reloc::PIC_) {
2575 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2576 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2579 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2580 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2581 false, false, false, 0);
2586 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2587 SelectionDAG &DAG) const {
2588 assert(Subtarget->isTargetELF() &&
2589 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2590 MachineFunction &MF = DAG.getMachineFunction();
2591 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2592 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2593 EVT PtrVT = getPointerTy();
2595 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2596 ARMConstantPoolValue *CPV =
2597 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2598 ARMPCLabelIndex, PCAdj);
2599 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2600 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2601 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2602 MachinePointerInfo::getConstantPool(),
2603 false, false, false, 0);
2604 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2605 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2609 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2611 SDValue Val = DAG.getConstant(0, MVT::i32);
2612 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2613 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2614 Op.getOperand(1), Val);
2618 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2620 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2621 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2625 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2626 const ARMSubtarget *Subtarget) const {
2627 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2630 default: return SDValue(); // Don't custom lower most intrinsics.
2631 case Intrinsic::arm_thread_pointer: {
2632 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2633 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2635 case Intrinsic::eh_sjlj_lsda: {
2636 MachineFunction &MF = DAG.getMachineFunction();
2637 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2638 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2639 EVT PtrVT = getPointerTy();
2640 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2642 unsigned PCAdj = (RelocM != Reloc::PIC_)
2643 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2644 ARMConstantPoolValue *CPV =
2645 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2646 ARMCP::CPLSDA, PCAdj);
2647 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2648 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2650 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2651 MachinePointerInfo::getConstantPool(),
2652 false, false, false, 0);
2654 if (RelocM == Reloc::PIC_) {
2655 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2656 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2660 case Intrinsic::arm_neon_vmulls:
2661 case Intrinsic::arm_neon_vmullu: {
2662 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2663 ? ARMISD::VMULLs : ARMISD::VMULLu;
2664 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2665 Op.getOperand(1), Op.getOperand(2));
2670 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2671 const ARMSubtarget *Subtarget) {
2672 // FIXME: handle "fence singlethread" more efficiently.
2674 if (!Subtarget->hasDataBarrier()) {
2675 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2676 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2678 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2679 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2680 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2681 DAG.getConstant(0, MVT::i32));
2684 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2685 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2686 unsigned Domain = ARM_MB::ISH;
2687 if (Subtarget->isMClass()) {
2688 // Only a full system barrier exists in the M-class architectures.
2689 Domain = ARM_MB::SY;
2690 } else if (Subtarget->isSwift() && Ord == Release) {
2691 // Swift happens to implement ISHST barriers in a way that's compatible with
2692 // Release semantics but weaker than ISH so we'd be fools not to use
2693 // it. Beware: other processors probably don't!
2694 Domain = ARM_MB::ISHST;
2697 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2698 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2699 DAG.getConstant(Domain, MVT::i32));
2702 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2703 const ARMSubtarget *Subtarget) {
2704 // ARM pre v5TE and Thumb1 does not have preload instructions.
2705 if (!(Subtarget->isThumb2() ||
2706 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2707 // Just preserve the chain.
2708 return Op.getOperand(0);
2711 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2713 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2714 // ARMv7 with MP extension has PLDW.
2715 return Op.getOperand(0);
2717 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2718 if (Subtarget->isThumb()) {
2720 isRead = ~isRead & 1;
2721 isData = ~isData & 1;
2724 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2725 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2726 DAG.getConstant(isData, MVT::i32));
2729 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2730 MachineFunction &MF = DAG.getMachineFunction();
2731 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2733 // vastart just stores the address of the VarArgsFrameIndex slot into the
2734 // memory location argument.
2736 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2737 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2738 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2739 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2740 MachinePointerInfo(SV), false, false, 0);
2744 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2745 SDValue &Root, SelectionDAG &DAG,
2747 MachineFunction &MF = DAG.getMachineFunction();
2748 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2750 const TargetRegisterClass *RC;
2751 if (AFI->isThumb1OnlyFunction())
2752 RC = &ARM::tGPRRegClass;
2754 RC = &ARM::GPRRegClass;
2756 // Transform the arguments stored in physical registers into virtual ones.
2757 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2758 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2761 if (NextVA.isMemLoc()) {
2762 MachineFrameInfo *MFI = MF.getFrameInfo();
2763 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2765 // Create load node to retrieve arguments from the stack.
2766 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2767 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2768 MachinePointerInfo::getFixedStack(FI),
2769 false, false, false, 0);
2771 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2772 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2775 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2779 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2780 unsigned InRegsParamRecordIdx,
2782 unsigned &ArgRegsSize,
2783 unsigned &ArgRegsSaveSize)
2786 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2787 unsigned RBegin, REnd;
2788 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2789 NumGPRs = REnd - RBegin;
2791 unsigned int firstUnalloced;
2792 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2793 sizeof(GPRArgRegs) /
2794 sizeof(GPRArgRegs[0]));
2795 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2798 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2799 ArgRegsSize = NumGPRs * 4;
2801 // If parameter is split between stack and GPRs...
2802 if (NumGPRs && Align == 8 &&
2803 (ArgRegsSize < ArgSize ||
2804 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2805 // Add padding for part of param recovered from GPRs, so
2806 // its last byte must be at address K*8 - 1.
2807 // We need to do it, since remained (stack) part of parameter has
2808 // stack alignment, and we need to "attach" "GPRs head" without gaps
2811 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2812 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2814 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2816 ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2817 (ArgRegsSize + AFI->getArgRegsSaveSize());
2818 ArgRegsSaveSize = ArgRegsSize + Padding;
2820 // We don't need to extend regs save size for byval parameters if they
2821 // are passed via GPRs only.
2822 ArgRegsSaveSize = ArgRegsSize;
2825 // The remaining GPRs hold either the beginning of variable-argument
2826 // data, or the beginning of an aggregate passed by value (usually
2827 // byval). Either way, we allocate stack slots adjacent to the data
2828 // provided by our caller, and store the unallocated registers there.
2829 // If this is a variadic function, the va_list pointer will begin with
2830 // these values; otherwise, this reassembles a (byval) structure that
2831 // was split between registers and memory.
2832 // Return: The frame index registers were stored into.
2834 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2835 SDLoc dl, SDValue &Chain,
2836 const Value *OrigArg,
2837 unsigned InRegsParamRecordIdx,
2838 unsigned OffsetFromOrigArg,
2841 bool ForceMutable) const {
2843 // Currently, two use-cases possible:
2844 // Case #1. Non var-args function, and we meet first byval parameter.
2845 // Setup first unallocated register as first byval register;
2846 // eat all remained registers
2847 // (these two actions are performed by HandleByVal method).
2848 // Then, here, we initialize stack frame with
2849 // "store-reg" instructions.
2850 // Case #2. Var-args function, that doesn't contain byval parameters.
2851 // The same: eat all remained unallocated registers,
2852 // initialize stack frame.
2854 MachineFunction &MF = DAG.getMachineFunction();
2855 MachineFrameInfo *MFI = MF.getFrameInfo();
2856 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2857 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2858 unsigned RBegin, REnd;
2859 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2860 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2861 firstRegToSaveIndex = RBegin - ARM::R0;
2862 lastRegToSaveIndex = REnd - ARM::R0;
2864 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2865 (GPRArgRegs, array_lengthof(GPRArgRegs));
2866 lastRegToSaveIndex = 4;
2869 unsigned ArgRegsSize, ArgRegsSaveSize;
2870 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2871 ArgRegsSize, ArgRegsSaveSize);
2873 // Store any by-val regs to their spots on the stack so that they may be
2874 // loaded by deferencing the result of formal parameter pointer or va_next.
2875 // Note: once stack area for byval/varargs registers
2876 // was initialized, it can't be initialized again.
2877 if (ArgRegsSaveSize) {
2879 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2882 assert(AFI->getStoredByValParamsPadding() == 0 &&
2883 "The only parameter may be padded.");
2884 AFI->setStoredByValParamsPadding(Padding);
2887 int FrameIndex = MFI->CreateFixedObject(
2889 Padding + ArgOffset,
2891 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2893 SmallVector<SDValue, 4> MemOps;
2894 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2895 ++firstRegToSaveIndex, ++i) {
2896 const TargetRegisterClass *RC;
2897 if (AFI->isThumb1OnlyFunction())
2898 RC = &ARM::tGPRRegClass;
2900 RC = &ARM::GPRRegClass;
2902 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2903 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2905 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2906 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2908 MemOps.push_back(Store);
2909 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2910 DAG.getConstant(4, getPointerTy()));
2913 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2915 if (!MemOps.empty())
2916 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2917 &MemOps[0], MemOps.size());
2920 // This will point to the next argument passed via stack.
2921 return MFI->CreateFixedObject(
2922 4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2925 // Setup stack frame, the va_list pointer will start from.
2927 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2928 SDLoc dl, SDValue &Chain,
2930 bool ForceMutable) const {
2931 MachineFunction &MF = DAG.getMachineFunction();
2932 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2934 // Try to store any remaining integer argument regs
2935 // to their spots on the stack so that they may be loaded by deferencing
2936 // the result of va_next.
2937 // If there is no regs to be stored, just point address after last
2938 // argument passed via stack.
2940 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2941 0, ArgOffset, 0, ForceMutable);
2943 AFI->setVarArgsFrameIndex(FrameIndex);
2947 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2948 CallingConv::ID CallConv, bool isVarArg,
2949 const SmallVectorImpl<ISD::InputArg>
2951 SDLoc dl, SelectionDAG &DAG,
2952 SmallVectorImpl<SDValue> &InVals)
2954 MachineFunction &MF = DAG.getMachineFunction();
2955 MachineFrameInfo *MFI = MF.getFrameInfo();
2957 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2959 // Assign locations to all of the incoming arguments.
2960 SmallVector<CCValAssign, 16> ArgLocs;
2961 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2962 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2963 CCInfo.AnalyzeFormalArguments(Ins,
2964 CCAssignFnForNode(CallConv, /* Return*/ false,
2967 SmallVector<SDValue, 16> ArgValues;
2968 int lastInsIndex = -1;
2970 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2971 unsigned CurArgIdx = 0;
2973 // Initially ArgRegsSaveSize is zero.
2974 // Then we increase this value each time we meet byval parameter.
2975 // We also increase this value in case of varargs function.
2976 AFI->setArgRegsSaveSize(0);
2978 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2979 CCValAssign &VA = ArgLocs[i];
2980 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2981 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2982 // Arguments stored in registers.
2983 if (VA.isRegLoc()) {
2984 EVT RegVT = VA.getLocVT();
2986 if (VA.needsCustom()) {
2987 // f64 and vector types are split up into multiple registers or
2988 // combinations of registers and stack slots.
2989 if (VA.getLocVT() == MVT::v2f64) {
2990 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2992 VA = ArgLocs[++i]; // skip ahead to next loc
2994 if (VA.isMemLoc()) {
2995 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2996 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2997 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2998 MachinePointerInfo::getFixedStack(FI),
2999 false, false, false, 0);
3001 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3004 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3005 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3006 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3007 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3008 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3010 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3013 const TargetRegisterClass *RC;
3015 if (RegVT == MVT::f32)
3016 RC = &ARM::SPRRegClass;
3017 else if (RegVT == MVT::f64)
3018 RC = &ARM::DPRRegClass;
3019 else if (RegVT == MVT::v2f64)
3020 RC = &ARM::QPRRegClass;
3021 else if (RegVT == MVT::i32)
3022 RC = AFI->isThumb1OnlyFunction() ?
3023 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3024 (const TargetRegisterClass*)&ARM::GPRRegClass;
3026 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3028 // Transform the arguments in physical registers into virtual ones.
3029 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3030 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3033 // If this is an 8 or 16-bit value, it is really passed promoted
3034 // to 32 bits. Insert an assert[sz]ext to capture this, then
3035 // truncate to the right size.
3036 switch (VA.getLocInfo()) {
3037 default: llvm_unreachable("Unknown loc info!");
3038 case CCValAssign::Full: break;
3039 case CCValAssign::BCvt:
3040 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3042 case CCValAssign::SExt:
3043 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3044 DAG.getValueType(VA.getValVT()));
3045 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3047 case CCValAssign::ZExt:
3048 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3049 DAG.getValueType(VA.getValVT()));
3050 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3054 InVals.push_back(ArgValue);
3056 } else { // VA.isRegLoc()
3059 assert(VA.isMemLoc());
3060 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3062 int index = ArgLocs[i].getValNo();
3064 // Some Ins[] entries become multiple ArgLoc[] entries.
3065 // Process them only once.
3066 if (index != lastInsIndex)
3068 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3069 // FIXME: For now, all byval parameter objects are marked mutable.
3070 // This can be changed with more analysis.
3071 // In case of tail call optimization mark all arguments mutable.
3072 // Since they could be overwritten by lowering of arguments in case of
3074 if (Flags.isByVal()) {
3075 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3076 int FrameIndex = StoreByValRegs(
3077 CCInfo, DAG, dl, Chain, CurOrigArg,
3079 Ins[VA.getValNo()].PartOffset,
3080 VA.getLocMemOffset(),
3081 Flags.getByValSize(),
3082 true /*force mutable frames*/);
3083 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3084 CCInfo.nextInRegsParam();
3086 unsigned FIOffset = VA.getLocMemOffset() +
3087 AFI->getStoredByValParamsPadding();
3088 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3091 // Create load nodes to retrieve arguments from the stack.
3092 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3093 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3094 MachinePointerInfo::getFixedStack(FI),
3095 false, false, false, 0));
3097 lastInsIndex = index;
3104 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3105 CCInfo.getNextStackOffset());
3110 /// isFloatingPointZero - Return true if this is +0.0.
3111 static bool isFloatingPointZero(SDValue Op) {
3112 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3113 return CFP->getValueAPF().isPosZero();
3114 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3115 // Maybe this has already been legalized into the constant pool?
3116 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3117 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3118 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3119 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3120 return CFP->getValueAPF().isPosZero();
3126 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3127 /// the given operands.
3129 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3130 SDValue &ARMcc, SelectionDAG &DAG,
3132 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3133 unsigned C = RHSC->getZExtValue();
3134 if (!isLegalICmpImmediate(C)) {
3135 // Constant does not fit, try adjusting it by one?
3140 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3141 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3142 RHS = DAG.getConstant(C-1, MVT::i32);
3147 if (C != 0 && isLegalICmpImmediate(C-1)) {
3148 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3149 RHS = DAG.getConstant(C-1, MVT::i32);
3154 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3155 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3156 RHS = DAG.getConstant(C+1, MVT::i32);
3161 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3162 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3163 RHS = DAG.getConstant(C+1, MVT::i32);
3170 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3171 ARMISD::NodeType CompareType;
3174 CompareType = ARMISD::CMP;
3179 CompareType = ARMISD::CMPZ;
3182 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3183 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3186 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3188 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3191 if (!isFloatingPointZero(RHS))
3192 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3194 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3195 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3198 /// duplicateCmp - Glue values can have only one use, so this function
3199 /// duplicates a comparison node.
3201 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3202 unsigned Opc = Cmp.getOpcode();
3204 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3205 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3207 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3208 Cmp = Cmp.getOperand(0);
3209 Opc = Cmp.getOpcode();
3210 if (Opc == ARMISD::CMPFP)
3211 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3213 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3214 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3216 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3219 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3220 SDValue Cond = Op.getOperand(0);
3221 SDValue SelectTrue = Op.getOperand(1);
3222 SDValue SelectFalse = Op.getOperand(2);
3227 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3228 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3230 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3231 const ConstantSDNode *CMOVTrue =
3232 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3233 const ConstantSDNode *CMOVFalse =
3234 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3236 if (CMOVTrue && CMOVFalse) {
3237 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3238 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3242 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3244 False = SelectFalse;
3245 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3250 if (True.getNode() && False.getNode()) {
3251 EVT VT = Op.getValueType();
3252 SDValue ARMcc = Cond.getOperand(2);
3253 SDValue CCR = Cond.getOperand(3);
3254 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3255 assert(True.getValueType() == VT);
3256 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3261 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3262 // undefined bits before doing a full-word comparison with zero.
3263 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3264 DAG.getConstant(1, Cond.getValueType()));
3266 return DAG.getSelectCC(dl, Cond,
3267 DAG.getConstant(0, Cond.getValueType()),
3268 SelectTrue, SelectFalse, ISD::SETNE);
3271 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3272 if (CC == ISD::SETNE)
3274 return ISD::getSetCCSwappedOperands(CC);
3277 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3278 bool &swpCmpOps, bool &swpVselOps) {
3279 // Start by selecting the GE condition code for opcodes that return true for
3281 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3283 CondCode = ARMCC::GE;
3285 // and GT for opcodes that return false for 'equality'.
3286 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3288 CondCode = ARMCC::GT;
3290 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3291 // to swap the compare operands.
3292 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3296 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3297 // If we have an unordered opcode, we need to swap the operands to the VSEL
3298 // instruction (effectively negating the condition).
3300 // This also has the effect of swapping which one of 'less' or 'greater'
3301 // returns true, so we also swap the compare operands. It also switches
3302 // whether we return true for 'equality', so we compensate by picking the
3303 // opposite condition code to our original choice.
3304 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3305 CC == ISD::SETUGT) {
3306 swpCmpOps = !swpCmpOps;
3307 swpVselOps = !swpVselOps;
3308 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3311 // 'ordered' is 'anything but unordered', so use the VS condition code and
3312 // swap the VSEL operands.
3313 if (CC == ISD::SETO) {
3314 CondCode = ARMCC::VS;
3318 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3319 // code and swap the VSEL operands.
3320 if (CC == ISD::SETUNE) {
3321 CondCode = ARMCC::EQ;
3326 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3327 EVT VT = Op.getValueType();
3328 SDValue LHS = Op.getOperand(0);
3329 SDValue RHS = Op.getOperand(1);
3330 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3331 SDValue TrueVal = Op.getOperand(2);
3332 SDValue FalseVal = Op.getOperand(3);
3335 if (LHS.getValueType() == MVT::i32) {
3336 // Try to generate VSEL on ARMv8.
3337 // The VSEL instruction can't use all the usual ARM condition
3338 // codes: it only has two bits to select the condition code, so it's
3339 // constrained to use only GE, GT, VS and EQ.
3341 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3342 // swap the operands of the previous compare instruction (effectively
3343 // inverting the compare condition, swapping 'less' and 'greater') and
3344 // sometimes need to swap the operands to the VSEL (which inverts the
3345 // condition in the sense of firing whenever the previous condition didn't)
3346 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3347 TrueVal.getValueType() == MVT::f64)) {
3348 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3349 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3350 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3351 CC = getInverseCCForVSEL(CC);
3352 std::swap(TrueVal, FalseVal);
3357 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3358 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3359 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3363 ARMCC::CondCodes CondCode, CondCode2;
3364 FPCCToARMCC(CC, CondCode, CondCode2);
3366 // Try to generate VSEL on ARMv8.
3367 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3368 TrueVal.getValueType() == MVT::f64)) {
3369 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3370 // same operands, as follows:
3371 // c = fcmp [ogt, olt, ugt, ult] a, b
3373 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3374 // handled differently than the original code sequence.
3375 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3377 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3378 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3379 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3380 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3383 bool swpCmpOps = false;
3384 bool swpVselOps = false;
3385 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3387 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3388 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3390 std::swap(LHS, RHS);
3392 std::swap(TrueVal, FalseVal);
3396 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3397 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3398 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3399 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3401 if (CondCode2 != ARMCC::AL) {
3402 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3403 // FIXME: Needs another CMP because flag can have but one use.
3404 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3405 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3406 Result, TrueVal, ARMcc2, CCR, Cmp2);
3411 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3412 /// to morph to an integer compare sequence.
3413 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3414 const ARMSubtarget *Subtarget) {
3415 SDNode *N = Op.getNode();
3416 if (!N->hasOneUse())
3417 // Otherwise it requires moving the value from fp to integer registers.
3419 if (!N->getNumValues())
3421 EVT VT = Op.getValueType();
3422 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3423 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3424 // vmrs are very slow, e.g. cortex-a8.
3427 if (isFloatingPointZero(Op)) {
3431 return ISD::isNormalLoad(N);
3434 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3435 if (isFloatingPointZero(Op))
3436 return DAG.getConstant(0, MVT::i32);
3438 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3439 return DAG.getLoad(MVT::i32, SDLoc(Op),
3440 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3441 Ld->isVolatile(), Ld->isNonTemporal(),
3442 Ld->isInvariant(), Ld->getAlignment());
3444 llvm_unreachable("Unknown VFP cmp argument!");
3447 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3448 SDValue &RetVal1, SDValue &RetVal2) {
3449 if (isFloatingPointZero(Op)) {
3450 RetVal1 = DAG.getConstant(0, MVT::i32);
3451 RetVal2 = DAG.getConstant(0, MVT::i32);
3455 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3456 SDValue Ptr = Ld->getBasePtr();
3457 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3458 Ld->getChain(), Ptr,
3459 Ld->getPointerInfo(),
3460 Ld->isVolatile(), Ld->isNonTemporal(),
3461 Ld->isInvariant(), Ld->getAlignment());
3463 EVT PtrType = Ptr.getValueType();
3464 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3465 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3466 PtrType, Ptr, DAG.getConstant(4, PtrType));
3467 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3468 Ld->getChain(), NewPtr,
3469 Ld->getPointerInfo().getWithOffset(4),
3470 Ld->isVolatile(), Ld->isNonTemporal(),
3471 Ld->isInvariant(), NewAlign);
3475 llvm_unreachable("Unknown VFP cmp argument!");
3478 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3479 /// f32 and even f64 comparisons to integer ones.
3481 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3482 SDValue Chain = Op.getOperand(0);
3483 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3484 SDValue LHS = Op.getOperand(2);
3485 SDValue RHS = Op.getOperand(3);
3486 SDValue Dest = Op.getOperand(4);
3489 bool LHSSeenZero = false;
3490 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3491 bool RHSSeenZero = false;
3492 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3493 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3494 // If unsafe fp math optimization is enabled and there are no other uses of
3495 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3496 // to an integer comparison.
3497 if (CC == ISD::SETOEQ)
3499 else if (CC == ISD::SETUNE)
3502 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3504 if (LHS.getValueType() == MVT::f32) {
3505 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3506 bitcastf32Toi32(LHS, DAG), Mask);
3507 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3508 bitcastf32Toi32(RHS, DAG), Mask);
3509 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3510 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3511 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3512 Chain, Dest, ARMcc, CCR, Cmp);
3517 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3518 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3519 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3520 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3521 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3522 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3523 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3524 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3525 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3531 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3532 SDValue Chain = Op.getOperand(0);
3533 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3534 SDValue LHS = Op.getOperand(2);
3535 SDValue RHS = Op.getOperand(3);
3536 SDValue Dest = Op.getOperand(4);
3539 if (LHS.getValueType() == MVT::i32) {
3541 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3542 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3543 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3544 Chain, Dest, ARMcc, CCR, Cmp);
3547 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3549 if (getTargetMachine().Options.UnsafeFPMath &&
3550 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3551 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3552 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3553 if (Result.getNode())
3557 ARMCC::CondCodes CondCode, CondCode2;
3558 FPCCToARMCC(CC, CondCode, CondCode2);
3560 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3561 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3562 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3563 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3564 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3565 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3566 if (CondCode2 != ARMCC::AL) {
3567 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3568 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3569 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3574 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3575 SDValue Chain = Op.getOperand(0);
3576 SDValue Table = Op.getOperand(1);
3577 SDValue Index = Op.getOperand(2);
3580 EVT PTy = getPointerTy();
3581 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3582 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3583 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3584 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3585 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3586 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3587 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3588 if (Subtarget->isThumb2()) {
3589 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3590 // which does another jump to the destination. This also makes it easier
3591 // to translate it to TBB / TBH later.
3592 // FIXME: This might not work if the function is extremely large.
3593 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3594 Addr, Op.getOperand(2), JTI, UId);
3596 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3597 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3598 MachinePointerInfo::getJumpTable(),
3599 false, false, false, 0);
3600 Chain = Addr.getValue(1);
3601 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3602 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3604 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3605 MachinePointerInfo::getJumpTable(),
3606 false, false, false, 0);
3607 Chain = Addr.getValue(1);
3608 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3612 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3613 EVT VT = Op.getValueType();
3616 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3617 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3619 return DAG.UnrollVectorOp(Op.getNode());
3622 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3623 "Invalid type for custom lowering!");
3624 if (VT != MVT::v4i16)
3625 return DAG.UnrollVectorOp(Op.getNode());
3627 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3628 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3631 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3632 EVT VT = Op.getValueType();
3634 return LowerVectorFP_TO_INT(Op, DAG);
3639 switch (Op.getOpcode()) {
3640 default: llvm_unreachable("Invalid opcode!");
3641 case ISD::FP_TO_SINT:
3642 Opc = ARMISD::FTOSI;
3644 case ISD::FP_TO_UINT:
3645 Opc = ARMISD::FTOUI;
3648 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3649 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3652 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3653 EVT VT = Op.getValueType();
3656 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3657 if (VT.getVectorElementType() == MVT::f32)
3659 return DAG.UnrollVectorOp(Op.getNode());
3662 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3663 "Invalid type for custom lowering!");
3664 if (VT != MVT::v4f32)
3665 return DAG.UnrollVectorOp(Op.getNode());
3669 switch (Op.getOpcode()) {
3670 default: llvm_unreachable("Invalid opcode!");
3671 case ISD::SINT_TO_FP:
3672 CastOpc = ISD::SIGN_EXTEND;
3673 Opc = ISD::SINT_TO_FP;
3675 case ISD::UINT_TO_FP:
3676 CastOpc = ISD::ZERO_EXTEND;
3677 Opc = ISD::UINT_TO_FP;
3681 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3682 return DAG.getNode(Opc, dl, VT, Op);
3685 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3686 EVT VT = Op.getValueType();
3688 return LowerVectorINT_TO_FP(Op, DAG);
3693 switch (Op.getOpcode()) {
3694 default: llvm_unreachable("Invalid opcode!");
3695 case ISD::SINT_TO_FP:
3696 Opc = ARMISD::SITOF;
3698 case ISD::UINT_TO_FP:
3699 Opc = ARMISD::UITOF;
3703 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3704 return DAG.getNode(Opc, dl, VT, Op);
3707 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3708 // Implement fcopysign with a fabs and a conditional fneg.
3709 SDValue Tmp0 = Op.getOperand(0);
3710 SDValue Tmp1 = Op.getOperand(1);
3712 EVT VT = Op.getValueType();
3713 EVT SrcVT = Tmp1.getValueType();
3714 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3715 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3716 bool UseNEON = !InGPR && Subtarget->hasNEON();
3719 // Use VBSL to copy the sign bit.
3720 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3721 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3722 DAG.getTargetConstant(EncodedVal, MVT::i32));
3723 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3725 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3726 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3727 DAG.getConstant(32, MVT::i32));
3728 else /*if (VT == MVT::f32)*/
3729 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3730 if (SrcVT == MVT::f32) {
3731 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3733 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3734 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3735 DAG.getConstant(32, MVT::i32));
3736 } else if (VT == MVT::f32)
3737 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3738 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3739 DAG.getConstant(32, MVT::i32));
3740 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3741 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3743 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3745 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3746 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3747 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3749 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3750 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3751 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3752 if (VT == MVT::f32) {
3753 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3754 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3755 DAG.getConstant(0, MVT::i32));
3757 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3763 // Bitcast operand 1 to i32.
3764 if (SrcVT == MVT::f64)
3765 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3766 &Tmp1, 1).getValue(1);
3767 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3769 // Or in the signbit with integer operations.
3770 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3771 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3772 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3773 if (VT == MVT::f32) {
3774 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3775 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3776 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3777 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3780 // f64: Or the high part with signbit and then combine two parts.
3781 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3783 SDValue Lo = Tmp0.getValue(0);
3784 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3785 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3786 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3789 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3790 MachineFunction &MF = DAG.getMachineFunction();
3791 MachineFrameInfo *MFI = MF.getFrameInfo();
3792 MFI->setReturnAddressIsTaken(true);
3794 EVT VT = Op.getValueType();
3796 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3798 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3799 SDValue Offset = DAG.getConstant(4, MVT::i32);
3800 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3801 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3802 MachinePointerInfo(), false, false, false, 0);
3805 // Return LR, which contains the return address. Mark it an implicit live-in.
3806 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3807 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3810 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3811 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3812 MFI->setFrameAddressIsTaken(true);
3814 EVT VT = Op.getValueType();
3815 SDLoc dl(Op); // FIXME probably not meaningful
3816 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3817 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3818 ? ARM::R7 : ARM::R11;
3819 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3821 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3822 MachinePointerInfo(),
3823 false, false, false, 0);
3827 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3828 /// and size(DestVec) > 128-bits.
3829 /// This is achieved by doing the one extension from the SrcVec, splitting the
3830 /// result, extending these parts, and then concatenating these into the
3832 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3833 SDValue Op = N->getOperand(0);
3834 EVT SrcVT = Op.getValueType();
3835 EVT DestVT = N->getValueType(0);
3837 assert(DestVT.getSizeInBits() > 128 &&
3838 "Custom sext/zext expansion needs >128-bit vector.");
3839 // If this is a normal length extension, use the default expansion.
3840 if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3841 SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3845 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3846 unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3847 unsigned NumElts = SrcVT.getVectorNumElements();
3848 LLVMContext &Ctx = *DAG.getContext();
3849 SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3851 EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3853 EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3855 EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3858 Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3859 SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3860 DAG.getIntPtrConstant(0));
3861 SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3862 DAG.getIntPtrConstant(NumElts/2));
3863 ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3864 ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3865 return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3868 /// ExpandBITCAST - If the target supports VFP, this function is called to
3869 /// expand a bit convert where either the source or destination type is i64 to
3870 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3871 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3872 /// vectors), since the legalizer won't know what to do with that.
3873 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3874 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3876 SDValue Op = N->getOperand(0);
3878 // This function is only supposed to be called for i64 types, either as the
3879 // source or destination of the bit convert.
3880 EVT SrcVT = Op.getValueType();
3881 EVT DstVT = N->getValueType(0);
3882 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3883 "ExpandBITCAST called for non-i64 type");
3885 // Turn i64->f64 into VMOVDRR.
3886 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3887 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3888 DAG.getConstant(0, MVT::i32));
3889 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3890 DAG.getConstant(1, MVT::i32));
3891 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3892 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3895 // Turn f64->i64 into VMOVRRD.
3896 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3897 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3898 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3899 // Merge the pieces into a single i64 value.
3900 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3906 /// getZeroVector - Returns a vector of specified type with all zero elements.
3907 /// Zero vectors are used to represent vector negation and in those cases
3908 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3909 /// not support i64 elements, so sometimes the zero vectors will need to be
3910 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3912 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3913 assert(VT.isVector() && "Expected a vector type");
3914 // The canonical modified immediate encoding of a zero vector is....0!
3915 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3916 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3917 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3918 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3921 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3922 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3923 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3924 SelectionDAG &DAG) const {
3925 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3926 EVT VT = Op.getValueType();
3927 unsigned VTBits = VT.getSizeInBits();
3929 SDValue ShOpLo = Op.getOperand(0);
3930 SDValue ShOpHi = Op.getOperand(1);
3931 SDValue ShAmt = Op.getOperand(2);
3933 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3935 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3937 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3938 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3939 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3940 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3941 DAG.getConstant(VTBits, MVT::i32));
3942 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3943 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3944 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3946 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3947 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3949 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3950 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3953 SDValue Ops[2] = { Lo, Hi };
3954 return DAG.getMergeValues(Ops, 2, dl);
3957 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3958 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3959 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3960 SelectionDAG &DAG) const {
3961 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3962 EVT VT = Op.getValueType();
3963 unsigned VTBits = VT.getSizeInBits();
3965 SDValue ShOpLo = Op.getOperand(0);
3966 SDValue ShOpHi = Op.getOperand(1);
3967 SDValue ShAmt = Op.getOperand(2);
3970 assert(Op.getOpcode() == ISD::SHL_PARTS);
3971 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3972 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3973 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3974 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3975 DAG.getConstant(VTBits, MVT::i32));
3976 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3977 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3979 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3980 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3981 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3983 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3984 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3987 SDValue Ops[2] = { Lo, Hi };
3988 return DAG.getMergeValues(Ops, 2, dl);
3991 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3992 SelectionDAG &DAG) const {
3993 // The rounding mode is in bits 23:22 of the FPSCR.
3994 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3995 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3996 // so that the shift + and get folded into a bitfield extract.
3998 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3999 DAG.getConstant(Intrinsic::arm_get_fpscr,
4001 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4002 DAG.getConstant(1U << 22, MVT::i32));
4003 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4004 DAG.getConstant(22, MVT::i32));
4005 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4006 DAG.getConstant(3, MVT::i32));
4009 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4010 const ARMSubtarget *ST) {
4011 EVT VT = N->getValueType(0);
4014 if (!ST->hasV6T2Ops())
4017 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4018 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4021 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4022 /// for each 16-bit element from operand, repeated. The basic idea is to
4023 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4025 /// Trace for v4i16:
4026 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4027 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4028 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4029 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4030 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4031 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4032 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4033 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4034 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4035 EVT VT = N->getValueType(0);
4038 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4039 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4040 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4041 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4042 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4043 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4046 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4047 /// bit-count for each 16-bit element from the operand. We need slightly
4048 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4049 /// 64/128-bit registers.
4051 /// Trace for v4i16:
4052 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4053 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4054 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4055 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4056 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4057 EVT VT = N->getValueType(0);
4060 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4061 if (VT.is64BitVector()) {
4062 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4063 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4064 DAG.getIntPtrConstant(0));
4066 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4067 BitCounts, DAG.getIntPtrConstant(0));
4068 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4072 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4073 /// bit-count for each 32-bit element from the operand. The idea here is
4074 /// to split the vector into 16-bit elements, leverage the 16-bit count
4075 /// routine, and then combine the results.
4077 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4078 /// input = [v0 v1 ] (vi: 32-bit elements)
4079 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4080 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4081 /// vrev: N0 = [k1 k0 k3 k2 ]
4083 /// N1 =+[k1 k0 k3 k2 ]
4085 /// N2 =+[k1 k3 k0 k2 ]
4087 /// Extended =+[k1 k3 k0 k2 ]
4089 /// Extracted=+[k1 k3 ]
4091 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4092 EVT VT = N->getValueType(0);
4095 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4097 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4098 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4099 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4100 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4101 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4103 if (VT.is64BitVector()) {
4104 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4105 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4106 DAG.getIntPtrConstant(0));
4108 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4109 DAG.getIntPtrConstant(0));
4110 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4114 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4115 const ARMSubtarget *ST) {
4116 EVT VT = N->getValueType(0);
4118 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4119 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4120 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4121 "Unexpected type for custom ctpop lowering");
4123 if (VT.getVectorElementType() == MVT::i32)
4124 return lowerCTPOP32BitElements(N, DAG);
4126 return lowerCTPOP16BitElements(N, DAG);
4129 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4130 const ARMSubtarget *ST) {
4131 EVT VT = N->getValueType(0);
4137 // Lower vector shifts on NEON to use VSHL.
4138 assert(ST->hasNEON() && "unexpected vector shift");
4140 // Left shifts translate directly to the vshiftu intrinsic.
4141 if (N->getOpcode() == ISD::SHL)
4142 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4143 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4144 N->getOperand(0), N->getOperand(1));
4146 assert((N->getOpcode() == ISD::SRA ||
4147 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4149 // NEON uses the same intrinsics for both left and right shifts. For
4150 // right shifts, the shift amounts are negative, so negate the vector of
4152 EVT ShiftVT = N->getOperand(1).getValueType();
4153 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4154 getZeroVector(ShiftVT, DAG, dl),
4156 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4157 Intrinsic::arm_neon_vshifts :
4158 Intrinsic::arm_neon_vshiftu);
4159 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4160 DAG.getConstant(vshiftInt, MVT::i32),
4161 N->getOperand(0), NegatedCount);
4164 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4165 const ARMSubtarget *ST) {
4166 EVT VT = N->getValueType(0);
4169 // We can get here for a node like i32 = ISD::SHL i32, i64
4173 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4174 "Unknown shift to lower!");
4176 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4177 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4178 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4181 // If we are in thumb mode, we don't have RRX.
4182 if (ST->isThumb1Only()) return SDValue();
4184 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4185 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4186 DAG.getConstant(0, MVT::i32));
4187 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4188 DAG.getConstant(1, MVT::i32));
4190 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4191 // captures the result into a carry flag.
4192 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4193 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4195 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4196 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4198 // Merge the pieces into a single i64 value.
4199 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4202 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4203 SDValue TmpOp0, TmpOp1;
4204 bool Invert = false;
4208 SDValue Op0 = Op.getOperand(0);
4209 SDValue Op1 = Op.getOperand(1);
4210 SDValue CC = Op.getOperand(2);
4211 EVT VT = Op.getValueType();
4212 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4215 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4216 switch (SetCCOpcode) {
4217 default: llvm_unreachable("Illegal FP comparison");
4219 case ISD::SETNE: Invert = true; // Fallthrough
4221 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4223 case ISD::SETLT: Swap = true; // Fallthrough
4225 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4227 case ISD::SETLE: Swap = true; // Fallthrough
4229 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4230 case ISD::SETUGE: Swap = true; // Fallthrough
4231 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4232 case ISD::SETUGT: Swap = true; // Fallthrough
4233 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4234 case ISD::SETUEQ: Invert = true; // Fallthrough
4236 // Expand this to (OLT | OGT).
4240 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4241 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4243 case ISD::SETUO: Invert = true; // Fallthrough
4245 // Expand this to (OLT | OGE).
4249 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4250 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4254 // Integer comparisons.
4255 switch (SetCCOpcode) {
4256 default: llvm_unreachable("Illegal integer comparison");
4257 case ISD::SETNE: Invert = true;
4258 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4259 case ISD::SETLT: Swap = true;
4260 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4261 case ISD::SETLE: Swap = true;
4262 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4263 case ISD::SETULT: Swap = true;
4264 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4265 case ISD::SETULE: Swap = true;
4266 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4269 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4270 if (Opc == ARMISD::VCEQ) {
4273 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4275 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4278 // Ignore bitconvert.
4279 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4280 AndOp = AndOp.getOperand(0);
4282 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4284 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4285 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4292 std::swap(Op0, Op1);
4294 // If one of the operands is a constant vector zero, attempt to fold the
4295 // comparison to a specialized compare-against-zero form.
4297 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4299 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4300 if (Opc == ARMISD::VCGE)
4301 Opc = ARMISD::VCLEZ;
4302 else if (Opc == ARMISD::VCGT)
4303 Opc = ARMISD::VCLTZ;
4308 if (SingleOp.getNode()) {
4311 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4313 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4315 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4317 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4319 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4321 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4324 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4328 Result = DAG.getNOT(dl, Result, VT);
4333 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4334 /// valid vector constant for a NEON instruction with a "modified immediate"
4335 /// operand (e.g., VMOV). If so, return the encoded value.
4336 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4337 unsigned SplatBitSize, SelectionDAG &DAG,
4338 EVT &VT, bool is128Bits, NEONModImmType type) {
4339 unsigned OpCmode, Imm;
4341 // SplatBitSize is set to the smallest size that splats the vector, so a
4342 // zero vector will always have SplatBitSize == 8. However, NEON modified
4343 // immediate instructions others than VMOV do not support the 8-bit encoding
4344 // of a zero vector, and the default encoding of zero is supposed to be the
4349 switch (SplatBitSize) {
4351 if (type != VMOVModImm)
4353 // Any 1-byte value is OK. Op=0, Cmode=1110.
4354 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4357 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4361 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4362 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4363 if ((SplatBits & ~0xff) == 0) {
4364 // Value = 0x00nn: Op=x, Cmode=100x.
4369 if ((SplatBits & ~0xff00) == 0) {
4370 // Value = 0xnn00: Op=x, Cmode=101x.
4372 Imm = SplatBits >> 8;
4378 // NEON's 32-bit VMOV supports splat values where:
4379 // * only one byte is nonzero, or
4380 // * the least significant byte is 0xff and the second byte is nonzero, or
4381 // * the least significant 2 bytes are 0xff and the third is nonzero.
4382 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4383 if ((SplatBits & ~0xff) == 0) {
4384 // Value = 0x000000nn: Op=x, Cmode=000x.
4389 if ((SplatBits & ~0xff00) == 0) {
4390 // Value = 0x0000nn00: Op=x, Cmode=001x.
4392 Imm = SplatBits >> 8;
4395 if ((SplatBits & ~0xff0000) == 0) {
4396 // Value = 0x00nn0000: Op=x, Cmode=010x.
4398 Imm = SplatBits >> 16;
4401 if ((SplatBits & ~0xff000000) == 0) {
4402 // Value = 0xnn000000: Op=x, Cmode=011x.
4404 Imm = SplatBits >> 24;
4408 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4409 if (type == OtherModImm) return SDValue();
4411 if ((SplatBits & ~0xffff) == 0 &&
4412 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4413 // Value = 0x0000nnff: Op=x, Cmode=1100.
4415 Imm = SplatBits >> 8;
4420 if ((SplatBits & ~0xffffff) == 0 &&
4421 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4422 // Value = 0x00nnffff: Op=x, Cmode=1101.
4424 Imm = SplatBits >> 16;
4425 SplatBits |= 0xffff;
4429 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4430 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4431 // VMOV.I32. A (very) minor optimization would be to replicate the value
4432 // and fall through here to test for a valid 64-bit splat. But, then the
4433 // caller would also need to check and handle the change in size.
4437 if (type != VMOVModImm)
4439 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4440 uint64_t BitMask = 0xff;
4442 unsigned ImmMask = 1;
4444 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4445 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4448 } else if ((SplatBits & BitMask) != 0) {
4454 // Op=1, Cmode=1110.
4457 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4462 llvm_unreachable("unexpected size for isNEONModifiedImm");
4465 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4466 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4469 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4470 const ARMSubtarget *ST) const {
4474 bool IsDouble = Op.getValueType() == MVT::f64;
4475 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4477 // Try splatting with a VMOV.f32...
4478 APFloat FPVal = CFP->getValueAPF();
4479 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4482 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4483 // We have code in place to select a valid ConstantFP already, no need to
4488 // It's a float and we are trying to use NEON operations where
4489 // possible. Lower it to a splat followed by an extract.
4491 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4492 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4494 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4495 DAG.getConstant(0, MVT::i32));
4498 // The rest of our options are NEON only, make sure that's allowed before
4500 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4504 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4506 // It wouldn't really be worth bothering for doubles except for one very
4507 // important value, which does happen to match: 0.0. So make sure we don't do
4509 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4512 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4513 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4515 if (NewVal != SDValue()) {
4517 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4520 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4522 // It's a float: cast and extract a vector element.
4523 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4525 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4526 DAG.getConstant(0, MVT::i32));
4529 // Finally, try a VMVN.i32
4530 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4532 if (NewVal != SDValue()) {
4534 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4537 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4539 // It's a float: cast and extract a vector element.
4540 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4542 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4543 DAG.getConstant(0, MVT::i32));
4549 // check if an VEXT instruction can handle the shuffle mask when the
4550 // vector sources of the shuffle are the same.
4551 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4552 unsigned NumElts = VT.getVectorNumElements();
4554 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4560 // If this is a VEXT shuffle, the immediate value is the index of the first
4561 // element. The other shuffle indices must be the successive elements after
4563 unsigned ExpectedElt = Imm;
4564 for (unsigned i = 1; i < NumElts; ++i) {
4565 // Increment the expected index. If it wraps around, just follow it
4566 // back to index zero and keep going.
4568 if (ExpectedElt == NumElts)
4571 if (M[i] < 0) continue; // ignore UNDEF indices
4572 if (ExpectedElt != static_cast<unsigned>(M[i]))
4580 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4581 bool &ReverseVEXT, unsigned &Imm) {
4582 unsigned NumElts = VT.getVectorNumElements();
4583 ReverseVEXT = false;
4585 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4591 // If this is a VEXT shuffle, the immediate value is the index of the first
4592 // element. The other shuffle indices must be the successive elements after
4594 unsigned ExpectedElt = Imm;
4595 for (unsigned i = 1; i < NumElts; ++i) {
4596 // Increment the expected index. If it wraps around, it may still be
4597 // a VEXT but the source vectors must be swapped.
4599 if (ExpectedElt == NumElts * 2) {
4604 if (M[i] < 0) continue; // ignore UNDEF indices
4605 if (ExpectedElt != static_cast<unsigned>(M[i]))
4609 // Adjust the index value if the source operands will be swapped.
4616 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4617 /// instruction with the specified blocksize. (The order of the elements
4618 /// within each block of the vector is reversed.)
4619 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4620 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4621 "Only possible block sizes for VREV are: 16, 32, 64");
4623 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4627 unsigned NumElts = VT.getVectorNumElements();
4628 unsigned BlockElts = M[0] + 1;
4629 // If the first shuffle index is UNDEF, be optimistic.
4631 BlockElts = BlockSize / EltSz;
4633 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4636 for (unsigned i = 0; i < NumElts; ++i) {
4637 if (M[i] < 0) continue; // ignore UNDEF indices
4638 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4645 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4646 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4647 // range, then 0 is placed into the resulting vector. So pretty much any mask
4648 // of 8 elements can work here.
4649 return VT == MVT::v8i8 && M.size() == 8;
4652 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4653 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4657 unsigned NumElts = VT.getVectorNumElements();
4658 WhichResult = (M[0] == 0 ? 0 : 1);
4659 for (unsigned i = 0; i < NumElts; i += 2) {
4660 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4661 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4667 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4668 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4669 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4670 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4671 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4675 unsigned NumElts = VT.getVectorNumElements();
4676 WhichResult = (M[0] == 0 ? 0 : 1);
4677 for (unsigned i = 0; i < NumElts; i += 2) {
4678 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4679 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4685 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4686 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4690 unsigned NumElts = VT.getVectorNumElements();
4691 WhichResult = (M[0] == 0 ? 0 : 1);
4692 for (unsigned i = 0; i != NumElts; ++i) {
4693 if (M[i] < 0) continue; // ignore UNDEF indices
4694 if ((unsigned) M[i] != 2 * i + WhichResult)
4698 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4699 if (VT.is64BitVector() && EltSz == 32)
4705 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4706 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4707 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4708 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4709 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4713 unsigned Half = VT.getVectorNumElements() / 2;
4714 WhichResult = (M[0] == 0 ? 0 : 1);
4715 for (unsigned j = 0; j != 2; ++j) {
4716 unsigned Idx = WhichResult;
4717 for (unsigned i = 0; i != Half; ++i) {
4718 int MIdx = M[i + j * Half];
4719 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4725 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4726 if (VT.is64BitVector() && EltSz == 32)
4732 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4733 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4737 unsigned NumElts = VT.getVectorNumElements();
4738 WhichResult = (M[0] == 0 ? 0 : 1);
4739 unsigned Idx = WhichResult * NumElts / 2;
4740 for (unsigned i = 0; i != NumElts; i += 2) {
4741 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4742 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4747 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4748 if (VT.is64BitVector() && EltSz == 32)
4754 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4755 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4756 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4757 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4758 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4762 unsigned NumElts = VT.getVectorNumElements();
4763 WhichResult = (M[0] == 0 ? 0 : 1);
4764 unsigned Idx = WhichResult * NumElts / 2;
4765 for (unsigned i = 0; i != NumElts; i += 2) {
4766 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4767 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4772 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4773 if (VT.is64BitVector() && EltSz == 32)
4779 /// \return true if this is a reverse operation on an vector.
4780 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4781 unsigned NumElts = VT.getVectorNumElements();
4782 // Make sure the mask has the right size.
4783 if (NumElts != M.size())
4786 // Look for <15, ..., 3, -1, 1, 0>.
4787 for (unsigned i = 0; i != NumElts; ++i)
4788 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4794 // If N is an integer constant that can be moved into a register in one
4795 // instruction, return an SDValue of such a constant (will become a MOV
4796 // instruction). Otherwise return null.
4797 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4798 const ARMSubtarget *ST, SDLoc dl) {
4800 if (!isa<ConstantSDNode>(N))
4802 Val = cast<ConstantSDNode>(N)->getZExtValue();
4804 if (ST->isThumb1Only()) {
4805 if (Val <= 255 || ~Val <= 255)
4806 return DAG.getConstant(Val, MVT::i32);
4808 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4809 return DAG.getConstant(Val, MVT::i32);
4814 // If this is a case we can't handle, return null and let the default
4815 // expansion code take care of it.
4816 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4817 const ARMSubtarget *ST) const {
4818 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4820 EVT VT = Op.getValueType();
4822 APInt SplatBits, SplatUndef;
4823 unsigned SplatBitSize;
4825 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4826 if (SplatBitSize <= 64) {
4827 // Check if an immediate VMOV works.
4829 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4830 SplatUndef.getZExtValue(), SplatBitSize,
4831 DAG, VmovVT, VT.is128BitVector(),
4833 if (Val.getNode()) {
4834 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4835 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4838 // Try an immediate VMVN.
4839 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4840 Val = isNEONModifiedImm(NegatedImm,
4841 SplatUndef.getZExtValue(), SplatBitSize,
4842 DAG, VmovVT, VT.is128BitVector(),
4844 if (Val.getNode()) {
4845 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4846 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4849 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4850 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4851 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4853 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4854 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4860 // Scan through the operands to see if only one value is used.
4862 // As an optimisation, even if more than one value is used it may be more
4863 // profitable to splat with one value then change some lanes.
4865 // Heuristically we decide to do this if the vector has a "dominant" value,
4866 // defined as splatted to more than half of the lanes.
4867 unsigned NumElts = VT.getVectorNumElements();
4868 bool isOnlyLowElement = true;
4869 bool usesOnlyOneValue = true;
4870 bool hasDominantValue = false;
4871 bool isConstant = true;
4873 // Map of the number of times a particular SDValue appears in the
4875 DenseMap<SDValue, unsigned> ValueCounts;
4877 for (unsigned i = 0; i < NumElts; ++i) {
4878 SDValue V = Op.getOperand(i);
4879 if (V.getOpcode() == ISD::UNDEF)
4882 isOnlyLowElement = false;
4883 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4886 ValueCounts.insert(std::make_pair(V, 0));
4887 unsigned &Count = ValueCounts[V];
4889 // Is this value dominant? (takes up more than half of the lanes)
4890 if (++Count > (NumElts / 2)) {
4891 hasDominantValue = true;
4895 if (ValueCounts.size() != 1)
4896 usesOnlyOneValue = false;
4897 if (!Value.getNode() && ValueCounts.size() > 0)
4898 Value = ValueCounts.begin()->first;
4900 if (ValueCounts.size() == 0)
4901 return DAG.getUNDEF(VT);
4903 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4904 // Keep going if we are hitting this case.
4905 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4906 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4908 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4910 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4911 // i32 and try again.
4912 if (hasDominantValue && EltSize <= 32) {
4916 // If we are VDUPing a value that comes directly from a vector, that will
4917 // cause an unnecessary move to and from a GPR, where instead we could
4918 // just use VDUPLANE. We can only do this if the lane being extracted
4919 // is at a constant index, as the VDUP from lane instructions only have
4920 // constant-index forms.
4921 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4922 isa<ConstantSDNode>(Value->getOperand(1))) {
4923 // We need to create a new undef vector to use for the VDUPLANE if the
4924 // size of the vector from which we get the value is different than the
4925 // size of the vector that we need to create. We will insert the element
4926 // such that the register coalescer will remove unnecessary copies.
4927 if (VT != Value->getOperand(0).getValueType()) {
4928 ConstantSDNode *constIndex;
4929 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4930 assert(constIndex && "The index is not a constant!");
4931 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4932 VT.getVectorNumElements();
4933 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4934 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4935 Value, DAG.getConstant(index, MVT::i32)),
4936 DAG.getConstant(index, MVT::i32));
4938 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4939 Value->getOperand(0), Value->getOperand(1));
4941 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4943 if (!usesOnlyOneValue) {
4944 // The dominant value was splatted as 'N', but we now have to insert
4945 // all differing elements.
4946 for (unsigned I = 0; I < NumElts; ++I) {
4947 if (Op.getOperand(I) == Value)
4949 SmallVector<SDValue, 3> Ops;
4951 Ops.push_back(Op.getOperand(I));
4952 Ops.push_back(DAG.getConstant(I, MVT::i32));
4953 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4958 if (VT.getVectorElementType().isFloatingPoint()) {
4959 SmallVector<SDValue, 8> Ops;
4960 for (unsigned i = 0; i < NumElts; ++i)
4961 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4963 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4964 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4965 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4967 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4969 if (usesOnlyOneValue) {
4970 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4971 if (isConstant && Val.getNode())
4972 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4976 // If all elements are constants and the case above didn't get hit, fall back
4977 // to the default expansion, which will generate a load from the constant
4982 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4984 SDValue shuffle = ReconstructShuffle(Op, DAG);
4985 if (shuffle != SDValue())
4989 // Vectors with 32- or 64-bit elements can be built by directly assigning
4990 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4991 // will be legalized.
4992 if (EltSize >= 32) {
4993 // Do the expansion with floating-point types, since that is what the VFP
4994 // registers are defined to use, and since i64 is not legal.
4995 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4996 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4997 SmallVector<SDValue, 8> Ops;
4998 for (unsigned i = 0; i < NumElts; ++i)
4999 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5000 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5001 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5004 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5005 // know the default expansion would otherwise fall back on something even
5006 // worse. For a vector with one or two non-undef values, that's
5007 // scalar_to_vector for the elements followed by a shuffle (provided the
5008 // shuffle is valid for the target) and materialization element by element
5009 // on the stack followed by a load for everything else.
5010 if (!isConstant && !usesOnlyOneValue) {
5011 SDValue Vec = DAG.getUNDEF(VT);
5012 for (unsigned i = 0 ; i < NumElts; ++i) {
5013 SDValue V = Op.getOperand(i);
5014 if (V.getOpcode() == ISD::UNDEF)
5016 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5017 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5025 // Gather data to see if the operation can be modelled as a
5026 // shuffle in combination with VEXTs.
5027 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5028 SelectionDAG &DAG) const {
5030 EVT VT = Op.getValueType();
5031 unsigned NumElts = VT.getVectorNumElements();
5033 SmallVector<SDValue, 2> SourceVecs;
5034 SmallVector<unsigned, 2> MinElts;
5035 SmallVector<unsigned, 2> MaxElts;
5037 for (unsigned i = 0; i < NumElts; ++i) {
5038 SDValue V = Op.getOperand(i);
5039 if (V.getOpcode() == ISD::UNDEF)
5041 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5042 // A shuffle can only come from building a vector from various
5043 // elements of other vectors.
5045 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5046 VT.getVectorElementType()) {
5047 // This code doesn't know how to handle shuffles where the vector
5048 // element types do not match (this happens because type legalization
5049 // promotes the return type of EXTRACT_VECTOR_ELT).
5050 // FIXME: It might be appropriate to extend this code to handle
5051 // mismatched types.
5055 // Record this extraction against the appropriate vector if possible...
5056 SDValue SourceVec = V.getOperand(0);
5057 // If the element number isn't a constant, we can't effectively
5058 // analyze what's going on.
5059 if (!isa<ConstantSDNode>(V.getOperand(1)))
5061 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5062 bool FoundSource = false;
5063 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5064 if (SourceVecs[j] == SourceVec) {
5065 if (MinElts[j] > EltNo)
5067 if (MaxElts[j] < EltNo)
5074 // Or record a new source if not...
5076 SourceVecs.push_back(SourceVec);
5077 MinElts.push_back(EltNo);
5078 MaxElts.push_back(EltNo);
5082 // Currently only do something sane when at most two source vectors
5084 if (SourceVecs.size() > 2)
5087 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5088 int VEXTOffsets[2] = {0, 0};
5090 // This loop extracts the usage patterns of the source vectors
5091 // and prepares appropriate SDValues for a shuffle if possible.
5092 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5093 if (SourceVecs[i].getValueType() == VT) {
5094 // No VEXT necessary
5095 ShuffleSrcs[i] = SourceVecs[i];
5098 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5099 // It probably isn't worth padding out a smaller vector just to
5100 // break it down again in a shuffle.
5104 // Since only 64-bit and 128-bit vectors are legal on ARM and
5105 // we've eliminated the other cases...
5106 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5107 "unexpected vector sizes in ReconstructShuffle");
5109 if (MaxElts[i] - MinElts[i] >= NumElts) {
5110 // Span too large for a VEXT to cope
5114 if (MinElts[i] >= NumElts) {
5115 // The extraction can just take the second half
5116 VEXTOffsets[i] = NumElts;
5117 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5119 DAG.getIntPtrConstant(NumElts));
5120 } else if (MaxElts[i] < NumElts) {
5121 // The extraction can just take the first half
5123 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5125 DAG.getIntPtrConstant(0));
5127 // An actual VEXT is needed
5128 VEXTOffsets[i] = MinElts[i];
5129 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5131 DAG.getIntPtrConstant(0));
5132 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5134 DAG.getIntPtrConstant(NumElts));
5135 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5136 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5140 SmallVector<int, 8> Mask;
5142 for (unsigned i = 0; i < NumElts; ++i) {
5143 SDValue Entry = Op.getOperand(i);
5144 if (Entry.getOpcode() == ISD::UNDEF) {
5149 SDValue ExtractVec = Entry.getOperand(0);
5150 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5151 .getOperand(1))->getSExtValue();
5152 if (ExtractVec == SourceVecs[0]) {
5153 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5155 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5159 // Final check before we try to produce nonsense...
5160 if (isShuffleMaskLegal(Mask, VT))
5161 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5167 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5168 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5169 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5170 /// are assumed to be legal.
5172 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5174 if (VT.getVectorNumElements() == 4 &&
5175 (VT.is128BitVector() || VT.is64BitVector())) {
5176 unsigned PFIndexes[4];
5177 for (unsigned i = 0; i != 4; ++i) {
5181 PFIndexes[i] = M[i];
5184 // Compute the index in the perfect shuffle table.
5185 unsigned PFTableIndex =
5186 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5187 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5188 unsigned Cost = (PFEntry >> 30);
5195 unsigned Imm, WhichResult;
5197 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5198 return (EltSize >= 32 ||
5199 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5200 isVREVMask(M, VT, 64) ||
5201 isVREVMask(M, VT, 32) ||
5202 isVREVMask(M, VT, 16) ||
5203 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5204 isVTBLMask(M, VT) ||
5205 isVTRNMask(M, VT, WhichResult) ||
5206 isVUZPMask(M, VT, WhichResult) ||
5207 isVZIPMask(M, VT, WhichResult) ||
5208 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5209 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5210 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5211 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5214 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5215 /// the specified operations to build the shuffle.
5216 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5217 SDValue RHS, SelectionDAG &DAG,
5219 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5220 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5221 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5224 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5233 OP_VUZPL, // VUZP, left result
5234 OP_VUZPR, // VUZP, right result
5235 OP_VZIPL, // VZIP, left result
5236 OP_VZIPR, // VZIP, right result
5237 OP_VTRNL, // VTRN, left result
5238 OP_VTRNR // VTRN, right result
5241 if (OpNum == OP_COPY) {
5242 if (LHSID == (1*9+2)*9+3) return LHS;
5243 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5247 SDValue OpLHS, OpRHS;
5248 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5249 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5250 EVT VT = OpLHS.getValueType();
5253 default: llvm_unreachable("Unknown shuffle opcode!");
5255 // VREV divides the vector in half and swaps within the half.
5256 if (VT.getVectorElementType() == MVT::i32 ||
5257 VT.getVectorElementType() == MVT::f32)
5258 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5259 // vrev <4 x i16> -> VREV32
5260 if (VT.getVectorElementType() == MVT::i16)
5261 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5262 // vrev <4 x i8> -> VREV16
5263 assert(VT.getVectorElementType() == MVT::i8);
5264 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5269 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5270 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5274 return DAG.getNode(ARMISD::VEXT, dl, VT,
5276 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5279 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5280 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5283 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5284 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5287 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5288 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5292 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5293 ArrayRef<int> ShuffleMask,
5294 SelectionDAG &DAG) {
5295 // Check to see if we can use the VTBL instruction.
5296 SDValue V1 = Op.getOperand(0);
5297 SDValue V2 = Op.getOperand(1);
5300 SmallVector<SDValue, 8> VTBLMask;
5301 for (ArrayRef<int>::iterator
5302 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5303 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5305 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5306 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5307 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5310 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5311 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5315 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5316 SelectionDAG &DAG) {
5318 SDValue OpLHS = Op.getOperand(0);
5319 EVT VT = OpLHS.getValueType();
5321 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5322 "Expect an v8i16/v16i8 type");
5323 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5324 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5325 // extract the first 8 bytes into the top double word and the last 8 bytes
5326 // into the bottom double word. The v8i16 case is similar.
5327 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5328 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5329 DAG.getConstant(ExtractNum, MVT::i32));
5332 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5333 SDValue V1 = Op.getOperand(0);
5334 SDValue V2 = Op.getOperand(1);
5336 EVT VT = Op.getValueType();
5337 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5339 // Convert shuffles that are directly supported on NEON to target-specific
5340 // DAG nodes, instead of keeping them as shuffles and matching them again
5341 // during code selection. This is more efficient and avoids the possibility
5342 // of inconsistencies between legalization and selection.
5343 // FIXME: floating-point vectors should be canonicalized to integer vectors
5344 // of the same time so that they get CSEd properly.
5345 ArrayRef<int> ShuffleMask = SVN->getMask();
5347 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5348 if (EltSize <= 32) {
5349 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5350 int Lane = SVN->getSplatIndex();
5351 // If this is undef splat, generate it via "just" vdup, if possible.
5352 if (Lane == -1) Lane = 0;
5354 // Test if V1 is a SCALAR_TO_VECTOR.
5355 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5356 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5358 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5359 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5361 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5362 !isa<ConstantSDNode>(V1.getOperand(0))) {
5363 bool IsScalarToVector = true;
5364 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5365 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5366 IsScalarToVector = false;
5369 if (IsScalarToVector)
5370 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5372 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5373 DAG.getConstant(Lane, MVT::i32));
5378 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5381 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5382 DAG.getConstant(Imm, MVT::i32));
5385 if (isVREVMask(ShuffleMask, VT, 64))
5386 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5387 if (isVREVMask(ShuffleMask, VT, 32))
5388 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5389 if (isVREVMask(ShuffleMask, VT, 16))
5390 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5392 if (V2->getOpcode() == ISD::UNDEF &&
5393 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5394 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5395 DAG.getConstant(Imm, MVT::i32));
5398 // Check for Neon shuffles that modify both input vectors in place.
5399 // If both results are used, i.e., if there are two shuffles with the same
5400 // source operands and with masks corresponding to both results of one of
5401 // these operations, DAG memoization will ensure that a single node is
5402 // used for both shuffles.
5403 unsigned WhichResult;
5404 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5405 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5406 V1, V2).getValue(WhichResult);
5407 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5408 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5409 V1, V2).getValue(WhichResult);
5410 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5411 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5412 V1, V2).getValue(WhichResult);
5414 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5415 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5416 V1, V1).getValue(WhichResult);
5417 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5418 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5419 V1, V1).getValue(WhichResult);
5420 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5421 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5422 V1, V1).getValue(WhichResult);
5425 // If the shuffle is not directly supported and it has 4 elements, use
5426 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5427 unsigned NumElts = VT.getVectorNumElements();
5429 unsigned PFIndexes[4];
5430 for (unsigned i = 0; i != 4; ++i) {
5431 if (ShuffleMask[i] < 0)
5434 PFIndexes[i] = ShuffleMask[i];
5437 // Compute the index in the perfect shuffle table.
5438 unsigned PFTableIndex =
5439 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5440 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5441 unsigned Cost = (PFEntry >> 30);
5444 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5447 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5448 if (EltSize >= 32) {
5449 // Do the expansion with floating-point types, since that is what the VFP
5450 // registers are defined to use, and since i64 is not legal.
5451 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5452 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5453 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5454 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5455 SmallVector<SDValue, 8> Ops;
5456 for (unsigned i = 0; i < NumElts; ++i) {
5457 if (ShuffleMask[i] < 0)
5458 Ops.push_back(DAG.getUNDEF(EltVT));
5460 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5461 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5462 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5465 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5466 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5469 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5470 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5472 if (VT == MVT::v8i8) {
5473 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5474 if (NewOp.getNode())
5481 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5482 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5483 SDValue Lane = Op.getOperand(2);
5484 if (!isa<ConstantSDNode>(Lane))
5490 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5491 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5492 SDValue Lane = Op.getOperand(1);
5493 if (!isa<ConstantSDNode>(Lane))
5496 SDValue Vec = Op.getOperand(0);
5497 if (Op.getValueType() == MVT::i32 &&
5498 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5500 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5506 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5507 // The only time a CONCAT_VECTORS operation can have legal types is when
5508 // two 64-bit vectors are concatenated to a 128-bit vector.
5509 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5510 "unexpected CONCAT_VECTORS");
5512 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5513 SDValue Op0 = Op.getOperand(0);
5514 SDValue Op1 = Op.getOperand(1);
5515 if (Op0.getOpcode() != ISD::UNDEF)
5516 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5517 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5518 DAG.getIntPtrConstant(0));
5519 if (Op1.getOpcode() != ISD::UNDEF)
5520 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5521 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5522 DAG.getIntPtrConstant(1));
5523 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5526 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5527 /// element has been zero/sign-extended, depending on the isSigned parameter,
5528 /// from an integer type half its size.
5529 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5531 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5532 EVT VT = N->getValueType(0);
5533 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5534 SDNode *BVN = N->getOperand(0).getNode();
5535 if (BVN->getValueType(0) != MVT::v4i32 ||
5536 BVN->getOpcode() != ISD::BUILD_VECTOR)
5538 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5539 unsigned HiElt = 1 - LoElt;
5540 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5541 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5542 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5543 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5544 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5547 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5548 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5551 if (Hi0->isNullValue() && Hi1->isNullValue())
5557 if (N->getOpcode() != ISD::BUILD_VECTOR)
5560 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5561 SDNode *Elt = N->getOperand(i).getNode();
5562 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5563 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5564 unsigned HalfSize = EltSize / 2;
5566 if (!isIntN(HalfSize, C->getSExtValue()))
5569 if (!isUIntN(HalfSize, C->getZExtValue()))
5580 /// isSignExtended - Check if a node is a vector value that is sign-extended
5581 /// or a constant BUILD_VECTOR with sign-extended elements.
5582 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5583 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5585 if (isExtendedBUILD_VECTOR(N, DAG, true))
5590 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5591 /// or a constant BUILD_VECTOR with zero-extended elements.
5592 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5593 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5595 if (isExtendedBUILD_VECTOR(N, DAG, false))
5600 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5601 if (OrigVT.getSizeInBits() >= 64)
5604 assert(OrigVT.isSimple() && "Expecting a simple value type");
5606 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5607 switch (OrigSimpleTy) {
5608 default: llvm_unreachable("Unexpected Vector Type");
5617 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5618 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5619 /// We insert the required extension here to get the vector to fill a D register.
5620 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5623 unsigned ExtOpcode) {
5624 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5625 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5626 // 64-bits we need to insert a new extension so that it will be 64-bits.
5627 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5628 if (OrigTy.getSizeInBits() >= 64)
5631 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5632 EVT NewVT = getExtensionTo64Bits(OrigTy);
5634 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5637 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5638 /// does not do any sign/zero extension. If the original vector is less
5639 /// than 64 bits, an appropriate extension will be added after the load to
5640 /// reach a total size of 64 bits. We have to add the extension separately
5641 /// because ARM does not have a sign/zero extending load for vectors.
5642 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5643 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5645 // The load already has the right type.
5646 if (ExtendedTy == LD->getMemoryVT())
5647 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5648 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5649 LD->isNonTemporal(), LD->isInvariant(),
5650 LD->getAlignment());
5652 // We need to create a zextload/sextload. We cannot just create a load
5653 // followed by a zext/zext node because LowerMUL is also run during normal
5654 // operation legalization where we can't create illegal types.
5655 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5656 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5657 LD->getMemoryVT(), LD->isVolatile(),
5658 LD->isNonTemporal(), LD->getAlignment());
5661 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5662 /// extending load, or BUILD_VECTOR with extended elements, return the
5663 /// unextended value. The unextended vector should be 64 bits so that it can
5664 /// be used as an operand to a VMULL instruction. If the original vector size
5665 /// before extension is less than 64 bits we add a an extension to resize
5666 /// the vector to 64 bits.
5667 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5668 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5669 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5670 N->getOperand(0)->getValueType(0),
5674 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5675 return SkipLoadExtensionForVMULL(LD, DAG);
5677 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5678 // have been legalized as a BITCAST from v4i32.
5679 if (N->getOpcode() == ISD::BITCAST) {
5680 SDNode *BVN = N->getOperand(0).getNode();
5681 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5682 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5683 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5684 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5685 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5687 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5688 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5689 EVT VT = N->getValueType(0);
5690 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5691 unsigned NumElts = VT.getVectorNumElements();
5692 MVT TruncVT = MVT::getIntegerVT(EltSize);
5693 SmallVector<SDValue, 8> Ops;
5694 for (unsigned i = 0; i != NumElts; ++i) {
5695 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5696 const APInt &CInt = C->getAPIntValue();
5697 // Element types smaller than 32 bits are not legal, so use i32 elements.
5698 // The values are implicitly truncated so sext vs. zext doesn't matter.
5699 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5701 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5702 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5705 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5706 unsigned Opcode = N->getOpcode();
5707 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5708 SDNode *N0 = N->getOperand(0).getNode();
5709 SDNode *N1 = N->getOperand(1).getNode();
5710 return N0->hasOneUse() && N1->hasOneUse() &&
5711 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5716 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5717 unsigned Opcode = N->getOpcode();
5718 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5719 SDNode *N0 = N->getOperand(0).getNode();
5720 SDNode *N1 = N->getOperand(1).getNode();
5721 return N0->hasOneUse() && N1->hasOneUse() &&
5722 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5727 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5728 // Multiplications are only custom-lowered for 128-bit vectors so that
5729 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5730 EVT VT = Op.getValueType();
5731 assert(VT.is128BitVector() && VT.isInteger() &&
5732 "unexpected type for custom-lowering ISD::MUL");
5733 SDNode *N0 = Op.getOperand(0).getNode();
5734 SDNode *N1 = Op.getOperand(1).getNode();
5735 unsigned NewOpc = 0;
5737 bool isN0SExt = isSignExtended(N0, DAG);
5738 bool isN1SExt = isSignExtended(N1, DAG);
5739 if (isN0SExt && isN1SExt)
5740 NewOpc = ARMISD::VMULLs;
5742 bool isN0ZExt = isZeroExtended(N0, DAG);
5743 bool isN1ZExt = isZeroExtended(N1, DAG);
5744 if (isN0ZExt && isN1ZExt)
5745 NewOpc = ARMISD::VMULLu;
5746 else if (isN1SExt || isN1ZExt) {
5747 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5748 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5749 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5750 NewOpc = ARMISD::VMULLs;
5752 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5753 NewOpc = ARMISD::VMULLu;
5755 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5757 NewOpc = ARMISD::VMULLu;
5763 if (VT == MVT::v2i64)
5764 // Fall through to expand this. It is not legal.
5767 // Other vector multiplications are legal.
5772 // Legalize to a VMULL instruction.
5775 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5777 Op0 = SkipExtensionForVMULL(N0, DAG);
5778 assert(Op0.getValueType().is64BitVector() &&
5779 Op1.getValueType().is64BitVector() &&
5780 "unexpected types for extended operands to VMULL");
5781 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5784 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5785 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5792 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5793 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5794 EVT Op1VT = Op1.getValueType();
5795 return DAG.getNode(N0->getOpcode(), DL, VT,
5796 DAG.getNode(NewOpc, DL, VT,
5797 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5798 DAG.getNode(NewOpc, DL, VT,
5799 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5803 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5805 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5806 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5807 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5808 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5809 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5810 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5811 // Get reciprocal estimate.
5812 // float4 recip = vrecpeq_f32(yf);
5813 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5814 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5815 // Because char has a smaller range than uchar, we can actually get away
5816 // without any newton steps. This requires that we use a weird bias
5817 // of 0xb000, however (again, this has been exhaustively tested).
5818 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5819 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5820 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5821 Y = DAG.getConstant(0xb000, MVT::i32);
5822 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5823 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5824 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5825 // Convert back to short.
5826 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5827 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5832 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5834 // Convert to float.
5835 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5836 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5837 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5838 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5839 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5840 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5842 // Use reciprocal estimate and one refinement step.
5843 // float4 recip = vrecpeq_f32(yf);
5844 // recip *= vrecpsq_f32(yf, recip);
5845 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5846 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5847 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5848 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5850 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5851 // Because short has a smaller range than ushort, we can actually get away
5852 // with only a single newton step. This requires that we use a weird bias
5853 // of 89, however (again, this has been exhaustively tested).
5854 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5855 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5856 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5857 N1 = DAG.getConstant(0x89, MVT::i32);
5858 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5859 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5860 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5861 // Convert back to integer and return.
5862 // return vmovn_s32(vcvt_s32_f32(result));
5863 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5864 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5868 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5869 EVT VT = Op.getValueType();
5870 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5871 "unexpected type for custom-lowering ISD::SDIV");
5874 SDValue N0 = Op.getOperand(0);
5875 SDValue N1 = Op.getOperand(1);
5878 if (VT == MVT::v8i8) {
5879 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5880 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5882 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5883 DAG.getIntPtrConstant(4));
5884 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5885 DAG.getIntPtrConstant(4));
5886 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5887 DAG.getIntPtrConstant(0));
5888 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5889 DAG.getIntPtrConstant(0));
5891 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5892 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5894 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5895 N0 = LowerCONCAT_VECTORS(N0, DAG);
5897 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5900 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5903 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5904 EVT VT = Op.getValueType();
5905 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5906 "unexpected type for custom-lowering ISD::UDIV");
5909 SDValue N0 = Op.getOperand(0);
5910 SDValue N1 = Op.getOperand(1);
5913 if (VT == MVT::v8i8) {
5914 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5915 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5917 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5918 DAG.getIntPtrConstant(4));
5919 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5920 DAG.getIntPtrConstant(4));
5921 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5922 DAG.getIntPtrConstant(0));
5923 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5924 DAG.getIntPtrConstant(0));
5926 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5927 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5929 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5930 N0 = LowerCONCAT_VECTORS(N0, DAG);
5932 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5933 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5938 // v4i16 sdiv ... Convert to float.
5939 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5940 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5941 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5942 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5943 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5944 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5946 // Use reciprocal estimate and two refinement steps.
5947 // float4 recip = vrecpeq_f32(yf);
5948 // recip *= vrecpsq_f32(yf, recip);
5949 // recip *= vrecpsq_f32(yf, recip);
5950 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5951 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5952 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5953 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5955 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5956 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5957 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5959 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5960 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5961 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5962 // and that it will never cause us to return an answer too large).
5963 // float4 result = as_float4(as_int4(xf*recip) + 2);
5964 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5965 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5966 N1 = DAG.getConstant(2, MVT::i32);
5967 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5968 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5969 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5970 // Convert back to integer and return.
5971 // return vmovn_u32(vcvt_s32_f32(result));
5972 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5973 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5977 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5978 EVT VT = Op.getNode()->getValueType(0);
5979 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5982 bool ExtraOp = false;
5983 switch (Op.getOpcode()) {
5984 default: llvm_unreachable("Invalid code");
5985 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5986 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5987 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5988 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5992 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5994 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5995 Op.getOperand(1), Op.getOperand(2));
5998 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5999 // Monotonic load/store is legal for all targets
6000 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6003 // Aquire/Release load/store is not legal for targets without a
6004 // dmb or equivalent available.
6009 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
6010 SelectionDAG &DAG) {
6012 assert (Node->getValueType(0) == MVT::i64 &&
6013 "Only know how to expand i64 atomics");
6014 AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6016 SmallVector<SDValue, 6> Ops;
6017 Ops.push_back(Node->getOperand(0)); // Chain
6018 Ops.push_back(Node->getOperand(1)); // Ptr
6019 for(unsigned i=2; i<Node->getNumOperands(); i++) {
6021 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6022 Node->getOperand(i), DAG.getIntPtrConstant(0)));
6024 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6025 Node->getOperand(i), DAG.getIntPtrConstant(1)));
6027 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6029 DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6030 cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
6031 AN->getSynchScope());
6032 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6033 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6034 Results.push_back(Result.getValue(2));
6037 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6038 SmallVectorImpl<SDValue> &Results,
6040 const ARMSubtarget *Subtarget) {
6042 SDValue Cycles32, OutChain;
6044 if (Subtarget->hasPerfMon()) {
6045 // Under Power Management extensions, the cycle-count is:
6046 // mrc p15, #0, <Rt>, c9, c13, #0
6047 SDValue Ops[] = { N->getOperand(0), // Chain
6048 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6049 DAG.getConstant(15, MVT::i32),
6050 DAG.getConstant(0, MVT::i32),
6051 DAG.getConstant(9, MVT::i32),
6052 DAG.getConstant(13, MVT::i32),
6053 DAG.getConstant(0, MVT::i32)
6056 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6057 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6058 array_lengthof(Ops));
6059 OutChain = Cycles32.getValue(1);
6061 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6062 // there are older ARM CPUs that have implementation-specific ways of
6063 // obtaining this information (FIXME!).
6064 Cycles32 = DAG.getConstant(0, MVT::i32);
6065 OutChain = DAG.getEntryNode();
6069 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6070 Cycles32, DAG.getConstant(0, MVT::i32));
6071 Results.push_back(Cycles64);
6072 Results.push_back(OutChain);
6075 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6076 switch (Op.getOpcode()) {
6077 default: llvm_unreachable("Don't know how to custom lower this!");
6078 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6079 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6080 case ISD::GlobalAddress:
6081 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6082 LowerGlobalAddressELF(Op, DAG);
6083 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6084 case ISD::SELECT: return LowerSELECT(Op, DAG);
6085 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6086 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6087 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6088 case ISD::VASTART: return LowerVASTART(Op, DAG);
6089 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6090 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6091 case ISD::SINT_TO_FP:
6092 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6093 case ISD::FP_TO_SINT:
6094 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6095 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6096 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6097 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6098 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6099 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6100 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6101 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6103 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6106 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6107 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6108 case ISD::SRL_PARTS:
6109 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6110 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6111 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6112 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6113 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6114 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6115 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6116 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6117 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6118 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6119 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6120 case ISD::MUL: return LowerMUL(Op, DAG);
6121 case ISD::SDIV: return LowerSDIV(Op, DAG);
6122 case ISD::UDIV: return LowerUDIV(Op, DAG);
6126 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6127 case ISD::ATOMIC_LOAD:
6128 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6130 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6134 /// ReplaceNodeResults - Replace the results of node with an illegal result
6135 /// type with new values built out of custom code.
6136 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6137 SmallVectorImpl<SDValue>&Results,
6138 SelectionDAG &DAG) const {
6140 switch (N->getOpcode()) {
6142 llvm_unreachable("Don't know how to custom expand this!");
6144 Res = ExpandBITCAST(N, DAG);
6146 case ISD::SIGN_EXTEND:
6147 case ISD::ZERO_EXTEND:
6148 Res = ExpandVectorExtension(N, DAG);
6152 Res = Expand64BitShift(N, DAG, Subtarget);
6154 case ISD::READCYCLECOUNTER:
6155 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6157 case ISD::ATOMIC_STORE:
6158 case ISD::ATOMIC_LOAD:
6159 case ISD::ATOMIC_LOAD_ADD:
6160 case ISD::ATOMIC_LOAD_AND:
6161 case ISD::ATOMIC_LOAD_NAND:
6162 case ISD::ATOMIC_LOAD_OR:
6163 case ISD::ATOMIC_LOAD_SUB:
6164 case ISD::ATOMIC_LOAD_XOR:
6165 case ISD::ATOMIC_SWAP:
6166 case ISD::ATOMIC_CMP_SWAP:
6167 case ISD::ATOMIC_LOAD_MIN:
6168 case ISD::ATOMIC_LOAD_UMIN:
6169 case ISD::ATOMIC_LOAD_MAX:
6170 case ISD::ATOMIC_LOAD_UMAX:
6171 ReplaceATOMIC_OP_64(N, Results, DAG);
6175 Results.push_back(Res);
6178 //===----------------------------------------------------------------------===//
6179 // ARM Scheduler Hooks
6180 //===----------------------------------------------------------------------===//
6183 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6184 MachineBasicBlock *BB,
6185 unsigned Size) const {
6186 unsigned dest = MI->getOperand(0).getReg();
6187 unsigned ptr = MI->getOperand(1).getReg();
6188 unsigned oldval = MI->getOperand(2).getReg();
6189 unsigned newval = MI->getOperand(3).getReg();
6190 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6191 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6192 DebugLoc dl = MI->getDebugLoc();
6193 bool isThumb2 = Subtarget->isThumb2();
6195 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6196 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6197 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6198 (const TargetRegisterClass*)&ARM::GPRRegClass);
6201 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6202 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6203 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6206 unsigned ldrOpc, strOpc;
6207 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6209 MachineFunction *MF = BB->getParent();
6210 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6211 MachineFunction::iterator It = BB;
6212 ++It; // insert the new blocks after the current block
6214 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6215 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6216 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6217 MF->insert(It, loop1MBB);
6218 MF->insert(It, loop2MBB);
6219 MF->insert(It, exitMBB);
6221 // Transfer the remainder of BB and its successor edges to exitMBB.
6222 exitMBB->splice(exitMBB->begin(), BB,
6223 llvm::next(MachineBasicBlock::iterator(MI)),
6225 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6229 // fallthrough --> loop1MBB
6230 BB->addSuccessor(loop1MBB);
6233 // ldrex dest, [ptr]
6237 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6238 if (ldrOpc == ARM::t2LDREX)
6240 AddDefaultPred(MIB);
6241 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6242 .addReg(dest).addReg(oldval));
6243 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6244 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6245 BB->addSuccessor(loop2MBB);
6246 BB->addSuccessor(exitMBB);
6249 // strex scratch, newval, [ptr]
6253 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6254 if (strOpc == ARM::t2STREX)
6256 AddDefaultPred(MIB);
6257 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6258 .addReg(scratch).addImm(0));
6259 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6260 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6261 BB->addSuccessor(loop1MBB);
6262 BB->addSuccessor(exitMBB);
6268 MI->eraseFromParent(); // The instruction is gone now.
6274 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6275 unsigned Size, unsigned BinOpcode) const {
6276 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6277 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6279 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6280 MachineFunction *MF = BB->getParent();
6281 MachineFunction::iterator It = BB;
6284 unsigned dest = MI->getOperand(0).getReg();
6285 unsigned ptr = MI->getOperand(1).getReg();
6286 unsigned incr = MI->getOperand(2).getReg();
6287 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6288 DebugLoc dl = MI->getDebugLoc();
6289 bool isThumb2 = Subtarget->isThumb2();
6291 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6293 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6294 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6295 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6298 unsigned ldrOpc, strOpc;
6299 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6301 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6302 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6303 MF->insert(It, loopMBB);
6304 MF->insert(It, exitMBB);
6306 // Transfer the remainder of BB and its successor edges to exitMBB.
6307 exitMBB->splice(exitMBB->begin(), BB,
6308 llvm::next(MachineBasicBlock::iterator(MI)),
6310 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6312 const TargetRegisterClass *TRC = isThumb2 ?
6313 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6314 (const TargetRegisterClass*)&ARM::GPRRegClass;
6315 unsigned scratch = MRI.createVirtualRegister(TRC);
6316 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6320 // fallthrough --> loopMBB
6321 BB->addSuccessor(loopMBB);
6325 // <binop> scratch2, dest, incr
6326 // strex scratch, scratch2, ptr
6329 // fallthrough --> exitMBB
6331 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6332 if (ldrOpc == ARM::t2LDREX)
6334 AddDefaultPred(MIB);
6336 // operand order needs to go the other way for NAND
6337 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6338 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6339 addReg(incr).addReg(dest)).addReg(0);
6341 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6342 addReg(dest).addReg(incr)).addReg(0);
6345 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6346 if (strOpc == ARM::t2STREX)
6348 AddDefaultPred(MIB);
6349 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6350 .addReg(scratch).addImm(0));
6351 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6352 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6354 BB->addSuccessor(loopMBB);
6355 BB->addSuccessor(exitMBB);
6361 MI->eraseFromParent(); // The instruction is gone now.
6367 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6368 MachineBasicBlock *BB,
6371 ARMCC::CondCodes Cond) const {
6372 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6374 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6375 MachineFunction *MF = BB->getParent();
6376 MachineFunction::iterator It = BB;
6379 unsigned dest = MI->getOperand(0).getReg();
6380 unsigned ptr = MI->getOperand(1).getReg();
6381 unsigned incr = MI->getOperand(2).getReg();
6382 unsigned oldval = dest;
6383 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6384 DebugLoc dl = MI->getDebugLoc();
6385 bool isThumb2 = Subtarget->isThumb2();
6387 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6389 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6390 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6391 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6394 unsigned ldrOpc, strOpc, extendOpc;
6395 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6397 default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6399 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6402 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6409 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6410 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6411 MF->insert(It, loopMBB);
6412 MF->insert(It, exitMBB);
6414 // Transfer the remainder of BB and its successor edges to exitMBB.
6415 exitMBB->splice(exitMBB->begin(), BB,
6416 llvm::next(MachineBasicBlock::iterator(MI)),
6418 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6420 const TargetRegisterClass *TRC = isThumb2 ?
6421 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6422 (const TargetRegisterClass*)&ARM::GPRRegClass;
6423 unsigned scratch = MRI.createVirtualRegister(TRC);
6424 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6428 // fallthrough --> loopMBB
6429 BB->addSuccessor(loopMBB);
6433 // (sign extend dest, if required)
6435 // cmov.cond scratch2, incr, dest
6436 // strex scratch, scratch2, ptr
6439 // fallthrough --> exitMBB
6441 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6442 if (ldrOpc == ARM::t2LDREX)
6444 AddDefaultPred(MIB);
6446 // Sign extend the value, if necessary.
6447 if (signExtend && extendOpc) {
6448 oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6449 : &ARM::GPRnopcRegClass);
6451 MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6452 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6457 // Build compare and cmov instructions.
6458 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6459 .addReg(oldval).addReg(incr));
6460 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6461 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6463 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6464 if (strOpc == ARM::t2STREX)
6466 AddDefaultPred(MIB);
6467 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6468 .addReg(scratch).addImm(0));
6469 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6470 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6472 BB->addSuccessor(loopMBB);
6473 BB->addSuccessor(exitMBB);
6479 MI->eraseFromParent(); // The instruction is gone now.
6485 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6486 unsigned Op1, unsigned Op2,
6487 bool NeedsCarry, bool IsCmpxchg,
6488 bool IsMinMax, ARMCC::CondCodes CC) const {
6489 // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6490 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6492 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6493 MachineFunction *MF = BB->getParent();
6494 MachineFunction::iterator It = BB;
6497 bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6498 unsigned offset = (isStore ? -2 : 0);
6499 unsigned destlo = MI->getOperand(0).getReg();
6500 unsigned desthi = MI->getOperand(1).getReg();
6501 unsigned ptr = MI->getOperand(offset+2).getReg();
6502 unsigned vallo = MI->getOperand(offset+3).getReg();
6503 unsigned valhi = MI->getOperand(offset+4).getReg();
6504 unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6505 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6506 DebugLoc dl = MI->getDebugLoc();
6507 bool isThumb2 = Subtarget->isThumb2();
6509 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6511 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6512 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6513 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6514 MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6515 MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6518 unsigned ldrOpc, strOpc;
6519 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6521 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6522 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6523 if (IsCmpxchg || IsMinMax)
6524 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6526 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6527 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6529 MF->insert(It, loopMBB);
6530 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6531 if (IsCmpxchg) MF->insert(It, cont2BB);
6532 MF->insert(It, exitMBB);
6534 // Transfer the remainder of BB and its successor edges to exitMBB.
6535 exitMBB->splice(exitMBB->begin(), BB,
6536 llvm::next(MachineBasicBlock::iterator(MI)),
6538 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6540 const TargetRegisterClass *TRC = isThumb2 ?
6541 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6542 (const TargetRegisterClass*)&ARM::GPRRegClass;
6543 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6547 // fallthrough --> loopMBB
6548 BB->addSuccessor(loopMBB);
6551 // ldrexd r2, r3, ptr
6552 // <binopa> r0, r2, incr
6553 // <binopb> r1, r3, incr
6554 // strexd storesuccess, r0, r1, ptr
6555 // cmp storesuccess, #0
6557 // fallthrough --> exitMBB
6563 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6564 .addReg(destlo, RegState::Define)
6565 .addReg(desthi, RegState::Define)
6568 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6569 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6570 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6571 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6572 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6573 .addReg(GPRPair0, 0, ARM::gsub_0);
6574 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6575 .addReg(GPRPair0, 0, ARM::gsub_1);
6579 unsigned StoreLo, StoreHi;
6582 for (unsigned i = 0; i < 2; i++) {
6583 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6585 .addReg(i == 0 ? destlo : desthi)
6586 .addReg(i == 0 ? vallo : valhi));
6587 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6588 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6589 BB->addSuccessor(exitMBB);
6590 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6591 BB = (i == 0 ? contBB : cont2BB);
6594 // Copy to physregs for strexd
6595 StoreLo = MI->getOperand(5).getReg();
6596 StoreHi = MI->getOperand(6).getReg();
6598 // Perform binary operation
6599 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6600 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6601 .addReg(destlo).addReg(vallo))
6602 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6603 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6604 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6605 .addReg(desthi).addReg(valhi))
6606 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6611 // Copy to physregs for strexd
6616 // Compare and branch to exit block.
6617 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6618 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6619 BB->addSuccessor(exitMBB);
6620 BB->addSuccessor(contBB);
6628 MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6629 MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6630 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6631 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6633 // Marshal a pair...
6634 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6635 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6636 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6637 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6638 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6641 .addImm(ARM::gsub_0);
6642 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6645 .addImm(ARM::gsub_1);
6648 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6649 .addReg(StorePair).addReg(ptr));
6652 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6653 .addReg(storesuccess).addImm(0));
6654 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6655 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6657 BB->addSuccessor(loopMBB);
6658 BB->addSuccessor(exitMBB);
6664 MI->eraseFromParent(); // The instruction is gone now.
6670 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6672 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6674 unsigned destlo = MI->getOperand(0).getReg();
6675 unsigned desthi = MI->getOperand(1).getReg();
6676 unsigned ptr = MI->getOperand(2).getReg();
6677 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6678 DebugLoc dl = MI->getDebugLoc();
6679 bool isThumb2 = Subtarget->isThumb2();
6681 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6683 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6684 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6685 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6687 unsigned ldrOpc, strOpc;
6688 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6690 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6693 MIB.addReg(destlo, RegState::Define)
6694 .addReg(desthi, RegState::Define)
6698 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6699 MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6701 // Copy GPRPair0 into dest. (This copy will normally be coalesced.)
6702 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6703 .addReg(GPRPair0, 0, ARM::gsub_0);
6704 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6705 .addReg(GPRPair0, 0, ARM::gsub_1);
6707 AddDefaultPred(MIB);
6709 MI->eraseFromParent(); // The instruction is gone now.
6714 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6715 /// registers the function context.
6716 void ARMTargetLowering::
6717 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6718 MachineBasicBlock *DispatchBB, int FI) const {
6719 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6720 DebugLoc dl = MI->getDebugLoc();
6721 MachineFunction *MF = MBB->getParent();
6722 MachineRegisterInfo *MRI = &MF->getRegInfo();
6723 MachineConstantPool *MCP = MF->getConstantPool();
6724 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6725 const Function *F = MF->getFunction();
6727 bool isThumb = Subtarget->isThumb();
6728 bool isThumb2 = Subtarget->isThumb2();
6730 unsigned PCLabelId = AFI->createPICLabelUId();
6731 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6732 ARMConstantPoolValue *CPV =
6733 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6734 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6736 const TargetRegisterClass *TRC = isThumb ?
6737 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6738 (const TargetRegisterClass*)&ARM::GPRRegClass;
6740 // Grab constant pool and fixed stack memory operands.
6741 MachineMemOperand *CPMMO =
6742 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6743 MachineMemOperand::MOLoad, 4, 4);
6745 MachineMemOperand *FIMMOSt =
6746 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6747 MachineMemOperand::MOStore, 4, 4);
6749 // Load the address of the dispatch MBB into the jump buffer.
6751 // Incoming value: jbuf
6752 // ldr.n r5, LCPI1_1
6755 // str r5, [$jbuf, #+4] ; &jbuf[1]
6756 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6757 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6758 .addConstantPoolIndex(CPI)
6759 .addMemOperand(CPMMO));
6760 // Set the low bit because of thumb mode.
6761 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6763 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6764 .addReg(NewVReg1, RegState::Kill)
6766 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6767 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6768 .addReg(NewVReg2, RegState::Kill)
6770 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6771 .addReg(NewVReg3, RegState::Kill)
6773 .addImm(36) // &jbuf[1] :: pc
6774 .addMemOperand(FIMMOSt));
6775 } else if (isThumb) {
6776 // Incoming value: jbuf
6777 // ldr.n r1, LCPI1_4
6781 // add r2, $jbuf, #+4 ; &jbuf[1]
6783 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6784 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6785 .addConstantPoolIndex(CPI)
6786 .addMemOperand(CPMMO));
6787 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6788 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6789 .addReg(NewVReg1, RegState::Kill)
6791 // Set the low bit because of thumb mode.
6792 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6793 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6794 .addReg(ARM::CPSR, RegState::Define)
6796 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6797 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6798 .addReg(ARM::CPSR, RegState::Define)
6799 .addReg(NewVReg2, RegState::Kill)
6800 .addReg(NewVReg3, RegState::Kill));
6801 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6802 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6804 .addImm(36)); // &jbuf[1] :: pc
6805 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6806 .addReg(NewVReg4, RegState::Kill)
6807 .addReg(NewVReg5, RegState::Kill)
6809 .addMemOperand(FIMMOSt));
6811 // Incoming value: jbuf
6814 // str r1, [$jbuf, #+4] ; &jbuf[1]
6815 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6816 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6817 .addConstantPoolIndex(CPI)
6819 .addMemOperand(CPMMO));
6820 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6821 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6822 .addReg(NewVReg1, RegState::Kill)
6823 .addImm(PCLabelId));
6824 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6825 .addReg(NewVReg2, RegState::Kill)
6827 .addImm(36) // &jbuf[1] :: pc
6828 .addMemOperand(FIMMOSt));
6832 MachineBasicBlock *ARMTargetLowering::
6833 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6834 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6835 DebugLoc dl = MI->getDebugLoc();
6836 MachineFunction *MF = MBB->getParent();
6837 MachineRegisterInfo *MRI = &MF->getRegInfo();
6838 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6839 MachineFrameInfo *MFI = MF->getFrameInfo();
6840 int FI = MFI->getFunctionContextIndex();
6842 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6843 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6844 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6846 // Get a mapping of the call site numbers to all of the landing pads they're
6848 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6849 unsigned MaxCSNum = 0;
6850 MachineModuleInfo &MMI = MF->getMMI();
6851 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6853 if (!BB->isLandingPad()) continue;
6855 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6857 for (MachineBasicBlock::iterator
6858 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6859 if (!II->isEHLabel()) continue;
6861 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6862 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6864 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6865 for (SmallVectorImpl<unsigned>::iterator
6866 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6867 CSI != CSE; ++CSI) {
6868 CallSiteNumToLPad[*CSI].push_back(BB);
6869 MaxCSNum = std::max(MaxCSNum, *CSI);
6875 // Get an ordered list of the machine basic blocks for the jump table.
6876 std::vector<MachineBasicBlock*> LPadList;
6877 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6878 LPadList.reserve(CallSiteNumToLPad.size());
6879 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6880 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6881 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6882 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6883 LPadList.push_back(*II);
6884 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6888 assert(!LPadList.empty() &&
6889 "No landing pad destinations for the dispatch jump table!");
6891 // Create the jump table and associated information.
6892 MachineJumpTableInfo *JTI =
6893 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6894 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6895 unsigned UId = AFI->createJumpTableUId();
6896 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6898 // Create the MBBs for the dispatch code.
6900 // Shove the dispatch's address into the return slot in the function context.
6901 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6902 DispatchBB->setIsLandingPad();
6904 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6905 unsigned trap_opcode;
6906 if (Subtarget->isThumb())
6907 trap_opcode = ARM::tTRAP;
6909 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6911 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6912 DispatchBB->addSuccessor(TrapBB);
6914 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6915 DispatchBB->addSuccessor(DispContBB);
6918 MF->insert(MF->end(), DispatchBB);
6919 MF->insert(MF->end(), DispContBB);
6920 MF->insert(MF->end(), TrapBB);
6922 // Insert code into the entry block that creates and registers the function
6924 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6926 MachineMemOperand *FIMMOLd =
6927 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6928 MachineMemOperand::MOLoad |
6929 MachineMemOperand::MOVolatile, 4, 4);
6931 MachineInstrBuilder MIB;
6932 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6934 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6935 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6937 // Add a register mask with no preserved registers. This results in all
6938 // registers being marked as clobbered.
6939 MIB.addRegMask(RI.getNoPreservedMask());
6941 unsigned NumLPads = LPadList.size();
6942 if (Subtarget->isThumb2()) {
6943 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6944 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6947 .addMemOperand(FIMMOLd));
6949 if (NumLPads < 256) {
6950 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6952 .addImm(LPadList.size()));
6954 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6955 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6956 .addImm(NumLPads & 0xFFFF));
6958 unsigned VReg2 = VReg1;
6959 if ((NumLPads & 0xFFFF0000) != 0) {
6960 VReg2 = MRI->createVirtualRegister(TRC);
6961 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6963 .addImm(NumLPads >> 16));
6966 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6971 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6976 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6977 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6978 .addJumpTableIndex(MJTI)
6981 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6984 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6985 .addReg(NewVReg3, RegState::Kill)
6987 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6989 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6990 .addReg(NewVReg4, RegState::Kill)
6992 .addJumpTableIndex(MJTI)
6994 } else if (Subtarget->isThumb()) {
6995 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6996 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6999 .addMemOperand(FIMMOLd));
7001 if (NumLPads < 256) {
7002 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7006 MachineConstantPool *ConstantPool = MF->getConstantPool();
7007 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7008 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7010 // MachineConstantPool wants an explicit alignment.
7011 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7013 Align = getDataLayout()->getTypeAllocSize(C->getType());
7014 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7016 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7017 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7018 .addReg(VReg1, RegState::Define)
7019 .addConstantPoolIndex(Idx));
7020 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7025 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7030 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7031 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7032 .addReg(ARM::CPSR, RegState::Define)
7036 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7037 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7038 .addJumpTableIndex(MJTI)
7041 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7042 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7043 .addReg(ARM::CPSR, RegState::Define)
7044 .addReg(NewVReg2, RegState::Kill)
7047 MachineMemOperand *JTMMOLd =
7048 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7049 MachineMemOperand::MOLoad, 4, 4);
7051 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7052 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7053 .addReg(NewVReg4, RegState::Kill)
7055 .addMemOperand(JTMMOLd));
7057 unsigned NewVReg6 = NewVReg5;
7058 if (RelocM == Reloc::PIC_) {
7059 NewVReg6 = MRI->createVirtualRegister(TRC);
7060 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7061 .addReg(ARM::CPSR, RegState::Define)
7062 .addReg(NewVReg5, RegState::Kill)
7066 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7067 .addReg(NewVReg6, RegState::Kill)
7068 .addJumpTableIndex(MJTI)
7071 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7072 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7075 .addMemOperand(FIMMOLd));
7077 if (NumLPads < 256) {
7078 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7081 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7082 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7083 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7084 .addImm(NumLPads & 0xFFFF));
7086 unsigned VReg2 = VReg1;
7087 if ((NumLPads & 0xFFFF0000) != 0) {
7088 VReg2 = MRI->createVirtualRegister(TRC);
7089 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7091 .addImm(NumLPads >> 16));
7094 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7098 MachineConstantPool *ConstantPool = MF->getConstantPool();
7099 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7100 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7102 // MachineConstantPool wants an explicit alignment.
7103 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7105 Align = getDataLayout()->getTypeAllocSize(C->getType());
7106 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7108 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7109 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7110 .addReg(VReg1, RegState::Define)
7111 .addConstantPoolIndex(Idx)
7113 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7115 .addReg(VReg1, RegState::Kill));
7118 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7123 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7125 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7127 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7128 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7129 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7130 .addJumpTableIndex(MJTI)
7133 MachineMemOperand *JTMMOLd =
7134 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7135 MachineMemOperand::MOLoad, 4, 4);
7136 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7138 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7139 .addReg(NewVReg3, RegState::Kill)
7142 .addMemOperand(JTMMOLd));
7144 if (RelocM == Reloc::PIC_) {
7145 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7146 .addReg(NewVReg5, RegState::Kill)
7148 .addJumpTableIndex(MJTI)
7151 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7152 .addReg(NewVReg5, RegState::Kill)
7153 .addJumpTableIndex(MJTI)
7158 // Add the jump table entries as successors to the MBB.
7159 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7160 for (std::vector<MachineBasicBlock*>::iterator
7161 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7162 MachineBasicBlock *CurMBB = *I;
7163 if (SeenMBBs.insert(CurMBB))
7164 DispContBB->addSuccessor(CurMBB);
7167 // N.B. the order the invoke BBs are processed in doesn't matter here.
7168 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7169 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7170 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7171 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7172 MachineBasicBlock *BB = *I;
7174 // Remove the landing pad successor from the invoke block and replace it
7175 // with the new dispatch block.
7176 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7178 while (!Successors.empty()) {
7179 MachineBasicBlock *SMBB = Successors.pop_back_val();
7180 if (SMBB->isLandingPad()) {
7181 BB->removeSuccessor(SMBB);
7182 MBBLPads.push_back(SMBB);
7186 BB->addSuccessor(DispatchBB);
7188 // Find the invoke call and mark all of the callee-saved registers as
7189 // 'implicit defined' so that they're spilled. This prevents code from
7190 // moving instructions to before the EH block, where they will never be
7192 for (MachineBasicBlock::reverse_iterator
7193 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7194 if (!II->isCall()) continue;
7196 DenseMap<unsigned, bool> DefRegs;
7197 for (MachineInstr::mop_iterator
7198 OI = II->operands_begin(), OE = II->operands_end();
7200 if (!OI->isReg()) continue;
7201 DefRegs[OI->getReg()] = true;
7204 MachineInstrBuilder MIB(*MF, &*II);
7206 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7207 unsigned Reg = SavedRegs[i];
7208 if (Subtarget->isThumb2() &&
7209 !ARM::tGPRRegClass.contains(Reg) &&
7210 !ARM::hGPRRegClass.contains(Reg))
7212 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7214 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7217 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7224 // Mark all former landing pads as non-landing pads. The dispatch is the only
7226 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7227 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7228 (*I)->setIsLandingPad(false);
7230 // The instruction is gone now.
7231 MI->eraseFromParent();
7237 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7238 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7239 E = MBB->succ_end(); I != E; ++I)
7242 llvm_unreachable("Expecting a BB with two successors!");
7245 MachineBasicBlock *ARMTargetLowering::
7246 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
7247 // This pseudo instruction has 3 operands: dst, src, size
7248 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7249 // Otherwise, we will generate unrolled scalar copies.
7250 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7251 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7252 MachineFunction::iterator It = BB;
7255 unsigned dest = MI->getOperand(0).getReg();
7256 unsigned src = MI->getOperand(1).getReg();
7257 unsigned SizeVal = MI->getOperand(2).getImm();
7258 unsigned Align = MI->getOperand(3).getImm();
7259 DebugLoc dl = MI->getDebugLoc();
7261 bool isThumb2 = Subtarget->isThumb2();
7262 MachineFunction *MF = BB->getParent();
7263 MachineRegisterInfo &MRI = MF->getRegInfo();
7264 unsigned ldrOpc, strOpc, UnitSize = 0;
7266 const TargetRegisterClass *TRC = isThumb2 ?
7267 (const TargetRegisterClass*)&ARM::tGPRRegClass :
7268 (const TargetRegisterClass*)&ARM::GPRRegClass;
7269 const TargetRegisterClass *TRC_Vec = 0;
7272 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7273 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7275 } else if (Align & 2) {
7276 ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
7277 strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
7280 // Check whether we can use NEON instructions.
7281 if (!MF->getFunction()->getAttributes().
7282 hasAttribute(AttributeSet::FunctionIndex,
7283 Attribute::NoImplicitFloat) &&
7284 Subtarget->hasNEON()) {
7285 if ((Align % 16 == 0) && SizeVal >= 16) {
7286 ldrOpc = ARM::VLD1q32wb_fixed;
7287 strOpc = ARM::VST1q32wb_fixed;
7289 TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
7291 else if ((Align % 8 == 0) && SizeVal >= 8) {
7292 ldrOpc = ARM::VLD1d32wb_fixed;
7293 strOpc = ARM::VST1d32wb_fixed;
7295 TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
7298 // Can't use NEON instructions.
7299 if (UnitSize == 0) {
7300 ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
7301 strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
7306 unsigned BytesLeft = SizeVal % UnitSize;
7307 unsigned LoopSize = SizeVal - BytesLeft;
7309 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7310 // Use LDR and STR to copy.
7311 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7312 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7313 unsigned srcIn = src;
7314 unsigned destIn = dest;
7315 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7316 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7317 unsigned srcOut = MRI.createVirtualRegister(TRC);
7318 unsigned destOut = MRI.createVirtualRegister(TRC);
7319 if (UnitSize >= 8) {
7320 AddDefaultPred(BuildMI(*BB, MI, dl,
7321 TII->get(ldrOpc), scratch)
7322 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
7324 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7325 .addReg(destIn).addImm(0).addReg(scratch));
7326 } else if (isThumb2) {
7327 AddDefaultPred(BuildMI(*BB, MI, dl,
7328 TII->get(ldrOpc), scratch)
7329 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
7331 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7332 .addReg(scratch).addReg(destIn)
7335 AddDefaultPred(BuildMI(*BB, MI, dl,
7336 TII->get(ldrOpc), scratch)
7337 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
7340 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7341 .addReg(scratch).addReg(destIn)
7342 .addReg(0).addImm(UnitSize));
7348 // Handle the leftover bytes with LDRB and STRB.
7349 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7350 // [destOut] = STRB_POST(scratch, destIn, 1)
7351 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7352 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7353 for (unsigned i = 0; i < BytesLeft; i++) {
7354 unsigned scratch = MRI.createVirtualRegister(TRC);
7355 unsigned srcOut = MRI.createVirtualRegister(TRC);
7356 unsigned destOut = MRI.createVirtualRegister(TRC);
7358 AddDefaultPred(BuildMI(*BB, MI, dl,
7359 TII->get(ldrOpc),scratch)
7360 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7362 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7363 .addReg(scratch).addReg(destIn)
7364 .addReg(0).addImm(1));
7366 AddDefaultPred(BuildMI(*BB, MI, dl,
7367 TII->get(ldrOpc),scratch)
7368 .addReg(srcOut, RegState::Define).addReg(srcIn)
7369 .addReg(0).addImm(1));
7371 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7372 .addReg(scratch).addReg(destIn)
7373 .addReg(0).addImm(1));
7378 MI->eraseFromParent(); // The instruction is gone now.
7382 // Expand the pseudo op to a loop.
7385 // movw varEnd, # --> with thumb2
7387 // ldrcp varEnd, idx --> without thumb2
7388 // fallthrough --> loopMBB
7390 // PHI varPhi, varEnd, varLoop
7391 // PHI srcPhi, src, srcLoop
7392 // PHI destPhi, dst, destLoop
7393 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7394 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7395 // subs varLoop, varPhi, #UnitSize
7397 // fallthrough --> exitMBB
7399 // epilogue to handle left-over bytes
7400 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7401 // [destOut] = STRB_POST(scratch, destLoop, 1)
7402 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7403 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7404 MF->insert(It, loopMBB);
7405 MF->insert(It, exitMBB);
7407 // Transfer the remainder of BB and its successor edges to exitMBB.
7408 exitMBB->splice(exitMBB->begin(), BB,
7409 llvm::next(MachineBasicBlock::iterator(MI)),
7411 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7413 // Load an immediate to varEnd.
7414 unsigned varEnd = MRI.createVirtualRegister(TRC);
7416 unsigned VReg1 = varEnd;
7417 if ((LoopSize & 0xFFFF0000) != 0)
7418 VReg1 = MRI.createVirtualRegister(TRC);
7419 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7420 .addImm(LoopSize & 0xFFFF));
7422 if ((LoopSize & 0xFFFF0000) != 0)
7423 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7425 .addImm(LoopSize >> 16));
7427 MachineConstantPool *ConstantPool = MF->getConstantPool();
7428 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7429 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7431 // MachineConstantPool wants an explicit alignment.
7432 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7434 Align = getDataLayout()->getTypeAllocSize(C->getType());
7435 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7437 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7438 .addReg(varEnd, RegState::Define)
7439 .addConstantPoolIndex(Idx)
7442 BB->addSuccessor(loopMBB);
7444 // Generate the loop body:
7445 // varPhi = PHI(varLoop, varEnd)
7446 // srcPhi = PHI(srcLoop, src)
7447 // destPhi = PHI(destLoop, dst)
7448 MachineBasicBlock *entryBB = BB;
7450 unsigned varLoop = MRI.createVirtualRegister(TRC);
7451 unsigned varPhi = MRI.createVirtualRegister(TRC);
7452 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7453 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7454 unsigned destLoop = MRI.createVirtualRegister(TRC);
7455 unsigned destPhi = MRI.createVirtualRegister(TRC);
7457 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7458 .addReg(varLoop).addMBB(loopMBB)
7459 .addReg(varEnd).addMBB(entryBB);
7460 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7461 .addReg(srcLoop).addMBB(loopMBB)
7462 .addReg(src).addMBB(entryBB);
7463 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7464 .addReg(destLoop).addMBB(loopMBB)
7465 .addReg(dest).addMBB(entryBB);
7467 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7468 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7469 unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7470 if (UnitSize >= 8) {
7471 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7472 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7474 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7475 .addReg(destPhi).addImm(0).addReg(scratch));
7476 } else if (isThumb2) {
7477 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7478 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7480 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7481 .addReg(scratch).addReg(destPhi)
7484 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7485 .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7488 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7489 .addReg(scratch).addReg(destPhi)
7490 .addReg(0).addImm(UnitSize));
7493 // Decrement loop variable by UnitSize.
7494 MachineInstrBuilder MIB = BuildMI(BB, dl,
7495 TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7496 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7497 MIB->getOperand(5).setReg(ARM::CPSR);
7498 MIB->getOperand(5).setIsDef(true);
7500 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7501 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7503 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7504 BB->addSuccessor(loopMBB);
7505 BB->addSuccessor(exitMBB);
7507 // Add epilogue to handle BytesLeft.
7509 MachineInstr *StartOfExit = exitMBB->begin();
7510 ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7511 strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7513 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7514 // [destOut] = STRB_POST(scratch, destLoop, 1)
7515 unsigned srcIn = srcLoop;
7516 unsigned destIn = destLoop;
7517 for (unsigned i = 0; i < BytesLeft; i++) {
7518 unsigned scratch = MRI.createVirtualRegister(TRC);
7519 unsigned srcOut = MRI.createVirtualRegister(TRC);
7520 unsigned destOut = MRI.createVirtualRegister(TRC);
7522 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7523 TII->get(ldrOpc),scratch)
7524 .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7526 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7527 .addReg(scratch).addReg(destIn)
7530 AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7531 TII->get(ldrOpc),scratch)
7532 .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7534 AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7535 .addReg(scratch).addReg(destIn)
7536 .addReg(0).addImm(1));
7542 MI->eraseFromParent(); // The instruction is gone now.
7547 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7548 MachineBasicBlock *BB) const {
7549 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7550 DebugLoc dl = MI->getDebugLoc();
7551 bool isThumb2 = Subtarget->isThumb2();
7552 switch (MI->getOpcode()) {
7555 llvm_unreachable("Unexpected instr type to insert");
7557 // The Thumb2 pre-indexed stores have the same MI operands, they just
7558 // define them differently in the .td files from the isel patterns, so
7559 // they need pseudos.
7560 case ARM::t2STR_preidx:
7561 MI->setDesc(TII->get(ARM::t2STR_PRE));
7563 case ARM::t2STRB_preidx:
7564 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7566 case ARM::t2STRH_preidx:
7567 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7570 case ARM::STRi_preidx:
7571 case ARM::STRBi_preidx: {
7572 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7573 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7574 // Decode the offset.
7575 unsigned Offset = MI->getOperand(4).getImm();
7576 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7577 Offset = ARM_AM::getAM2Offset(Offset);
7581 MachineMemOperand *MMO = *MI->memoperands_begin();
7582 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7583 .addOperand(MI->getOperand(0)) // Rn_wb
7584 .addOperand(MI->getOperand(1)) // Rt
7585 .addOperand(MI->getOperand(2)) // Rn
7586 .addImm(Offset) // offset (skip GPR==zero_reg)
7587 .addOperand(MI->getOperand(5)) // pred
7588 .addOperand(MI->getOperand(6))
7589 .addMemOperand(MMO);
7590 MI->eraseFromParent();
7593 case ARM::STRr_preidx:
7594 case ARM::STRBr_preidx:
7595 case ARM::STRH_preidx: {
7597 switch (MI->getOpcode()) {
7598 default: llvm_unreachable("unexpected opcode!");
7599 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7600 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7601 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7603 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7604 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7605 MIB.addOperand(MI->getOperand(i));
7606 MI->eraseFromParent();
7609 case ARM::ATOMIC_LOAD_ADD_I8:
7610 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7611 case ARM::ATOMIC_LOAD_ADD_I16:
7612 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7613 case ARM::ATOMIC_LOAD_ADD_I32:
7614 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7616 case ARM::ATOMIC_LOAD_AND_I8:
7617 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7618 case ARM::ATOMIC_LOAD_AND_I16:
7619 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7620 case ARM::ATOMIC_LOAD_AND_I32:
7621 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7623 case ARM::ATOMIC_LOAD_OR_I8:
7624 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7625 case ARM::ATOMIC_LOAD_OR_I16:
7626 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7627 case ARM::ATOMIC_LOAD_OR_I32:
7628 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7630 case ARM::ATOMIC_LOAD_XOR_I8:
7631 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7632 case ARM::ATOMIC_LOAD_XOR_I16:
7633 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7634 case ARM::ATOMIC_LOAD_XOR_I32:
7635 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7637 case ARM::ATOMIC_LOAD_NAND_I8:
7638 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7639 case ARM::ATOMIC_LOAD_NAND_I16:
7640 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7641 case ARM::ATOMIC_LOAD_NAND_I32:
7642 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7644 case ARM::ATOMIC_LOAD_SUB_I8:
7645 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7646 case ARM::ATOMIC_LOAD_SUB_I16:
7647 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7648 case ARM::ATOMIC_LOAD_SUB_I32:
7649 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7651 case ARM::ATOMIC_LOAD_MIN_I8:
7652 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7653 case ARM::ATOMIC_LOAD_MIN_I16:
7654 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7655 case ARM::ATOMIC_LOAD_MIN_I32:
7656 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7658 case ARM::ATOMIC_LOAD_MAX_I8:
7659 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7660 case ARM::ATOMIC_LOAD_MAX_I16:
7661 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7662 case ARM::ATOMIC_LOAD_MAX_I32:
7663 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7665 case ARM::ATOMIC_LOAD_UMIN_I8:
7666 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7667 case ARM::ATOMIC_LOAD_UMIN_I16:
7668 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7669 case ARM::ATOMIC_LOAD_UMIN_I32:
7670 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7672 case ARM::ATOMIC_LOAD_UMAX_I8:
7673 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7674 case ARM::ATOMIC_LOAD_UMAX_I16:
7675 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7676 case ARM::ATOMIC_LOAD_UMAX_I32:
7677 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7679 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
7680 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7681 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7683 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
7684 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7685 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7687 case ARM::ATOMIC_LOAD_I64:
7688 return EmitAtomicLoad64(MI, BB);
7690 case ARM::ATOMIC_LOAD_ADD_I64:
7691 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7692 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7693 /*NeedsCarry*/ true);
7694 case ARM::ATOMIC_LOAD_SUB_I64:
7695 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7696 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7697 /*NeedsCarry*/ true);
7698 case ARM::ATOMIC_LOAD_OR_I64:
7699 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7700 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7701 case ARM::ATOMIC_LOAD_XOR_I64:
7702 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7703 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7704 case ARM::ATOMIC_LOAD_AND_I64:
7705 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7706 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7707 case ARM::ATOMIC_STORE_I64:
7708 case ARM::ATOMIC_SWAP_I64:
7709 return EmitAtomicBinary64(MI, BB, 0, 0, false);
7710 case ARM::ATOMIC_CMP_SWAP_I64:
7711 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7712 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7713 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7714 case ARM::ATOMIC_LOAD_MIN_I64:
7715 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7716 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7717 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7718 /*IsMinMax*/ true, ARMCC::LT);
7719 case ARM::ATOMIC_LOAD_MAX_I64:
7720 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7721 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7722 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7723 /*IsMinMax*/ true, ARMCC::GE);
7724 case ARM::ATOMIC_LOAD_UMIN_I64:
7725 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7726 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7727 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7728 /*IsMinMax*/ true, ARMCC::LO);
7729 case ARM::ATOMIC_LOAD_UMAX_I64:
7730 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7731 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7732 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7733 /*IsMinMax*/ true, ARMCC::HS);
7735 case ARM::tMOVCCr_pseudo: {
7736 // To "insert" a SELECT_CC instruction, we actually have to insert the
7737 // diamond control-flow pattern. The incoming instruction knows the
7738 // destination vreg to set, the condition code register to branch on, the
7739 // true/false values to select between, and a branch opcode to use.
7740 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7741 MachineFunction::iterator It = BB;
7747 // cmpTY ccX, r1, r2
7749 // fallthrough --> copy0MBB
7750 MachineBasicBlock *thisMBB = BB;
7751 MachineFunction *F = BB->getParent();
7752 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7753 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7754 F->insert(It, copy0MBB);
7755 F->insert(It, sinkMBB);
7757 // Transfer the remainder of BB and its successor edges to sinkMBB.
7758 sinkMBB->splice(sinkMBB->begin(), BB,
7759 llvm::next(MachineBasicBlock::iterator(MI)),
7761 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7763 BB->addSuccessor(copy0MBB);
7764 BB->addSuccessor(sinkMBB);
7766 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7767 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7770 // %FalseValue = ...
7771 // # fallthrough to sinkMBB
7774 // Update machine-CFG edges
7775 BB->addSuccessor(sinkMBB);
7778 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7781 BuildMI(*BB, BB->begin(), dl,
7782 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7783 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7784 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7786 MI->eraseFromParent(); // The pseudo instruction is gone now.
7791 case ARM::BCCZi64: {
7792 // If there is an unconditional branch to the other successor, remove it.
7793 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7795 // Compare both parts that make up the double comparison separately for
7797 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7799 unsigned LHS1 = MI->getOperand(1).getReg();
7800 unsigned LHS2 = MI->getOperand(2).getReg();
7802 AddDefaultPred(BuildMI(BB, dl,
7803 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7804 .addReg(LHS1).addImm(0));
7805 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7806 .addReg(LHS2).addImm(0)
7807 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7809 unsigned RHS1 = MI->getOperand(3).getReg();
7810 unsigned RHS2 = MI->getOperand(4).getReg();
7811 AddDefaultPred(BuildMI(BB, dl,
7812 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7813 .addReg(LHS1).addReg(RHS1));
7814 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7815 .addReg(LHS2).addReg(RHS2)
7816 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7819 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7820 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7821 if (MI->getOperand(0).getImm() == ARMCC::NE)
7822 std::swap(destMBB, exitMBB);
7824 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7825 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7827 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7829 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7831 MI->eraseFromParent(); // The pseudo instruction is gone now.
7835 case ARM::Int_eh_sjlj_setjmp:
7836 case ARM::Int_eh_sjlj_setjmp_nofp:
7837 case ARM::tInt_eh_sjlj_setjmp:
7838 case ARM::t2Int_eh_sjlj_setjmp:
7839 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7840 EmitSjLjDispatchBlock(MI, BB);
7845 // To insert an ABS instruction, we have to insert the
7846 // diamond control-flow pattern. The incoming instruction knows the
7847 // source vreg to test against 0, the destination vreg to set,
7848 // the condition code register to branch on, the
7849 // true/false values to select between, and a branch opcode to use.
7854 // BCC (branch to SinkBB if V0 >= 0)
7855 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7856 // SinkBB: V1 = PHI(V2, V3)
7857 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7858 MachineFunction::iterator BBI = BB;
7860 MachineFunction *Fn = BB->getParent();
7861 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7862 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7863 Fn->insert(BBI, RSBBB);
7864 Fn->insert(BBI, SinkBB);
7866 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7867 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7868 bool isThumb2 = Subtarget->isThumb2();
7869 MachineRegisterInfo &MRI = Fn->getRegInfo();
7870 // In Thumb mode S must not be specified if source register is the SP or
7871 // PC and if destination register is the SP, so restrict register class
7872 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7873 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7874 (const TargetRegisterClass*)&ARM::GPRRegClass);
7876 // Transfer the remainder of BB and its successor edges to sinkMBB.
7877 SinkBB->splice(SinkBB->begin(), BB,
7878 llvm::next(MachineBasicBlock::iterator(MI)),
7880 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7882 BB->addSuccessor(RSBBB);
7883 BB->addSuccessor(SinkBB);
7885 // fall through to SinkMBB
7886 RSBBB->addSuccessor(SinkBB);
7888 // insert a cmp at the end of BB
7889 AddDefaultPred(BuildMI(BB, dl,
7890 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7891 .addReg(ABSSrcReg).addImm(0));
7893 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7895 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7896 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7898 // insert rsbri in RSBBB
7899 // Note: BCC and rsbri will be converted into predicated rsbmi
7900 // by if-conversion pass
7901 BuildMI(*RSBBB, RSBBB->begin(), dl,
7902 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7903 .addReg(ABSSrcReg, RegState::Kill)
7904 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7906 // insert PHI in SinkBB,
7907 // reuse ABSDstReg to not change uses of ABS instruction
7908 BuildMI(*SinkBB, SinkBB->begin(), dl,
7909 TII->get(ARM::PHI), ABSDstReg)
7910 .addReg(NewRsbDstReg).addMBB(RSBBB)
7911 .addReg(ABSSrcReg).addMBB(BB);
7913 // remove ABS instruction
7914 MI->eraseFromParent();
7916 // return last added BB
7919 case ARM::COPY_STRUCT_BYVAL_I32:
7921 return EmitStructByval(MI, BB);
7925 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7926 SDNode *Node) const {
7927 if (!MI->hasPostISelHook()) {
7928 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7929 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7933 const MCInstrDesc *MCID = &MI->getDesc();
7934 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7935 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7936 // operand is still set to noreg. If needed, set the optional operand's
7937 // register to CPSR, and remove the redundant implicit def.
7939 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7941 // Rename pseudo opcodes.
7942 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7944 const ARMBaseInstrInfo *TII =
7945 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7946 MCID = &TII->get(NewOpc);
7948 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7949 "converted opcode should be the same except for cc_out");
7953 // Add the optional cc_out operand
7954 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7956 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7958 // Any ARM instruction that sets the 's' bit should specify an optional
7959 // "cc_out" operand in the last operand position.
7960 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7961 assert(!NewOpc && "Optional cc_out operand required");
7964 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7965 // since we already have an optional CPSR def.
7966 bool definesCPSR = false;
7967 bool deadCPSR = false;
7968 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7970 const MachineOperand &MO = MI->getOperand(i);
7971 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7975 MI->RemoveOperand(i);
7980 assert(!NewOpc && "Optional cc_out operand required");
7983 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7985 assert(!MI->getOperand(ccOutIdx).getReg() &&
7986 "expect uninitialized optional cc_out operand");
7990 // If this instruction was defined with an optional CPSR def and its dag node
7991 // had a live implicit CPSR def, then activate the optional CPSR def.
7992 MachineOperand &MO = MI->getOperand(ccOutIdx);
7993 MO.setReg(ARM::CPSR);
7997 //===----------------------------------------------------------------------===//
7998 // ARM Optimization Hooks
7999 //===----------------------------------------------------------------------===//
8001 // Helper function that checks if N is a null or all ones constant.
8002 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8003 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8006 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8009 // Return true if N is conditionally 0 or all ones.
8010 // Detects these expressions where cc is an i1 value:
8012 // (select cc 0, y) [AllOnes=0]
8013 // (select cc y, 0) [AllOnes=0]
8014 // (zext cc) [AllOnes=0]
8015 // (sext cc) [AllOnes=0/1]
8016 // (select cc -1, y) [AllOnes=1]
8017 // (select cc y, -1) [AllOnes=1]
8019 // Invert is set when N is the null/all ones constant when CC is false.
8020 // OtherOp is set to the alternative value of N.
8021 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8022 SDValue &CC, bool &Invert,
8024 SelectionDAG &DAG) {
8025 switch (N->getOpcode()) {
8026 default: return false;
8028 CC = N->getOperand(0);
8029 SDValue N1 = N->getOperand(1);
8030 SDValue N2 = N->getOperand(2);
8031 if (isZeroOrAllOnes(N1, AllOnes)) {
8036 if (isZeroOrAllOnes(N2, AllOnes)) {
8043 case ISD::ZERO_EXTEND:
8044 // (zext cc) can never be the all ones value.
8048 case ISD::SIGN_EXTEND: {
8049 EVT VT = N->getValueType(0);
8050 CC = N->getOperand(0);
8051 if (CC.getValueType() != MVT::i1)
8055 // When looking for an AllOnes constant, N is an sext, and the 'other'
8057 OtherOp = DAG.getConstant(0, VT);
8058 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8059 // When looking for a 0 constant, N can be zext or sext.
8060 OtherOp = DAG.getConstant(1, VT);
8062 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8068 // Combine a constant select operand into its use:
8070 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8071 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8072 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8073 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8074 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8076 // The transform is rejected if the select doesn't have a constant operand that
8077 // is null, or all ones when AllOnes is set.
8079 // Also recognize sext/zext from i1:
8081 // (add (zext cc), x) -> (select cc (add x, 1), x)
8082 // (add (sext cc), x) -> (select cc (add x, -1), x)
8084 // These transformations eventually create predicated instructions.
8086 // @param N The node to transform.
8087 // @param Slct The N operand that is a select.
8088 // @param OtherOp The other N operand (x above).
8089 // @param DCI Context.
8090 // @param AllOnes Require the select constant to be all ones instead of null.
8091 // @returns The new node, or SDValue() on failure.
8093 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8094 TargetLowering::DAGCombinerInfo &DCI,
8095 bool AllOnes = false) {
8096 SelectionDAG &DAG = DCI.DAG;
8097 EVT VT = N->getValueType(0);
8098 SDValue NonConstantVal;
8101 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8102 NonConstantVal, DAG))
8105 // Slct is now know to be the desired identity constant when CC is true.
8106 SDValue TrueVal = OtherOp;
8107 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8108 OtherOp, NonConstantVal);
8109 // Unless SwapSelectOps says CC should be false.
8111 std::swap(TrueVal, FalseVal);
8113 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8114 CCOp, TrueVal, FalseVal);
8117 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8119 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8120 TargetLowering::DAGCombinerInfo &DCI) {
8121 SDValue N0 = N->getOperand(0);
8122 SDValue N1 = N->getOperand(1);
8123 if (N0.getNode()->hasOneUse()) {
8124 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8125 if (Result.getNode())
8128 if (N1.getNode()->hasOneUse()) {
8129 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8130 if (Result.getNode())
8136 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8137 // (only after legalization).
8138 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8139 TargetLowering::DAGCombinerInfo &DCI,
8140 const ARMSubtarget *Subtarget) {
8142 // Only perform optimization if after legalize, and if NEON is available. We
8143 // also expected both operands to be BUILD_VECTORs.
8144 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8145 || N0.getOpcode() != ISD::BUILD_VECTOR
8146 || N1.getOpcode() != ISD::BUILD_VECTOR)
8149 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8150 EVT VT = N->getValueType(0);
8151 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8154 // Check that the vector operands are of the right form.
8155 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8156 // operands, where N is the size of the formed vector.
8157 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8158 // index such that we have a pair wise add pattern.
8160 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8161 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8163 SDValue Vec = N0->getOperand(0)->getOperand(0);
8164 SDNode *V = Vec.getNode();
8165 unsigned nextIndex = 0;
8167 // For each operands to the ADD which are BUILD_VECTORs,
8168 // check to see if each of their operands are an EXTRACT_VECTOR with
8169 // the same vector and appropriate index.
8170 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8171 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8172 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8174 SDValue ExtVec0 = N0->getOperand(i);
8175 SDValue ExtVec1 = N1->getOperand(i);
8177 // First operand is the vector, verify its the same.
8178 if (V != ExtVec0->getOperand(0).getNode() ||
8179 V != ExtVec1->getOperand(0).getNode())
8182 // Second is the constant, verify its correct.
8183 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8184 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8186 // For the constant, we want to see all the even or all the odd.
8187 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8188 || C1->getZExtValue() != nextIndex+1)
8197 // Create VPADDL node.
8198 SelectionDAG &DAG = DCI.DAG;
8199 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8201 // Build operand list.
8202 SmallVector<SDValue, 8> Ops;
8203 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8204 TLI.getPointerTy()));
8206 // Input is the vector.
8209 // Get widened type and narrowed type.
8211 unsigned numElem = VT.getVectorNumElements();
8212 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8213 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8214 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8215 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8217 llvm_unreachable("Invalid vector element type for padd optimization.");
8220 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8221 widenType, &Ops[0], Ops.size());
8222 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8225 static SDValue findMUL_LOHI(SDValue V) {
8226 if (V->getOpcode() == ISD::UMUL_LOHI ||
8227 V->getOpcode() == ISD::SMUL_LOHI)
8232 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8233 TargetLowering::DAGCombinerInfo &DCI,
8234 const ARMSubtarget *Subtarget) {
8236 if (Subtarget->isThumb1Only()) return SDValue();
8238 // Only perform the checks after legalize when the pattern is available.
8239 if (DCI.isBeforeLegalize()) return SDValue();
8241 // Look for multiply add opportunities.
8242 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8243 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8244 // a glue link from the first add to the second add.
8245 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8246 // a S/UMLAL instruction.
8249 // \ / \ [no multiline comment]
8255 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8256 SDValue AddcOp0 = AddcNode->getOperand(0);
8257 SDValue AddcOp1 = AddcNode->getOperand(1);
8259 // Check if the two operands are from the same mul_lohi node.
8260 if (AddcOp0.getNode() == AddcOp1.getNode())
8263 assert(AddcNode->getNumValues() == 2 &&
8264 AddcNode->getValueType(0) == MVT::i32 &&
8265 "Expect ADDC with two result values. First: i32");
8267 // Check that we have a glued ADDC node.
8268 if (AddcNode->getValueType(1) != MVT::Glue)
8271 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8272 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8273 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8274 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8275 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8278 // Look for the glued ADDE.
8279 SDNode* AddeNode = AddcNode->getGluedUser();
8280 if (AddeNode == NULL)
8283 // Make sure it is really an ADDE.
8284 if (AddeNode->getOpcode() != ISD::ADDE)
8287 assert(AddeNode->getNumOperands() == 3 &&
8288 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8289 "ADDE node has the wrong inputs");
8291 // Check for the triangle shape.
8292 SDValue AddeOp0 = AddeNode->getOperand(0);
8293 SDValue AddeOp1 = AddeNode->getOperand(1);
8295 // Make sure that the ADDE operands are not coming from the same node.
8296 if (AddeOp0.getNode() == AddeOp1.getNode())
8299 // Find the MUL_LOHI node walking up ADDE's operands.
8300 bool IsLeftOperandMUL = false;
8301 SDValue MULOp = findMUL_LOHI(AddeOp0);
8302 if (MULOp == SDValue())
8303 MULOp = findMUL_LOHI(AddeOp1);
8305 IsLeftOperandMUL = true;
8306 if (MULOp == SDValue())
8309 // Figure out the right opcode.
8310 unsigned Opc = MULOp->getOpcode();
8311 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8313 // Figure out the high and low input values to the MLAL node.
8314 SDValue* HiMul = &MULOp;
8315 SDValue* HiAdd = NULL;
8316 SDValue* LoMul = NULL;
8317 SDValue* LowAdd = NULL;
8319 if (IsLeftOperandMUL)
8325 if (AddcOp0->getOpcode() == Opc) {
8329 if (AddcOp1->getOpcode() == Opc) {
8337 if (LoMul->getNode() != HiMul->getNode())
8340 // Create the merged node.
8341 SelectionDAG &DAG = DCI.DAG;
8343 // Build operand list.
8344 SmallVector<SDValue, 8> Ops;
8345 Ops.push_back(LoMul->getOperand(0));
8346 Ops.push_back(LoMul->getOperand(1));
8347 Ops.push_back(*LowAdd);
8348 Ops.push_back(*HiAdd);
8350 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8351 DAG.getVTList(MVT::i32, MVT::i32),
8352 &Ops[0], Ops.size());
8354 // Replace the ADDs' nodes uses by the MLA node's values.
8355 SDValue HiMLALResult(MLALNode.getNode(), 1);
8356 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8358 SDValue LoMLALResult(MLALNode.getNode(), 0);
8359 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8361 // Return original node to notify the driver to stop replacing.
8362 SDValue resNode(AddcNode, 0);
8366 /// PerformADDCCombine - Target-specific dag combine transform from
8367 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8368 static SDValue PerformADDCCombine(SDNode *N,
8369 TargetLowering::DAGCombinerInfo &DCI,
8370 const ARMSubtarget *Subtarget) {
8372 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8376 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8377 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8378 /// called with the default operands, and if that fails, with commuted
8380 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8381 TargetLowering::DAGCombinerInfo &DCI,
8382 const ARMSubtarget *Subtarget){
8384 // Attempt to create vpaddl for this add.
8385 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8386 if (Result.getNode())
8389 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8390 if (N0.getNode()->hasOneUse()) {
8391 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8392 if (Result.getNode()) return Result;
8397 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8399 static SDValue PerformADDCombine(SDNode *N,
8400 TargetLowering::DAGCombinerInfo &DCI,
8401 const ARMSubtarget *Subtarget) {
8402 SDValue N0 = N->getOperand(0);
8403 SDValue N1 = N->getOperand(1);
8405 // First try with the default operand order.
8406 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8407 if (Result.getNode())
8410 // If that didn't work, try again with the operands commuted.
8411 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8414 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8416 static SDValue PerformSUBCombine(SDNode *N,
8417 TargetLowering::DAGCombinerInfo &DCI) {
8418 SDValue N0 = N->getOperand(0);
8419 SDValue N1 = N->getOperand(1);
8421 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8422 if (N1.getNode()->hasOneUse()) {
8423 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8424 if (Result.getNode()) return Result;
8430 /// PerformVMULCombine
8431 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8432 /// special multiplier accumulator forwarding.
8438 // However, for (A + B) * (A + B),
8445 static SDValue PerformVMULCombine(SDNode *N,
8446 TargetLowering::DAGCombinerInfo &DCI,
8447 const ARMSubtarget *Subtarget) {
8448 if (!Subtarget->hasVMLxForwarding())
8451 SelectionDAG &DAG = DCI.DAG;
8452 SDValue N0 = N->getOperand(0);
8453 SDValue N1 = N->getOperand(1);
8454 unsigned Opcode = N0.getOpcode();
8455 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8456 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8457 Opcode = N1.getOpcode();
8458 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8459 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8467 EVT VT = N->getValueType(0);
8469 SDValue N00 = N0->getOperand(0);
8470 SDValue N01 = N0->getOperand(1);
8471 return DAG.getNode(Opcode, DL, VT,
8472 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8473 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8476 static SDValue PerformMULCombine(SDNode *N,
8477 TargetLowering::DAGCombinerInfo &DCI,
8478 const ARMSubtarget *Subtarget) {
8479 SelectionDAG &DAG = DCI.DAG;
8481 if (Subtarget->isThumb1Only())
8484 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8487 EVT VT = N->getValueType(0);
8488 if (VT.is64BitVector() || VT.is128BitVector())
8489 return PerformVMULCombine(N, DCI, Subtarget);
8493 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8497 int64_t MulAmt = C->getSExtValue();
8498 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8500 ShiftAmt = ShiftAmt & (32 - 1);
8501 SDValue V = N->getOperand(0);
8505 MulAmt >>= ShiftAmt;
8508 if (isPowerOf2_32(MulAmt - 1)) {
8509 // (mul x, 2^N + 1) => (add (shl x, N), x)
8510 Res = DAG.getNode(ISD::ADD, DL, VT,
8512 DAG.getNode(ISD::SHL, DL, VT,
8514 DAG.getConstant(Log2_32(MulAmt - 1),
8516 } else if (isPowerOf2_32(MulAmt + 1)) {
8517 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8518 Res = DAG.getNode(ISD::SUB, DL, VT,
8519 DAG.getNode(ISD::SHL, DL, VT,
8521 DAG.getConstant(Log2_32(MulAmt + 1),
8527 uint64_t MulAmtAbs = -MulAmt;
8528 if (isPowerOf2_32(MulAmtAbs + 1)) {
8529 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8530 Res = DAG.getNode(ISD::SUB, DL, VT,
8532 DAG.getNode(ISD::SHL, DL, VT,
8534 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8536 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8537 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8538 Res = DAG.getNode(ISD::ADD, DL, VT,
8540 DAG.getNode(ISD::SHL, DL, VT,
8542 DAG.getConstant(Log2_32(MulAmtAbs-1),
8544 Res = DAG.getNode(ISD::SUB, DL, VT,
8545 DAG.getConstant(0, MVT::i32),Res);
8552 Res = DAG.getNode(ISD::SHL, DL, VT,
8553 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8555 // Do not add new nodes to DAG combiner worklist.
8556 DCI.CombineTo(N, Res, false);
8560 static SDValue PerformANDCombine(SDNode *N,
8561 TargetLowering::DAGCombinerInfo &DCI,
8562 const ARMSubtarget *Subtarget) {
8564 // Attempt to use immediate-form VBIC
8565 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8567 EVT VT = N->getValueType(0);
8568 SelectionDAG &DAG = DCI.DAG;
8570 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8573 APInt SplatBits, SplatUndef;
8574 unsigned SplatBitSize;
8577 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8578 if (SplatBitSize <= 64) {
8580 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8581 SplatUndef.getZExtValue(), SplatBitSize,
8582 DAG, VbicVT, VT.is128BitVector(),
8584 if (Val.getNode()) {
8586 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8587 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8588 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8593 if (!Subtarget->isThumb1Only()) {
8594 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8595 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8596 if (Result.getNode())
8603 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8604 static SDValue PerformORCombine(SDNode *N,
8605 TargetLowering::DAGCombinerInfo &DCI,
8606 const ARMSubtarget *Subtarget) {
8607 // Attempt to use immediate-form VORR
8608 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8610 EVT VT = N->getValueType(0);
8611 SelectionDAG &DAG = DCI.DAG;
8613 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8616 APInt SplatBits, SplatUndef;
8617 unsigned SplatBitSize;
8619 if (BVN && Subtarget->hasNEON() &&
8620 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8621 if (SplatBitSize <= 64) {
8623 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8624 SplatUndef.getZExtValue(), SplatBitSize,
8625 DAG, VorrVT, VT.is128BitVector(),
8627 if (Val.getNode()) {
8629 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8630 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8631 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8636 if (!Subtarget->isThumb1Only()) {
8637 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8638 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8639 if (Result.getNode())
8643 // The code below optimizes (or (and X, Y), Z).
8644 // The AND operand needs to have a single user to make these optimizations
8646 SDValue N0 = N->getOperand(0);
8647 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8649 SDValue N1 = N->getOperand(1);
8651 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8652 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8653 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8655 unsigned SplatBitSize;
8658 APInt SplatBits0, SplatBits1;
8659 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8660 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8661 // Ensure that the second operand of both ands are constants
8662 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8663 HasAnyUndefs) && !HasAnyUndefs) {
8664 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8665 HasAnyUndefs) && !HasAnyUndefs) {
8666 // Ensure that the bit width of the constants are the same and that
8667 // the splat arguments are logical inverses as per the pattern we
8668 // are trying to simplify.
8669 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8670 SplatBits0 == ~SplatBits1) {
8671 // Canonicalize the vector type to make instruction selection
8673 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8674 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8678 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8684 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8687 // BFI is only available on V6T2+
8688 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8692 // 1) or (and A, mask), val => ARMbfi A, val, mask
8693 // iff (val & mask) == val
8695 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8696 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8697 // && mask == ~mask2
8698 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8699 // && ~mask == mask2
8700 // (i.e., copy a bitfield value into another bitfield of the same width)
8705 SDValue N00 = N0.getOperand(0);
8707 // The value and the mask need to be constants so we can verify this is
8708 // actually a bitfield set. If the mask is 0xffff, we can do better
8709 // via a movt instruction, so don't use BFI in that case.
8710 SDValue MaskOp = N0.getOperand(1);
8711 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8714 unsigned Mask = MaskC->getZExtValue();
8718 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8719 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8721 unsigned Val = N1C->getZExtValue();
8722 if ((Val & ~Mask) != Val)
8725 if (ARM::isBitFieldInvertedMask(Mask)) {
8726 Val >>= countTrailingZeros(~Mask);
8728 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8729 DAG.getConstant(Val, MVT::i32),
8730 DAG.getConstant(Mask, MVT::i32));
8732 // Do not add new nodes to DAG combiner worklist.
8733 DCI.CombineTo(N, Res, false);
8736 } else if (N1.getOpcode() == ISD::AND) {
8737 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8738 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8741 unsigned Mask2 = N11C->getZExtValue();
8743 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8745 if (ARM::isBitFieldInvertedMask(Mask) &&
8747 // The pack halfword instruction works better for masks that fit it,
8748 // so use that when it's available.
8749 if (Subtarget->hasT2ExtractPack() &&
8750 (Mask == 0xffff || Mask == 0xffff0000))
8753 unsigned amt = countTrailingZeros(Mask2);
8754 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8755 DAG.getConstant(amt, MVT::i32));
8756 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8757 DAG.getConstant(Mask, MVT::i32));
8758 // Do not add new nodes to DAG combiner worklist.
8759 DCI.CombineTo(N, Res, false);
8761 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8763 // The pack halfword instruction works better for masks that fit it,
8764 // so use that when it's available.
8765 if (Subtarget->hasT2ExtractPack() &&
8766 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8769 unsigned lsb = countTrailingZeros(Mask);
8770 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8771 DAG.getConstant(lsb, MVT::i32));
8772 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8773 DAG.getConstant(Mask2, MVT::i32));
8774 // Do not add new nodes to DAG combiner worklist.
8775 DCI.CombineTo(N, Res, false);
8780 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8781 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8782 ARM::isBitFieldInvertedMask(~Mask)) {
8783 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8784 // where lsb(mask) == #shamt and masked bits of B are known zero.
8785 SDValue ShAmt = N00.getOperand(1);
8786 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8787 unsigned LSB = countTrailingZeros(Mask);
8791 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8792 DAG.getConstant(~Mask, MVT::i32));
8794 // Do not add new nodes to DAG combiner worklist.
8795 DCI.CombineTo(N, Res, false);
8801 static SDValue PerformXORCombine(SDNode *N,
8802 TargetLowering::DAGCombinerInfo &DCI,
8803 const ARMSubtarget *Subtarget) {
8804 EVT VT = N->getValueType(0);
8805 SelectionDAG &DAG = DCI.DAG;
8807 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8810 if (!Subtarget->isThumb1Only()) {
8811 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8812 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8813 if (Result.getNode())
8820 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8821 /// the bits being cleared by the AND are not demanded by the BFI.
8822 static SDValue PerformBFICombine(SDNode *N,
8823 TargetLowering::DAGCombinerInfo &DCI) {
8824 SDValue N1 = N->getOperand(1);
8825 if (N1.getOpcode() == ISD::AND) {
8826 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8829 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8830 unsigned LSB = countTrailingZeros(~InvMask);
8831 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8832 unsigned Mask = (1 << Width)-1;
8833 unsigned Mask2 = N11C->getZExtValue();
8834 if ((Mask & (~Mask2)) == 0)
8835 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8836 N->getOperand(0), N1.getOperand(0),
8842 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8843 /// ARMISD::VMOVRRD.
8844 static SDValue PerformVMOVRRDCombine(SDNode *N,
8845 TargetLowering::DAGCombinerInfo &DCI) {
8846 // vmovrrd(vmovdrr x, y) -> x,y
8847 SDValue InDouble = N->getOperand(0);
8848 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8849 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8851 // vmovrrd(load f64) -> (load i32), (load i32)
8852 SDNode *InNode = InDouble.getNode();
8853 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8854 InNode->getValueType(0) == MVT::f64 &&
8855 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8856 !cast<LoadSDNode>(InNode)->isVolatile()) {
8857 // TODO: Should this be done for non-FrameIndex operands?
8858 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8860 SelectionDAG &DAG = DCI.DAG;
8862 SDValue BasePtr = LD->getBasePtr();
8863 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8864 LD->getPointerInfo(), LD->isVolatile(),
8865 LD->isNonTemporal(), LD->isInvariant(),
8866 LD->getAlignment());
8868 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8869 DAG.getConstant(4, MVT::i32));
8870 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8871 LD->getPointerInfo(), LD->isVolatile(),
8872 LD->isNonTemporal(), LD->isInvariant(),
8873 std::min(4U, LD->getAlignment() / 2));
8875 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8876 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8877 DCI.RemoveFromWorklist(LD);
8885 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8886 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8887 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8888 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8889 SDValue Op0 = N->getOperand(0);
8890 SDValue Op1 = N->getOperand(1);
8891 if (Op0.getOpcode() == ISD::BITCAST)
8892 Op0 = Op0.getOperand(0);
8893 if (Op1.getOpcode() == ISD::BITCAST)
8894 Op1 = Op1.getOperand(0);
8895 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8896 Op0.getNode() == Op1.getNode() &&
8897 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8898 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8899 N->getValueType(0), Op0.getOperand(0));
8903 /// PerformSTORECombine - Target-specific dag combine xforms for
8905 static SDValue PerformSTORECombine(SDNode *N,
8906 TargetLowering::DAGCombinerInfo &DCI) {
8907 StoreSDNode *St = cast<StoreSDNode>(N);
8908 if (St->isVolatile())
8911 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8912 // pack all of the elements in one place. Next, store to memory in fewer
8914 SDValue StVal = St->getValue();
8915 EVT VT = StVal.getValueType();
8916 if (St->isTruncatingStore() && VT.isVector()) {
8917 SelectionDAG &DAG = DCI.DAG;
8918 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8919 EVT StVT = St->getMemoryVT();
8920 unsigned NumElems = VT.getVectorNumElements();
8921 assert(StVT != VT && "Cannot truncate to the same type");
8922 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8923 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8925 // From, To sizes and ElemCount must be pow of two
8926 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8928 // We are going to use the original vector elt for storing.
8929 // Accumulated smaller vector elements must be a multiple of the store size.
8930 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8932 unsigned SizeRatio = FromEltSz / ToEltSz;
8933 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8935 // Create a type on which we perform the shuffle.
8936 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8937 NumElems*SizeRatio);
8938 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8941 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8942 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8943 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8945 // Can't shuffle using an illegal type.
8946 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8948 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8949 DAG.getUNDEF(WideVec.getValueType()),
8951 // At this point all of the data is stored at the bottom of the
8952 // register. We now need to save it to mem.
8954 // Find the largest store unit
8955 MVT StoreType = MVT::i8;
8956 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8957 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8958 MVT Tp = (MVT::SimpleValueType)tp;
8959 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8962 // Didn't find a legal store type.
8963 if (!TLI.isTypeLegal(StoreType))
8966 // Bitcast the original vector into a vector of store-size units
8967 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8968 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8969 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8970 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8971 SmallVector<SDValue, 8> Chains;
8972 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8973 TLI.getPointerTy());
8974 SDValue BasePtr = St->getBasePtr();
8976 // Perform one or more big stores into memory.
8977 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8978 for (unsigned I = 0; I < E; I++) {
8979 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8980 StoreType, ShuffWide,
8981 DAG.getIntPtrConstant(I));
8982 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8983 St->getPointerInfo(), St->isVolatile(),
8984 St->isNonTemporal(), St->getAlignment());
8985 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8987 Chains.push_back(Ch);
8989 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8993 if (!ISD::isNormalStore(St))
8996 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8997 // ARM stores of arguments in the same cache line.
8998 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8999 StVal.getNode()->hasOneUse()) {
9000 SelectionDAG &DAG = DCI.DAG;
9002 SDValue BasePtr = St->getBasePtr();
9003 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9004 StVal.getNode()->getOperand(0), BasePtr,
9005 St->getPointerInfo(), St->isVolatile(),
9006 St->isNonTemporal(), St->getAlignment());
9008 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9009 DAG.getConstant(4, MVT::i32));
9010 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9011 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9012 St->isNonTemporal(),
9013 std::min(4U, St->getAlignment() / 2));
9016 if (StVal.getValueType() != MVT::i64 ||
9017 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9020 // Bitcast an i64 store extracted from a vector to f64.
9021 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9022 SelectionDAG &DAG = DCI.DAG;
9024 SDValue IntVec = StVal.getOperand(0);
9025 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9026 IntVec.getValueType().getVectorNumElements());
9027 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9028 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9029 Vec, StVal.getOperand(1));
9031 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9032 // Make the DAGCombiner fold the bitcasts.
9033 DCI.AddToWorklist(Vec.getNode());
9034 DCI.AddToWorklist(ExtElt.getNode());
9035 DCI.AddToWorklist(V.getNode());
9036 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9037 St->getPointerInfo(), St->isVolatile(),
9038 St->isNonTemporal(), St->getAlignment(),
9042 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9043 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9044 /// i64 vector to have f64 elements, since the value can then be loaded
9045 /// directly into a VFP register.
9046 static bool hasNormalLoadOperand(SDNode *N) {
9047 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9048 for (unsigned i = 0; i < NumElts; ++i) {
9049 SDNode *Elt = N->getOperand(i).getNode();
9050 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9056 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9057 /// ISD::BUILD_VECTOR.
9058 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9059 TargetLowering::DAGCombinerInfo &DCI){
9060 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9061 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9062 // into a pair of GPRs, which is fine when the value is used as a scalar,
9063 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9064 SelectionDAG &DAG = DCI.DAG;
9065 if (N->getNumOperands() == 2) {
9066 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9071 // Load i64 elements as f64 values so that type legalization does not split
9072 // them up into i32 values.
9073 EVT VT = N->getValueType(0);
9074 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9077 SmallVector<SDValue, 8> Ops;
9078 unsigned NumElts = VT.getVectorNumElements();
9079 for (unsigned i = 0; i < NumElts; ++i) {
9080 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9082 // Make the DAGCombiner fold the bitcast.
9083 DCI.AddToWorklist(V.getNode());
9085 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9086 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9087 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9090 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9092 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9093 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9094 // At that time, we may have inserted bitcasts from integer to float.
9095 // If these bitcasts have survived DAGCombine, change the lowering of this
9096 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9097 // force to use floating point types.
9099 // Make sure we can change the type of the vector.
9100 // This is possible iff:
9101 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9102 // 1.1. Vector is used only once.
9103 // 1.2. Use is a bit convert to an integer type.
9104 // 2. The size of its operands are 32-bits (64-bits are not legal).
9105 EVT VT = N->getValueType(0);
9106 EVT EltVT = VT.getVectorElementType();
9108 // Check 1.1. and 2.
9109 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9112 // By construction, the input type must be float.
9113 assert(EltVT == MVT::f32 && "Unexpected type!");
9116 SDNode *Use = *N->use_begin();
9117 if (Use->getOpcode() != ISD::BITCAST ||
9118 Use->getValueType(0).isFloatingPoint())
9121 // Check profitability.
9122 // Model is, if more than half of the relevant operands are bitcast from
9123 // i32, turn the build_vector into a sequence of insert_vector_elt.
9124 // Relevant operands are everything that is not statically
9125 // (i.e., at compile time) bitcasted.
9126 unsigned NumOfBitCastedElts = 0;
9127 unsigned NumElts = VT.getVectorNumElements();
9128 unsigned NumOfRelevantElts = NumElts;
9129 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9130 SDValue Elt = N->getOperand(Idx);
9131 if (Elt->getOpcode() == ISD::BITCAST) {
9132 // Assume only bit cast to i32 will go away.
9133 if (Elt->getOperand(0).getValueType() == MVT::i32)
9134 ++NumOfBitCastedElts;
9135 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9136 // Constants are statically casted, thus do not count them as
9137 // relevant operands.
9138 --NumOfRelevantElts;
9141 // Check if more than half of the elements require a non-free bitcast.
9142 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9145 SelectionDAG &DAG = DCI.DAG;
9146 // Create the new vector type.
9147 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9148 // Check if the type is legal.
9149 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9150 if (!TLI.isTypeLegal(VecVT))
9154 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9155 // => BITCAST INSERT_VECTOR_ELT
9156 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9158 SDValue Vec = DAG.getUNDEF(VecVT);
9160 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9161 SDValue V = N->getOperand(Idx);
9162 if (V.getOpcode() == ISD::UNDEF)
9164 if (V.getOpcode() == ISD::BITCAST &&
9165 V->getOperand(0).getValueType() == MVT::i32)
9166 // Fold obvious case.
9167 V = V.getOperand(0);
9169 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9170 // Make the DAGCombiner fold the bitcasts.
9171 DCI.AddToWorklist(V.getNode());
9173 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9174 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9176 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9177 // Make the DAGCombiner fold the bitcasts.
9178 DCI.AddToWorklist(Vec.getNode());
9182 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9183 /// ISD::INSERT_VECTOR_ELT.
9184 static SDValue PerformInsertEltCombine(SDNode *N,
9185 TargetLowering::DAGCombinerInfo &DCI) {
9186 // Bitcast an i64 load inserted into a vector to f64.
9187 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9188 EVT VT = N->getValueType(0);
9189 SDNode *Elt = N->getOperand(1).getNode();
9190 if (VT.getVectorElementType() != MVT::i64 ||
9191 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9194 SelectionDAG &DAG = DCI.DAG;
9196 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9197 VT.getVectorNumElements());
9198 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9199 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9200 // Make the DAGCombiner fold the bitcasts.
9201 DCI.AddToWorklist(Vec.getNode());
9202 DCI.AddToWorklist(V.getNode());
9203 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9204 Vec, V, N->getOperand(2));
9205 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9208 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9209 /// ISD::VECTOR_SHUFFLE.
9210 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9211 // The LLVM shufflevector instruction does not require the shuffle mask
9212 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9213 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9214 // operands do not match the mask length, they are extended by concatenating
9215 // them with undef vectors. That is probably the right thing for other
9216 // targets, but for NEON it is better to concatenate two double-register
9217 // size vector operands into a single quad-register size vector. Do that
9218 // transformation here:
9219 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9220 // shuffle(concat(v1, v2), undef)
9221 SDValue Op0 = N->getOperand(0);
9222 SDValue Op1 = N->getOperand(1);
9223 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9224 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9225 Op0.getNumOperands() != 2 ||
9226 Op1.getNumOperands() != 2)
9228 SDValue Concat0Op1 = Op0.getOperand(1);
9229 SDValue Concat1Op1 = Op1.getOperand(1);
9230 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9231 Concat1Op1.getOpcode() != ISD::UNDEF)
9233 // Skip the transformation if any of the types are illegal.
9234 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9235 EVT VT = N->getValueType(0);
9236 if (!TLI.isTypeLegal(VT) ||
9237 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9238 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9241 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9242 Op0.getOperand(0), Op1.getOperand(0));
9243 // Translate the shuffle mask.
9244 SmallVector<int, 16> NewMask;
9245 unsigned NumElts = VT.getVectorNumElements();
9246 unsigned HalfElts = NumElts/2;
9247 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9248 for (unsigned n = 0; n < NumElts; ++n) {
9249 int MaskElt = SVN->getMaskElt(n);
9251 if (MaskElt < (int)HalfElts)
9253 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9254 NewElt = HalfElts + MaskElt - NumElts;
9255 NewMask.push_back(NewElt);
9257 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9258 DAG.getUNDEF(VT), NewMask.data());
9261 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9262 /// NEON load/store intrinsics to merge base address updates.
9263 static SDValue CombineBaseUpdate(SDNode *N,
9264 TargetLowering::DAGCombinerInfo &DCI) {
9265 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9268 SelectionDAG &DAG = DCI.DAG;
9269 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9270 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9271 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9272 SDValue Addr = N->getOperand(AddrOpIdx);
9274 // Search for a use of the address operand that is an increment.
9275 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9276 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9278 if (User->getOpcode() != ISD::ADD ||
9279 UI.getUse().getResNo() != Addr.getResNo())
9282 // Check that the add is independent of the load/store. Otherwise, folding
9283 // it would create a cycle.
9284 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9287 // Find the new opcode for the updating load/store.
9289 bool isLaneOp = false;
9290 unsigned NewOpc = 0;
9291 unsigned NumVecs = 0;
9293 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9295 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9296 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9298 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9300 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9302 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9304 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9305 NumVecs = 2; isLaneOp = true; break;
9306 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9307 NumVecs = 3; isLaneOp = true; break;
9308 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9309 NumVecs = 4; isLaneOp = true; break;
9310 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9311 NumVecs = 1; isLoad = false; break;
9312 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9313 NumVecs = 2; isLoad = false; break;
9314 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9315 NumVecs = 3; isLoad = false; break;
9316 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9317 NumVecs = 4; isLoad = false; break;
9318 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9319 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9320 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9321 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9322 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9323 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9327 switch (N->getOpcode()) {
9328 default: llvm_unreachable("unexpected opcode for Neon base update");
9329 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9330 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9331 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9335 // Find the size of memory referenced by the load/store.
9338 VecTy = N->getValueType(0);
9340 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9341 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9343 NumBytes /= VecTy.getVectorNumElements();
9345 // If the increment is a constant, it must match the memory ref size.
9346 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9347 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9348 uint64_t IncVal = CInc->getZExtValue();
9349 if (IncVal != NumBytes)
9351 } else if (NumBytes >= 3 * 16) {
9352 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9353 // separate instructions that make it harder to use a non-constant update.
9357 // Create the new updating load/store node.
9359 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9361 for (n = 0; n < NumResultVecs; ++n)
9363 Tys[n++] = MVT::i32;
9364 Tys[n] = MVT::Other;
9365 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9366 SmallVector<SDValue, 8> Ops;
9367 Ops.push_back(N->getOperand(0)); // incoming chain
9368 Ops.push_back(N->getOperand(AddrOpIdx));
9370 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9371 Ops.push_back(N->getOperand(i));
9373 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9374 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9375 Ops.data(), Ops.size(),
9376 MemInt->getMemoryVT(),
9377 MemInt->getMemOperand());
9380 std::vector<SDValue> NewResults;
9381 for (unsigned i = 0; i < NumResultVecs; ++i) {
9382 NewResults.push_back(SDValue(UpdN.getNode(), i));
9384 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9385 DCI.CombineTo(N, NewResults);
9386 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9393 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9394 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9395 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9397 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9398 SelectionDAG &DAG = DCI.DAG;
9399 EVT VT = N->getValueType(0);
9400 // vldN-dup instructions only support 64-bit vectors for N > 1.
9401 if (!VT.is64BitVector())
9404 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9405 SDNode *VLD = N->getOperand(0).getNode();
9406 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9408 unsigned NumVecs = 0;
9409 unsigned NewOpc = 0;
9410 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9411 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9413 NewOpc = ARMISD::VLD2DUP;
9414 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9416 NewOpc = ARMISD::VLD3DUP;
9417 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9419 NewOpc = ARMISD::VLD4DUP;
9424 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9425 // numbers match the load.
9426 unsigned VLDLaneNo =
9427 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9428 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9430 // Ignore uses of the chain result.
9431 if (UI.getUse().getResNo() == NumVecs)
9434 if (User->getOpcode() != ARMISD::VDUPLANE ||
9435 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9439 // Create the vldN-dup node.
9442 for (n = 0; n < NumVecs; ++n)
9444 Tys[n] = MVT::Other;
9445 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9446 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9447 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9448 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9449 Ops, 2, VLDMemInt->getMemoryVT(),
9450 VLDMemInt->getMemOperand());
9453 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9455 unsigned ResNo = UI.getUse().getResNo();
9456 // Ignore uses of the chain result.
9457 if (ResNo == NumVecs)
9460 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9463 // Now the vldN-lane intrinsic is dead except for its chain result.
9464 // Update uses of the chain.
9465 std::vector<SDValue> VLDDupResults;
9466 for (unsigned n = 0; n < NumVecs; ++n)
9467 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9468 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9469 DCI.CombineTo(VLD, VLDDupResults);
9474 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9475 /// ARMISD::VDUPLANE.
9476 static SDValue PerformVDUPLANECombine(SDNode *N,
9477 TargetLowering::DAGCombinerInfo &DCI) {
9478 SDValue Op = N->getOperand(0);
9480 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9481 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9482 if (CombineVLDDUP(N, DCI))
9483 return SDValue(N, 0);
9485 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9486 // redundant. Ignore bit_converts for now; element sizes are checked below.
9487 while (Op.getOpcode() == ISD::BITCAST)
9488 Op = Op.getOperand(0);
9489 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9492 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9493 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9494 // The canonical VMOV for a zero vector uses a 32-bit element size.
9495 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9497 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9499 EVT VT = N->getValueType(0);
9500 if (EltSize > VT.getVectorElementType().getSizeInBits())
9503 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9506 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9507 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9508 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9512 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9514 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9519 APFloat APF = C->getValueAPF();
9520 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9521 != APFloat::opOK || !isExact)
9524 c0 = (I == 0) ? cN : c0;
9525 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9532 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9533 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9534 /// when the VMUL has a constant operand that is a power of 2.
9536 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9537 /// vmul.f32 d16, d17, d16
9538 /// vcvt.s32.f32 d16, d16
9540 /// vcvt.s32.f32 d16, d16, #3
9541 static SDValue PerformVCVTCombine(SDNode *N,
9542 TargetLowering::DAGCombinerInfo &DCI,
9543 const ARMSubtarget *Subtarget) {
9544 SelectionDAG &DAG = DCI.DAG;
9545 SDValue Op = N->getOperand(0);
9547 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9548 Op.getOpcode() != ISD::FMUL)
9552 SDValue N0 = Op->getOperand(0);
9553 SDValue ConstVec = Op->getOperand(1);
9554 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9556 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9557 !isConstVecPow2(ConstVec, isSigned, C))
9560 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9561 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9562 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9563 // These instructions only exist converting from f32 to i32. We can handle
9564 // smaller integers by generating an extra truncate, but larger ones would
9569 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9570 Intrinsic::arm_neon_vcvtfp2fxu;
9571 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9572 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9573 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9574 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9575 DAG.getConstant(Log2_64(C), MVT::i32));
9577 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9578 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9583 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9584 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9585 /// when the VDIV has a constant operand that is a power of 2.
9587 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9588 /// vcvt.f32.s32 d16, d16
9589 /// vdiv.f32 d16, d17, d16
9591 /// vcvt.f32.s32 d16, d16, #3
9592 static SDValue PerformVDIVCombine(SDNode *N,
9593 TargetLowering::DAGCombinerInfo &DCI,
9594 const ARMSubtarget *Subtarget) {
9595 SelectionDAG &DAG = DCI.DAG;
9596 SDValue Op = N->getOperand(0);
9597 unsigned OpOpcode = Op.getNode()->getOpcode();
9599 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9600 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9604 SDValue ConstVec = N->getOperand(1);
9605 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9607 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9608 !isConstVecPow2(ConstVec, isSigned, C))
9611 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9612 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9613 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9614 // These instructions only exist converting from i32 to f32. We can handle
9615 // smaller integers by generating an extra extend, but larger ones would
9620 SDValue ConvInput = Op.getOperand(0);
9621 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9622 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9623 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9624 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9627 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9628 Intrinsic::arm_neon_vcvtfxu2fp;
9629 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9631 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9632 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9635 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9636 /// operand of a vector shift operation, where all the elements of the
9637 /// build_vector must have the same constant integer value.
9638 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9639 // Ignore bit_converts.
9640 while (Op.getOpcode() == ISD::BITCAST)
9641 Op = Op.getOperand(0);
9642 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9643 APInt SplatBits, SplatUndef;
9644 unsigned SplatBitSize;
9646 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9647 HasAnyUndefs, ElementBits) ||
9648 SplatBitSize > ElementBits)
9650 Cnt = SplatBits.getSExtValue();
9654 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9655 /// operand of a vector shift left operation. That value must be in the range:
9656 /// 0 <= Value < ElementBits for a left shift; or
9657 /// 0 <= Value <= ElementBits for a long left shift.
9658 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9659 assert(VT.isVector() && "vector shift count is not a vector type");
9660 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9661 if (! getVShiftImm(Op, ElementBits, Cnt))
9663 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9666 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9667 /// operand of a vector shift right operation. For a shift opcode, the value
9668 /// is positive, but for an intrinsic the value count must be negative. The
9669 /// absolute value must be in the range:
9670 /// 1 <= |Value| <= ElementBits for a right shift; or
9671 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9672 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9674 assert(VT.isVector() && "vector shift count is not a vector type");
9675 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9676 if (! getVShiftImm(Op, ElementBits, Cnt))
9680 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9683 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9684 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9685 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9688 // Don't do anything for most intrinsics.
9691 // Vector shifts: check for immediate versions and lower them.
9692 // Note: This is done during DAG combining instead of DAG legalizing because
9693 // the build_vectors for 64-bit vector element shift counts are generally
9694 // not legal, and it is hard to see their values after they get legalized to
9695 // loads from a constant pool.
9696 case Intrinsic::arm_neon_vshifts:
9697 case Intrinsic::arm_neon_vshiftu:
9698 case Intrinsic::arm_neon_vshiftls:
9699 case Intrinsic::arm_neon_vshiftlu:
9700 case Intrinsic::arm_neon_vshiftn:
9701 case Intrinsic::arm_neon_vrshifts:
9702 case Intrinsic::arm_neon_vrshiftu:
9703 case Intrinsic::arm_neon_vrshiftn:
9704 case Intrinsic::arm_neon_vqshifts:
9705 case Intrinsic::arm_neon_vqshiftu:
9706 case Intrinsic::arm_neon_vqshiftsu:
9707 case Intrinsic::arm_neon_vqshiftns:
9708 case Intrinsic::arm_neon_vqshiftnu:
9709 case Intrinsic::arm_neon_vqshiftnsu:
9710 case Intrinsic::arm_neon_vqrshiftns:
9711 case Intrinsic::arm_neon_vqrshiftnu:
9712 case Intrinsic::arm_neon_vqrshiftnsu: {
9713 EVT VT = N->getOperand(1).getValueType();
9715 unsigned VShiftOpc = 0;
9718 case Intrinsic::arm_neon_vshifts:
9719 case Intrinsic::arm_neon_vshiftu:
9720 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9721 VShiftOpc = ARMISD::VSHL;
9724 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9725 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9726 ARMISD::VSHRs : ARMISD::VSHRu);
9731 case Intrinsic::arm_neon_vshiftls:
9732 case Intrinsic::arm_neon_vshiftlu:
9733 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9735 llvm_unreachable("invalid shift count for vshll intrinsic");
9737 case Intrinsic::arm_neon_vrshifts:
9738 case Intrinsic::arm_neon_vrshiftu:
9739 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9743 case Intrinsic::arm_neon_vqshifts:
9744 case Intrinsic::arm_neon_vqshiftu:
9745 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9749 case Intrinsic::arm_neon_vqshiftsu:
9750 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9752 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9754 case Intrinsic::arm_neon_vshiftn:
9755 case Intrinsic::arm_neon_vrshiftn:
9756 case Intrinsic::arm_neon_vqshiftns:
9757 case Intrinsic::arm_neon_vqshiftnu:
9758 case Intrinsic::arm_neon_vqshiftnsu:
9759 case Intrinsic::arm_neon_vqrshiftns:
9760 case Intrinsic::arm_neon_vqrshiftnu:
9761 case Intrinsic::arm_neon_vqrshiftnsu:
9762 // Narrowing shifts require an immediate right shift.
9763 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9765 llvm_unreachable("invalid shift count for narrowing vector shift "
9769 llvm_unreachable("unhandled vector shift");
9773 case Intrinsic::arm_neon_vshifts:
9774 case Intrinsic::arm_neon_vshiftu:
9775 // Opcode already set above.
9777 case Intrinsic::arm_neon_vshiftls:
9778 case Intrinsic::arm_neon_vshiftlu:
9779 if (Cnt == VT.getVectorElementType().getSizeInBits())
9780 VShiftOpc = ARMISD::VSHLLi;
9782 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9783 ARMISD::VSHLLs : ARMISD::VSHLLu);
9785 case Intrinsic::arm_neon_vshiftn:
9786 VShiftOpc = ARMISD::VSHRN; break;
9787 case Intrinsic::arm_neon_vrshifts:
9788 VShiftOpc = ARMISD::VRSHRs; break;
9789 case Intrinsic::arm_neon_vrshiftu:
9790 VShiftOpc = ARMISD::VRSHRu; break;
9791 case Intrinsic::arm_neon_vrshiftn:
9792 VShiftOpc = ARMISD::VRSHRN; break;
9793 case Intrinsic::arm_neon_vqshifts:
9794 VShiftOpc = ARMISD::VQSHLs; break;
9795 case Intrinsic::arm_neon_vqshiftu:
9796 VShiftOpc = ARMISD::VQSHLu; break;
9797 case Intrinsic::arm_neon_vqshiftsu:
9798 VShiftOpc = ARMISD::VQSHLsu; break;
9799 case Intrinsic::arm_neon_vqshiftns:
9800 VShiftOpc = ARMISD::VQSHRNs; break;
9801 case Intrinsic::arm_neon_vqshiftnu:
9802 VShiftOpc = ARMISD::VQSHRNu; break;
9803 case Intrinsic::arm_neon_vqshiftnsu:
9804 VShiftOpc = ARMISD::VQSHRNsu; break;
9805 case Intrinsic::arm_neon_vqrshiftns:
9806 VShiftOpc = ARMISD::VQRSHRNs; break;
9807 case Intrinsic::arm_neon_vqrshiftnu:
9808 VShiftOpc = ARMISD::VQRSHRNu; break;
9809 case Intrinsic::arm_neon_vqrshiftnsu:
9810 VShiftOpc = ARMISD::VQRSHRNsu; break;
9813 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9814 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9817 case Intrinsic::arm_neon_vshiftins: {
9818 EVT VT = N->getOperand(1).getValueType();
9820 unsigned VShiftOpc = 0;
9822 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9823 VShiftOpc = ARMISD::VSLI;
9824 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9825 VShiftOpc = ARMISD::VSRI;
9827 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9830 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9831 N->getOperand(1), N->getOperand(2),
9832 DAG.getConstant(Cnt, MVT::i32));
9835 case Intrinsic::arm_neon_vqrshifts:
9836 case Intrinsic::arm_neon_vqrshiftu:
9837 // No immediate versions of these to check for.
9844 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9845 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9846 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9847 /// vector element shift counts are generally not legal, and it is hard to see
9848 /// their values after they get legalized to loads from a constant pool.
9849 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9850 const ARMSubtarget *ST) {
9851 EVT VT = N->getValueType(0);
9852 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9853 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9854 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9855 SDValue N1 = N->getOperand(1);
9856 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9857 SDValue N0 = N->getOperand(0);
9858 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9859 DAG.MaskedValueIsZero(N0.getOperand(0),
9860 APInt::getHighBitsSet(32, 16)))
9861 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9865 // Nothing to be done for scalar shifts.
9866 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9867 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9870 assert(ST->hasNEON() && "unexpected vector shift");
9873 switch (N->getOpcode()) {
9874 default: llvm_unreachable("unexpected shift opcode");
9877 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9878 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9879 DAG.getConstant(Cnt, MVT::i32));
9884 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9885 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9886 ARMISD::VSHRs : ARMISD::VSHRu);
9887 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9888 DAG.getConstant(Cnt, MVT::i32));
9894 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9895 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9896 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9897 const ARMSubtarget *ST) {
9898 SDValue N0 = N->getOperand(0);
9900 // Check for sign- and zero-extensions of vector extract operations of 8-
9901 // and 16-bit vector elements. NEON supports these directly. They are
9902 // handled during DAG combining because type legalization will promote them
9903 // to 32-bit types and it is messy to recognize the operations after that.
9904 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9905 SDValue Vec = N0.getOperand(0);
9906 SDValue Lane = N0.getOperand(1);
9907 EVT VT = N->getValueType(0);
9908 EVT EltVT = N0.getValueType();
9909 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9911 if (VT == MVT::i32 &&
9912 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9913 TLI.isTypeLegal(Vec.getValueType()) &&
9914 isa<ConstantSDNode>(Lane)) {
9917 switch (N->getOpcode()) {
9918 default: llvm_unreachable("unexpected opcode");
9919 case ISD::SIGN_EXTEND:
9920 Opc = ARMISD::VGETLANEs;
9922 case ISD::ZERO_EXTEND:
9923 case ISD::ANY_EXTEND:
9924 Opc = ARMISD::VGETLANEu;
9927 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9934 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9935 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9936 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9937 const ARMSubtarget *ST) {
9938 // If the target supports NEON, try to use vmax/vmin instructions for f32
9939 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9940 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9941 // a NaN; only do the transformation when it matches that behavior.
9943 // For now only do this when using NEON for FP operations; if using VFP, it
9944 // is not obvious that the benefit outweighs the cost of switching to the
9946 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9947 N->getValueType(0) != MVT::f32)
9950 SDValue CondLHS = N->getOperand(0);
9951 SDValue CondRHS = N->getOperand(1);
9952 SDValue LHS = N->getOperand(2);
9953 SDValue RHS = N->getOperand(3);
9954 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9956 unsigned Opcode = 0;
9958 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9959 IsReversed = false; // x CC y ? x : y
9960 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9961 IsReversed = true ; // x CC y ? y : x
9975 // If LHS is NaN, an ordered comparison will be false and the result will
9976 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9977 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9978 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9979 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9981 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9982 // will return -0, so vmin can only be used for unsafe math or if one of
9983 // the operands is known to be nonzero.
9984 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9985 !DAG.getTarget().Options.UnsafeFPMath &&
9986 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9988 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9997 // If LHS is NaN, an ordered comparison will be false and the result will
9998 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9999 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10000 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10001 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10003 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10004 // will return +0, so vmax can only be used for unsafe math or if one of
10005 // the operands is known to be nonzero.
10006 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10007 !DAG.getTarget().Options.UnsafeFPMath &&
10008 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10010 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10016 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10019 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10021 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10022 SDValue Cmp = N->getOperand(4);
10023 if (Cmp.getOpcode() != ARMISD::CMPZ)
10024 // Only looking at EQ and NE cases.
10027 EVT VT = N->getValueType(0);
10029 SDValue LHS = Cmp.getOperand(0);
10030 SDValue RHS = Cmp.getOperand(1);
10031 SDValue FalseVal = N->getOperand(0);
10032 SDValue TrueVal = N->getOperand(1);
10033 SDValue ARMcc = N->getOperand(2);
10034 ARMCC::CondCodes CC =
10035 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10053 /// FIXME: Turn this into a target neutral optimization?
10055 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10056 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10057 N->getOperand(3), Cmp);
10058 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10060 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10061 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10062 N->getOperand(3), NewCmp);
10065 if (Res.getNode()) {
10066 APInt KnownZero, KnownOne;
10067 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10068 // Capture demanded bits information that would be otherwise lost.
10069 if (KnownZero == 0xfffffffe)
10070 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10071 DAG.getValueType(MVT::i1));
10072 else if (KnownZero == 0xffffff00)
10073 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10074 DAG.getValueType(MVT::i8));
10075 else if (KnownZero == 0xffff0000)
10076 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10077 DAG.getValueType(MVT::i16));
10083 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10084 DAGCombinerInfo &DCI) const {
10085 switch (N->getOpcode()) {
10087 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10088 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10089 case ISD::SUB: return PerformSUBCombine(N, DCI);
10090 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10091 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10092 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10093 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10094 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10095 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10096 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10097 case ISD::STORE: return PerformSTORECombine(N, DCI);
10098 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10099 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10100 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10101 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10102 case ISD::FP_TO_SINT:
10103 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10104 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10105 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10108 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10109 case ISD::SIGN_EXTEND:
10110 case ISD::ZERO_EXTEND:
10111 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10112 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10113 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10114 case ARMISD::VLD2DUP:
10115 case ARMISD::VLD3DUP:
10116 case ARMISD::VLD4DUP:
10117 return CombineBaseUpdate(N, DCI);
10118 case ARMISD::BUILD_VECTOR:
10119 return PerformARMBUILD_VECTORCombine(N, DCI);
10120 case ISD::INTRINSIC_VOID:
10121 case ISD::INTRINSIC_W_CHAIN:
10122 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10123 case Intrinsic::arm_neon_vld1:
10124 case Intrinsic::arm_neon_vld2:
10125 case Intrinsic::arm_neon_vld3:
10126 case Intrinsic::arm_neon_vld4:
10127 case Intrinsic::arm_neon_vld2lane:
10128 case Intrinsic::arm_neon_vld3lane:
10129 case Intrinsic::arm_neon_vld4lane:
10130 case Intrinsic::arm_neon_vst1:
10131 case Intrinsic::arm_neon_vst2:
10132 case Intrinsic::arm_neon_vst3:
10133 case Intrinsic::arm_neon_vst4:
10134 case Intrinsic::arm_neon_vst2lane:
10135 case Intrinsic::arm_neon_vst3lane:
10136 case Intrinsic::arm_neon_vst4lane:
10137 return CombineBaseUpdate(N, DCI);
10145 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10147 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10150 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10151 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10152 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10154 switch (VT.getSimpleVT().SimpleTy) {
10160 // Unaligned access can use (for example) LRDB, LRDH, LDR
10161 if (AllowsUnaligned) {
10163 *Fast = Subtarget->hasV7Ops();
10170 // For any little-endian targets with neon, we can support unaligned ld/st
10171 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10172 // A big-endian target may also explictly support unaligned accesses
10173 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10183 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10184 unsigned AlignCheck) {
10185 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10186 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10189 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10190 unsigned DstAlign, unsigned SrcAlign,
10191 bool IsMemset, bool ZeroMemset,
10193 MachineFunction &MF) const {
10194 const Function *F = MF.getFunction();
10196 // See if we can use NEON instructions for this...
10197 if ((!IsMemset || ZeroMemset) &&
10198 Subtarget->hasNEON() &&
10199 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10200 Attribute::NoImplicitFloat)) {
10203 (memOpAlign(SrcAlign, DstAlign, 16) ||
10204 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10206 } else if (Size >= 8 &&
10207 (memOpAlign(SrcAlign, DstAlign, 8) ||
10208 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10213 // Lowering to i32/i16 if the size permits.
10216 else if (Size >= 2)
10219 // Let the target-independent logic figure it out.
10223 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10224 if (Val.getOpcode() != ISD::LOAD)
10227 EVT VT1 = Val.getValueType();
10228 if (!VT1.isSimple() || !VT1.isInteger() ||
10229 !VT2.isSimple() || !VT2.isInteger())
10232 switch (VT1.getSimpleVT().SimpleTy) {
10237 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10244 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10245 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10248 if (!isTypeLegal(EVT::getEVT(Ty1)))
10251 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10253 // Assuming the caller doesn't have a zeroext or signext return parameter,
10254 // truncation all the way down to i1 is valid.
10259 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10263 unsigned Scale = 1;
10264 switch (VT.getSimpleVT().SimpleTy) {
10265 default: return false;
10280 if ((V & (Scale - 1)) != 0)
10283 return V == (V & ((1LL << 5) - 1));
10286 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10287 const ARMSubtarget *Subtarget) {
10288 bool isNeg = false;
10294 switch (VT.getSimpleVT().SimpleTy) {
10295 default: return false;
10300 // + imm12 or - imm8
10302 return V == (V & ((1LL << 8) - 1));
10303 return V == (V & ((1LL << 12) - 1));
10306 // Same as ARM mode. FIXME: NEON?
10307 if (!Subtarget->hasVFP2())
10312 return V == (V & ((1LL << 8) - 1));
10316 /// isLegalAddressImmediate - Return true if the integer value can be used
10317 /// as the offset of the target addressing mode for load / store of the
10319 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10320 const ARMSubtarget *Subtarget) {
10324 if (!VT.isSimple())
10327 if (Subtarget->isThumb1Only())
10328 return isLegalT1AddressImmediate(V, VT);
10329 else if (Subtarget->isThumb2())
10330 return isLegalT2AddressImmediate(V, VT, Subtarget);
10335 switch (VT.getSimpleVT().SimpleTy) {
10336 default: return false;
10341 return V == (V & ((1LL << 12) - 1));
10344 return V == (V & ((1LL << 8) - 1));
10347 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10352 return V == (V & ((1LL << 8) - 1));
10356 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10358 int Scale = AM.Scale;
10362 switch (VT.getSimpleVT().SimpleTy) {
10363 default: return false;
10371 Scale = Scale & ~1;
10372 return Scale == 2 || Scale == 4 || Scale == 8;
10375 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10379 // Note, we allow "void" uses (basically, uses that aren't loads or
10380 // stores), because arm allows folding a scale into many arithmetic
10381 // operations. This should be made more precise and revisited later.
10383 // Allow r << imm, but the imm has to be a multiple of two.
10384 if (Scale & 1) return false;
10385 return isPowerOf2_32(Scale);
10389 /// isLegalAddressingMode - Return true if the addressing mode represented
10390 /// by AM is legal for this target, for a load/store of the specified type.
10391 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10393 EVT VT = getValueType(Ty, true);
10394 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10397 // Can never fold addr of global into load/store.
10401 switch (AM.Scale) {
10402 case 0: // no scale reg, must be "r+i" or "r", or "i".
10405 if (Subtarget->isThumb1Only())
10409 // ARM doesn't support any R+R*scale+imm addr modes.
10413 if (!VT.isSimple())
10416 if (Subtarget->isThumb2())
10417 return isLegalT2ScaledAddressingMode(AM, VT);
10419 int Scale = AM.Scale;
10420 switch (VT.getSimpleVT().SimpleTy) {
10421 default: return false;
10425 if (Scale < 0) Scale = -Scale;
10429 return isPowerOf2_32(Scale & ~1);
10433 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10438 // Note, we allow "void" uses (basically, uses that aren't loads or
10439 // stores), because arm allows folding a scale into many arithmetic
10440 // operations. This should be made more precise and revisited later.
10442 // Allow r << imm, but the imm has to be a multiple of two.
10443 if (Scale & 1) return false;
10444 return isPowerOf2_32(Scale);
10450 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10451 /// icmp immediate, that is the target has icmp instructions which can compare
10452 /// a register against the immediate without having to materialize the
10453 /// immediate into a register.
10454 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10455 // Thumb2 and ARM modes can use cmn for negative immediates.
10456 if (!Subtarget->isThumb())
10457 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10458 if (Subtarget->isThumb2())
10459 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10460 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10461 return Imm >= 0 && Imm <= 255;
10464 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10465 /// *or sub* immediate, that is the target has add or sub instructions which can
10466 /// add a register with the immediate without having to materialize the
10467 /// immediate into a register.
10468 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10469 // Same encoding for add/sub, just flip the sign.
10470 int64_t AbsImm = llvm::abs64(Imm);
10471 if (!Subtarget->isThumb())
10472 return ARM_AM::getSOImmVal(AbsImm) != -1;
10473 if (Subtarget->isThumb2())
10474 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10475 // Thumb1 only has 8-bit unsigned immediate.
10476 return AbsImm >= 0 && AbsImm <= 255;
10479 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10480 bool isSEXTLoad, SDValue &Base,
10481 SDValue &Offset, bool &isInc,
10482 SelectionDAG &DAG) {
10483 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10486 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10487 // AddressingMode 3
10488 Base = Ptr->getOperand(0);
10489 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10490 int RHSC = (int)RHS->getZExtValue();
10491 if (RHSC < 0 && RHSC > -256) {
10492 assert(Ptr->getOpcode() == ISD::ADD);
10494 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10498 isInc = (Ptr->getOpcode() == ISD::ADD);
10499 Offset = Ptr->getOperand(1);
10501 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10502 // AddressingMode 2
10503 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10504 int RHSC = (int)RHS->getZExtValue();
10505 if (RHSC < 0 && RHSC > -0x1000) {
10506 assert(Ptr->getOpcode() == ISD::ADD);
10508 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10509 Base = Ptr->getOperand(0);
10514 if (Ptr->getOpcode() == ISD::ADD) {
10516 ARM_AM::ShiftOpc ShOpcVal=
10517 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10518 if (ShOpcVal != ARM_AM::no_shift) {
10519 Base = Ptr->getOperand(1);
10520 Offset = Ptr->getOperand(0);
10522 Base = Ptr->getOperand(0);
10523 Offset = Ptr->getOperand(1);
10528 isInc = (Ptr->getOpcode() == ISD::ADD);
10529 Base = Ptr->getOperand(0);
10530 Offset = Ptr->getOperand(1);
10534 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10538 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10539 bool isSEXTLoad, SDValue &Base,
10540 SDValue &Offset, bool &isInc,
10541 SelectionDAG &DAG) {
10542 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10545 Base = Ptr->getOperand(0);
10546 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10547 int RHSC = (int)RHS->getZExtValue();
10548 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10549 assert(Ptr->getOpcode() == ISD::ADD);
10551 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10553 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10554 isInc = Ptr->getOpcode() == ISD::ADD;
10555 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10563 /// getPreIndexedAddressParts - returns true by value, base pointer and
10564 /// offset pointer and addressing mode by reference if the node's address
10565 /// can be legally represented as pre-indexed load / store address.
10567 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10569 ISD::MemIndexedMode &AM,
10570 SelectionDAG &DAG) const {
10571 if (Subtarget->isThumb1Only())
10576 bool isSEXTLoad = false;
10577 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10578 Ptr = LD->getBasePtr();
10579 VT = LD->getMemoryVT();
10580 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10581 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10582 Ptr = ST->getBasePtr();
10583 VT = ST->getMemoryVT();
10588 bool isLegal = false;
10589 if (Subtarget->isThumb2())
10590 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10591 Offset, isInc, DAG);
10593 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10594 Offset, isInc, DAG);
10598 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10602 /// getPostIndexedAddressParts - returns true by value, base pointer and
10603 /// offset pointer and addressing mode by reference if this node can be
10604 /// combined with a load / store to form a post-indexed load / store.
10605 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10608 ISD::MemIndexedMode &AM,
10609 SelectionDAG &DAG) const {
10610 if (Subtarget->isThumb1Only())
10615 bool isSEXTLoad = false;
10616 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10617 VT = LD->getMemoryVT();
10618 Ptr = LD->getBasePtr();
10619 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10620 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10621 VT = ST->getMemoryVT();
10622 Ptr = ST->getBasePtr();
10627 bool isLegal = false;
10628 if (Subtarget->isThumb2())
10629 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10632 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10638 // Swap base ptr and offset to catch more post-index load / store when
10639 // it's legal. In Thumb2 mode, offset must be an immediate.
10640 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10641 !Subtarget->isThumb2())
10642 std::swap(Base, Offset);
10644 // Post-indexed load / store update the base pointer.
10649 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10653 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10656 const SelectionDAG &DAG,
10657 unsigned Depth) const {
10658 unsigned BitWidth = KnownOne.getBitWidth();
10659 KnownZero = KnownOne = APInt(BitWidth, 0);
10660 switch (Op.getOpcode()) {
10666 // These nodes' second result is a boolean
10667 if (Op.getResNo() == 0)
10669 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10671 case ARMISD::CMOV: {
10672 // Bits are known zero/one if known on the LHS and RHS.
10673 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10674 if (KnownZero == 0 && KnownOne == 0) return;
10676 APInt KnownZeroRHS, KnownOneRHS;
10677 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10678 KnownZero &= KnownZeroRHS;
10679 KnownOne &= KnownOneRHS;
10685 //===----------------------------------------------------------------------===//
10686 // ARM Inline Assembly Support
10687 //===----------------------------------------------------------------------===//
10689 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10690 // Looking for "rev" which is V6+.
10691 if (!Subtarget->hasV6Ops())
10694 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10695 std::string AsmStr = IA->getAsmString();
10696 SmallVector<StringRef, 4> AsmPieces;
10697 SplitString(AsmStr, AsmPieces, ";\n");
10699 switch (AsmPieces.size()) {
10700 default: return false;
10702 AsmStr = AsmPieces[0];
10704 SplitString(AsmStr, AsmPieces, " \t,");
10707 if (AsmPieces.size() == 3 &&
10708 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10709 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10710 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10711 if (Ty && Ty->getBitWidth() == 32)
10712 return IntrinsicLowering::LowerToByteSwap(CI);
10720 /// getConstraintType - Given a constraint letter, return the type of
10721 /// constraint it is for this target.
10722 ARMTargetLowering::ConstraintType
10723 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10724 if (Constraint.size() == 1) {
10725 switch (Constraint[0]) {
10727 case 'l': return C_RegisterClass;
10728 case 'w': return C_RegisterClass;
10729 case 'h': return C_RegisterClass;
10730 case 'x': return C_RegisterClass;
10731 case 't': return C_RegisterClass;
10732 case 'j': return C_Other; // Constant for movw.
10733 // An address with a single base register. Due to the way we
10734 // currently handle addresses it is the same as an 'r' memory constraint.
10735 case 'Q': return C_Memory;
10737 } else if (Constraint.size() == 2) {
10738 switch (Constraint[0]) {
10740 // All 'U+' constraints are addresses.
10741 case 'U': return C_Memory;
10744 return TargetLowering::getConstraintType(Constraint);
10747 /// Examine constraint type and operand type and determine a weight value.
10748 /// This object must already have been set up with the operand type
10749 /// and the current alternative constraint selected.
10750 TargetLowering::ConstraintWeight
10751 ARMTargetLowering::getSingleConstraintMatchWeight(
10752 AsmOperandInfo &info, const char *constraint) const {
10753 ConstraintWeight weight = CW_Invalid;
10754 Value *CallOperandVal = info.CallOperandVal;
10755 // If we don't have a value, we can't do a match,
10756 // but allow it at the lowest weight.
10757 if (CallOperandVal == NULL)
10759 Type *type = CallOperandVal->getType();
10760 // Look at the constraint type.
10761 switch (*constraint) {
10763 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10766 if (type->isIntegerTy()) {
10767 if (Subtarget->isThumb())
10768 weight = CW_SpecificReg;
10770 weight = CW_Register;
10774 if (type->isFloatingPointTy())
10775 weight = CW_Register;
10781 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10783 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10785 if (Constraint.size() == 1) {
10786 // GCC ARM Constraint Letters
10787 switch (Constraint[0]) {
10788 case 'l': // Low regs or general regs.
10789 if (Subtarget->isThumb())
10790 return RCPair(0U, &ARM::tGPRRegClass);
10791 return RCPair(0U, &ARM::GPRRegClass);
10792 case 'h': // High regs or no regs.
10793 if (Subtarget->isThumb())
10794 return RCPair(0U, &ARM::hGPRRegClass);
10797 return RCPair(0U, &ARM::GPRRegClass);
10799 if (VT == MVT::f32)
10800 return RCPair(0U, &ARM::SPRRegClass);
10801 if (VT.getSizeInBits() == 64)
10802 return RCPair(0U, &ARM::DPRRegClass);
10803 if (VT.getSizeInBits() == 128)
10804 return RCPair(0U, &ARM::QPRRegClass);
10807 if (VT == MVT::f32)
10808 return RCPair(0U, &ARM::SPR_8RegClass);
10809 if (VT.getSizeInBits() == 64)
10810 return RCPair(0U, &ARM::DPR_8RegClass);
10811 if (VT.getSizeInBits() == 128)
10812 return RCPair(0U, &ARM::QPR_8RegClass);
10815 if (VT == MVT::f32)
10816 return RCPair(0U, &ARM::SPRRegClass);
10820 if (StringRef("{cc}").equals_lower(Constraint))
10821 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10823 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10826 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10827 /// vector. If it is invalid, don't add anything to Ops.
10828 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10829 std::string &Constraint,
10830 std::vector<SDValue>&Ops,
10831 SelectionDAG &DAG) const {
10832 SDValue Result(0, 0);
10834 // Currently only support length 1 constraints.
10835 if (Constraint.length() != 1) return;
10837 char ConstraintLetter = Constraint[0];
10838 switch (ConstraintLetter) {
10841 case 'I': case 'J': case 'K': case 'L':
10842 case 'M': case 'N': case 'O':
10843 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10847 int64_t CVal64 = C->getSExtValue();
10848 int CVal = (int) CVal64;
10849 // None of these constraints allow values larger than 32 bits. Check
10850 // that the value fits in an int.
10851 if (CVal != CVal64)
10854 switch (ConstraintLetter) {
10856 // Constant suitable for movw, must be between 0 and
10858 if (Subtarget->hasV6T2Ops())
10859 if (CVal >= 0 && CVal <= 65535)
10863 if (Subtarget->isThumb1Only()) {
10864 // This must be a constant between 0 and 255, for ADD
10866 if (CVal >= 0 && CVal <= 255)
10868 } else if (Subtarget->isThumb2()) {
10869 // A constant that can be used as an immediate value in a
10870 // data-processing instruction.
10871 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10874 // A constant that can be used as an immediate value in a
10875 // data-processing instruction.
10876 if (ARM_AM::getSOImmVal(CVal) != -1)
10882 if (Subtarget->isThumb()) { // FIXME thumb2
10883 // This must be a constant between -255 and -1, for negated ADD
10884 // immediates. This can be used in GCC with an "n" modifier that
10885 // prints the negated value, for use with SUB instructions. It is
10886 // not useful otherwise but is implemented for compatibility.
10887 if (CVal >= -255 && CVal <= -1)
10890 // This must be a constant between -4095 and 4095. It is not clear
10891 // what this constraint is intended for. Implemented for
10892 // compatibility with GCC.
10893 if (CVal >= -4095 && CVal <= 4095)
10899 if (Subtarget->isThumb1Only()) {
10900 // A 32-bit value where only one byte has a nonzero value. Exclude
10901 // zero to match GCC. This constraint is used by GCC internally for
10902 // constants that can be loaded with a move/shift combination.
10903 // It is not useful otherwise but is implemented for compatibility.
10904 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10906 } else if (Subtarget->isThumb2()) {
10907 // A constant whose bitwise inverse can be used as an immediate
10908 // value in a data-processing instruction. This can be used in GCC
10909 // with a "B" modifier that prints the inverted value, for use with
10910 // BIC and MVN instructions. It is not useful otherwise but is
10911 // implemented for compatibility.
10912 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10915 // A constant whose bitwise inverse can be used as an immediate
10916 // value in a data-processing instruction. This can be used in GCC
10917 // with a "B" modifier that prints the inverted value, for use with
10918 // BIC and MVN instructions. It is not useful otherwise but is
10919 // implemented for compatibility.
10920 if (ARM_AM::getSOImmVal(~CVal) != -1)
10926 if (Subtarget->isThumb1Only()) {
10927 // This must be a constant between -7 and 7,
10928 // for 3-operand ADD/SUB immediate instructions.
10929 if (CVal >= -7 && CVal < 7)
10931 } else if (Subtarget->isThumb2()) {
10932 // A constant whose negation can be used as an immediate value in a
10933 // data-processing instruction. This can be used in GCC with an "n"
10934 // modifier that prints the negated value, for use with SUB
10935 // instructions. It is not useful otherwise but is implemented for
10937 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10940 // A constant whose negation can be used as an immediate value in a
10941 // data-processing instruction. This can be used in GCC with an "n"
10942 // modifier that prints the negated value, for use with SUB
10943 // instructions. It is not useful otherwise but is implemented for
10945 if (ARM_AM::getSOImmVal(-CVal) != -1)
10951 if (Subtarget->isThumb()) { // FIXME thumb2
10952 // This must be a multiple of 4 between 0 and 1020, for
10953 // ADD sp + immediate.
10954 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10957 // A power of two or a constant between 0 and 32. This is used in
10958 // GCC for the shift amount on shifted register operands, but it is
10959 // useful in general for any shift amounts.
10960 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10966 if (Subtarget->isThumb()) { // FIXME thumb2
10967 // This must be a constant between 0 and 31, for shift amounts.
10968 if (CVal >= 0 && CVal <= 31)
10974 if (Subtarget->isThumb()) { // FIXME thumb2
10975 // This must be a multiple of 4 between -508 and 508, for
10976 // ADD/SUB sp = sp + immediate.
10977 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10982 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10986 if (Result.getNode()) {
10987 Ops.push_back(Result);
10990 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10993 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10994 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10995 unsigned Opcode = Op->getOpcode();
10996 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10997 "Invalid opcode for Div/Rem lowering");
10998 bool isSigned = (Opcode == ISD::SDIVREM);
10999 EVT VT = Op->getValueType(0);
11000 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11003 switch (VT.getSimpleVT().SimpleTy) {
11004 default: llvm_unreachable("Unexpected request for libcall!");
11005 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11006 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11007 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11008 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11011 SDValue InChain = DAG.getEntryNode();
11013 TargetLowering::ArgListTy Args;
11014 TargetLowering::ArgListEntry Entry;
11015 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11016 EVT ArgVT = Op->getOperand(i).getValueType();
11017 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11018 Entry.Node = Op->getOperand(i);
11020 Entry.isSExt = isSigned;
11021 Entry.isZExt = !isSigned;
11022 Args.push_back(Entry);
11025 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11028 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11032 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11033 0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11034 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11035 Callee, Args, DAG, dl);
11036 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11038 return CallInfo.first;
11042 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11043 // The ARM target isn't yet aware of offsets.
11047 bool ARM::isBitFieldInvertedMask(unsigned v) {
11048 if (v == 0xffffffff)
11051 // there can be 1's on either or both "outsides", all the "inside"
11052 // bits must be 0's
11053 unsigned TO = CountTrailingOnes_32(v);
11054 unsigned LO = CountLeadingOnes_32(v);
11055 v = (v >> TO) << TO;
11056 v = (v << LO) >> LO;
11060 /// isFPImmLegal - Returns true if the target can instruction select the
11061 /// specified FP immediate natively. If false, the legalizer will
11062 /// materialize the FP immediate as a load from a constant pool.
11063 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11064 if (!Subtarget->hasVFP3())
11066 if (VT == MVT::f32)
11067 return ARM_AM::getFP32Imm(Imm) != -1;
11068 if (VT == MVT::f64)
11069 return ARM_AM::getFP64Imm(Imm) != -1;
11073 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11074 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11075 /// specified in the intrinsic calls.
11076 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11078 unsigned Intrinsic) const {
11079 switch (Intrinsic) {
11080 case Intrinsic::arm_neon_vld1:
11081 case Intrinsic::arm_neon_vld2:
11082 case Intrinsic::arm_neon_vld3:
11083 case Intrinsic::arm_neon_vld4:
11084 case Intrinsic::arm_neon_vld2lane:
11085 case Intrinsic::arm_neon_vld3lane:
11086 case Intrinsic::arm_neon_vld4lane: {
11087 Info.opc = ISD::INTRINSIC_W_CHAIN;
11088 // Conservatively set memVT to the entire set of vectors loaded.
11089 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11090 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11091 Info.ptrVal = I.getArgOperand(0);
11093 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11094 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11095 Info.vol = false; // volatile loads with NEON intrinsics not supported
11096 Info.readMem = true;
11097 Info.writeMem = false;
11100 case Intrinsic::arm_neon_vst1:
11101 case Intrinsic::arm_neon_vst2:
11102 case Intrinsic::arm_neon_vst3:
11103 case Intrinsic::arm_neon_vst4:
11104 case Intrinsic::arm_neon_vst2lane:
11105 case Intrinsic::arm_neon_vst3lane:
11106 case Intrinsic::arm_neon_vst4lane: {
11107 Info.opc = ISD::INTRINSIC_VOID;
11108 // Conservatively set memVT to the entire set of vectors stored.
11109 unsigned NumElts = 0;
11110 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11111 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11112 if (!ArgTy->isVectorTy())
11114 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11116 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11117 Info.ptrVal = I.getArgOperand(0);
11119 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11120 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11121 Info.vol = false; // volatile stores with NEON intrinsics not supported
11122 Info.readMem = false;
11123 Info.writeMem = true;
11126 case Intrinsic::arm_ldrex: {
11127 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11128 Info.opc = ISD::INTRINSIC_W_CHAIN;
11129 Info.memVT = MVT::getVT(PtrTy->getElementType());
11130 Info.ptrVal = I.getArgOperand(0);
11132 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11134 Info.readMem = true;
11135 Info.writeMem = false;
11138 case Intrinsic::arm_strex: {
11139 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11140 Info.opc = ISD::INTRINSIC_W_CHAIN;
11141 Info.memVT = MVT::getVT(PtrTy->getElementType());
11142 Info.ptrVal = I.getArgOperand(1);
11144 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11146 Info.readMem = false;
11147 Info.writeMem = true;
11150 case Intrinsic::arm_strexd: {
11151 Info.opc = ISD::INTRINSIC_W_CHAIN;
11152 Info.memVT = MVT::i64;
11153 Info.ptrVal = I.getArgOperand(2);
11157 Info.readMem = false;
11158 Info.writeMem = true;
11161 case Intrinsic::arm_ldrexd: {
11162 Info.opc = ISD::INTRINSIC_W_CHAIN;
11163 Info.memVT = MVT::i64;
11164 Info.ptrVal = I.getArgOperand(0);
11168 Info.readMem = true;
11169 Info.writeMem = false;