1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.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/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "arm-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
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 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
79 : CCState(CC, isVarArg, MF, 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 MCPhysReg 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::DPairRegClass);
159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163 const ARMSubtarget &STI)
164 : TargetLowering(TM), Subtarget(&STI) {
165 RegInfo = Subtarget->getRegisterInfo();
166 Itins = Subtarget->getInstrItineraryData();
168 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
170 if (Subtarget->isTargetMachO()) {
171 // Uses VFP for Thumb libfuncs if available.
172 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174 // Single-precision floating-point arithmetic.
175 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
176 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
177 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
178 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
180 // Double-precision floating-point arithmetic.
181 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
182 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
183 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
184 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
186 // Single-precision comparisons.
187 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
188 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
189 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
190 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
191 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
192 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
193 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
194 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
196 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
197 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
198 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
199 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
200 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
205 // Double-precision comparisons.
206 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
207 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
208 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
209 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
210 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
211 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
212 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
213 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
215 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
216 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
217 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
218 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
219 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
224 // Floating-point to integer conversions.
225 // i64 conversions are done via library routines even when generating VFP
226 // instructions, so use the same ones.
227 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
228 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
229 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
230 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
232 // Conversions between floating types.
233 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
234 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
236 // Integer to floating-point conversions.
237 // i64 conversions are done via library routines even when generating VFP
238 // instructions, so use the same ones.
239 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
240 // e.g., __floatunsidf vs. __floatunssidfvfp.
241 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
242 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
243 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
244 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
248 // These libcalls are not available in 32-bit.
249 setLibcallName(RTLIB::SHL_I128, nullptr);
250 setLibcallName(RTLIB::SRL_I128, nullptr);
251 setLibcallName(RTLIB::SRA_I128, nullptr);
253 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
254 !Subtarget->isTargetWindows()) {
255 static const struct {
256 const RTLIB::Libcall Op;
257 const char * const Name;
258 const CallingConv::ID CC;
259 const ISD::CondCode Cond;
261 // Double-precision floating-point arithmetic helper functions
262 // RTABI chapter 4.1.2, Table 2
263 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268 // Double-precision floating-point comparison helper functions
269 // RTABI chapter 4.1.2, Table 3
270 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
271 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
272 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
273 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
274 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
276 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
277 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
279 // Single-precision floating-point arithmetic helper functions
280 // RTABI chapter 4.1.2, Table 4
281 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286 // Single-precision floating-point comparison helper functions
287 // RTABI chapter 4.1.2, Table 5
288 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
289 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
290 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
291 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
292 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
294 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
295 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
297 // Floating-point to integer conversions.
298 // RTABI chapter 4.1.2, Table 6
299 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 // Conversions between floating types.
309 // RTABI chapter 4.1.2, Table 7
310 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 // Integer to floating-point conversions.
315 // RTABI chapter 4.1.2, Table 8
316 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 // Long long helper functions
326 // RTABI chapter 4.2, Table 9
327 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 // Integer division functions
333 // RTABI chapter 4.3.1
334 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 // RTABI chapter 4.3.4
345 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350 for (const auto &LC : LibraryCalls) {
351 setLibcallName(LC.Op, LC.Name);
352 setLibcallCallingConv(LC.Op, LC.CC);
353 if (LC.Cond != ISD::SETCC_INVALID)
354 setCmpLibcallCC(LC.Op, LC.Cond);
358 if (Subtarget->isTargetWindows()) {
359 static const struct {
360 const RTLIB::Libcall Op;
361 const char * const Name;
362 const CallingConv::ID CC;
364 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
366 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
371 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
374 for (const auto &LC : LibraryCalls) {
375 setLibcallName(LC.Op, LC.Name);
376 setLibcallCallingConv(LC.Op, LC.CC);
380 // Use divmod compiler-rt calls for iOS 5.0 and later.
381 if (Subtarget->getTargetTriple().isiOS() &&
382 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
383 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
384 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
387 // The half <-> float conversion functions are always soft-float, but are
388 // needed for some targets which use a hard-float calling convention by
390 if (Subtarget->isAAPCS_ABI()) {
391 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
393 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
395 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
396 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
397 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
400 if (Subtarget->isThumb1Only())
401 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
403 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
404 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
405 !Subtarget->isThumb1Only()) {
406 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
407 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
410 for (MVT VT : MVT::vector_valuetypes()) {
411 for (MVT InnerVT : MVT::vector_valuetypes()) {
412 setTruncStoreAction(VT, InnerVT, Expand);
413 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
414 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
415 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
418 setOperationAction(ISD::MULHS, VT, Expand);
419 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
420 setOperationAction(ISD::MULHU, VT, Expand);
421 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
423 setOperationAction(ISD::BSWAP, VT, Expand);
426 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
427 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
429 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
430 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
432 if (Subtarget->hasNEON()) {
433 addDRTypeForNEON(MVT::v2f32);
434 addDRTypeForNEON(MVT::v8i8);
435 addDRTypeForNEON(MVT::v4i16);
436 addDRTypeForNEON(MVT::v2i32);
437 addDRTypeForNEON(MVT::v1i64);
439 addQRTypeForNEON(MVT::v4f32);
440 addQRTypeForNEON(MVT::v2f64);
441 addQRTypeForNEON(MVT::v16i8);
442 addQRTypeForNEON(MVT::v8i16);
443 addQRTypeForNEON(MVT::v4i32);
444 addQRTypeForNEON(MVT::v2i64);
446 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
447 // neither Neon nor VFP support any arithmetic operations on it.
448 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
449 // supported for v4f32.
450 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
451 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
452 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
453 // FIXME: Code duplication: FDIV and FREM are expanded always, see
454 // ARMTargetLowering::addTypeForNEON method for details.
455 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
456 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
457 // FIXME: Create unittest.
458 // In another words, find a way when "copysign" appears in DAG with vector
460 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
461 // FIXME: Code duplication: SETCC has custom operation action, see
462 // ARMTargetLowering::addTypeForNEON method for details.
463 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
464 // FIXME: Create unittest for FNEG and for FABS.
465 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
466 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
467 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
468 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
469 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
470 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
471 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
472 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
473 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
474 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
475 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
476 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
477 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
478 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
479 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
480 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
481 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
482 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
483 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
485 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
486 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
487 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
488 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
489 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
490 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
491 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
492 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
493 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
494 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
495 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
496 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
497 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
498 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
499 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
501 // Mark v2f32 intrinsics.
502 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
503 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
504 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
505 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
506 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
507 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
508 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
509 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
510 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
511 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
512 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
513 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
514 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
515 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
516 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
518 // Neon does not support some operations on v1i64 and v2i64 types.
519 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
520 // Custom handling for some quad-vector types to detect VMULL.
521 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
522 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
523 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
524 // Custom handling for some vector types to avoid expensive expansions
525 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
526 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
527 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
528 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
529 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
530 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
531 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
532 // a destination type that is wider than the source, and nor does
533 // it have a FP_TO_[SU]INT instruction with a narrower destination than
535 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
536 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
537 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
538 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
540 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
541 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
543 // NEON does not have single instruction CTPOP for vectors with element
544 // types wider than 8-bits. However, custom lowering can leverage the
545 // v8i8/v16i8 vcnt instruction.
546 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
547 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
548 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
549 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
551 // NEON only has FMA instructions as of VFP4.
552 if (!Subtarget->hasVFP4()) {
553 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
554 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
557 setTargetDAGCombine(ISD::INTRINSIC_VOID);
558 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
559 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
560 setTargetDAGCombine(ISD::SHL);
561 setTargetDAGCombine(ISD::SRL);
562 setTargetDAGCombine(ISD::SRA);
563 setTargetDAGCombine(ISD::SIGN_EXTEND);
564 setTargetDAGCombine(ISD::ZERO_EXTEND);
565 setTargetDAGCombine(ISD::ANY_EXTEND);
566 setTargetDAGCombine(ISD::SELECT_CC);
567 setTargetDAGCombine(ISD::BUILD_VECTOR);
568 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
569 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
570 setTargetDAGCombine(ISD::STORE);
571 setTargetDAGCombine(ISD::FP_TO_SINT);
572 setTargetDAGCombine(ISD::FP_TO_UINT);
573 setTargetDAGCombine(ISD::FDIV);
574 setTargetDAGCombine(ISD::LOAD);
576 // It is legal to extload from v4i8 to v4i16 or v4i32.
577 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
579 for (MVT VT : MVT::integer_vector_valuetypes()) {
580 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
581 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
582 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
587 // ARM and Thumb2 support UMLAL/SMLAL.
588 if (!Subtarget->isThumb1Only())
589 setTargetDAGCombine(ISD::ADDC);
591 if (Subtarget->isFPOnlySP()) {
592 // When targetting a floating-point unit with only single-precision
593 // operations, f64 is legal for the few double-precision instructions which
594 // are present However, no double-precision operations other than moves,
595 // loads and stores are provided by the hardware.
596 setOperationAction(ISD::FADD, MVT::f64, Expand);
597 setOperationAction(ISD::FSUB, MVT::f64, Expand);
598 setOperationAction(ISD::FMUL, MVT::f64, Expand);
599 setOperationAction(ISD::FMA, MVT::f64, Expand);
600 setOperationAction(ISD::FDIV, MVT::f64, Expand);
601 setOperationAction(ISD::FREM, MVT::f64, Expand);
602 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
604 setOperationAction(ISD::FNEG, MVT::f64, Expand);
605 setOperationAction(ISD::FABS, MVT::f64, Expand);
606 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
607 setOperationAction(ISD::FSIN, MVT::f64, Expand);
608 setOperationAction(ISD::FCOS, MVT::f64, Expand);
609 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
610 setOperationAction(ISD::FPOW, MVT::f64, Expand);
611 setOperationAction(ISD::FLOG, MVT::f64, Expand);
612 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
613 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
614 setOperationAction(ISD::FEXP, MVT::f64, Expand);
615 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
616 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
617 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
618 setOperationAction(ISD::FRINT, MVT::f64, Expand);
619 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
620 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
621 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
622 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
623 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
624 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
625 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
626 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
627 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
628 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
631 computeRegisterProperties(Subtarget->getRegisterInfo());
633 // ARM does not have floating-point extending loads.
634 for (MVT VT : MVT::fp_valuetypes()) {
635 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
636 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
639 // ... or truncating stores
640 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
641 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
642 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
644 // ARM does not have i1 sign extending load.
645 for (MVT VT : MVT::integer_valuetypes())
646 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
648 // ARM supports all 4 flavors of integer indexed load / store.
649 if (!Subtarget->isThumb1Only()) {
650 for (unsigned im = (unsigned)ISD::PRE_INC;
651 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
652 setIndexedLoadAction(im, MVT::i1, Legal);
653 setIndexedLoadAction(im, MVT::i8, Legal);
654 setIndexedLoadAction(im, MVT::i16, Legal);
655 setIndexedLoadAction(im, MVT::i32, Legal);
656 setIndexedStoreAction(im, MVT::i1, Legal);
657 setIndexedStoreAction(im, MVT::i8, Legal);
658 setIndexedStoreAction(im, MVT::i16, Legal);
659 setIndexedStoreAction(im, MVT::i32, Legal);
663 setOperationAction(ISD::SADDO, MVT::i32, Custom);
664 setOperationAction(ISD::UADDO, MVT::i32, Custom);
665 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
666 setOperationAction(ISD::USUBO, MVT::i32, Custom);
668 // i64 operation support.
669 setOperationAction(ISD::MUL, MVT::i64, Expand);
670 setOperationAction(ISD::MULHU, MVT::i32, Expand);
671 if (Subtarget->isThumb1Only()) {
672 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
673 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
675 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
676 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
677 setOperationAction(ISD::MULHS, MVT::i32, Expand);
679 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
680 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
681 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
682 setOperationAction(ISD::SRL, MVT::i64, Custom);
683 setOperationAction(ISD::SRA, MVT::i64, Custom);
685 if (!Subtarget->isThumb1Only()) {
686 // FIXME: We should do this for Thumb1 as well.
687 setOperationAction(ISD::ADDC, MVT::i32, Custom);
688 setOperationAction(ISD::ADDE, MVT::i32, Custom);
689 setOperationAction(ISD::SUBC, MVT::i32, Custom);
690 setOperationAction(ISD::SUBE, MVT::i32, Custom);
693 // ARM does not have ROTL.
694 setOperationAction(ISD::ROTL, MVT::i32, Expand);
695 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
696 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
697 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
698 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
700 // These just redirect to CTTZ and CTLZ on ARM.
701 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
702 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
704 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
706 // Only ARMv6 has BSWAP.
707 if (!Subtarget->hasV6Ops())
708 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
710 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
711 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
712 // These are expanded into libcalls if the cpu doesn't have HW divider.
713 setOperationAction(ISD::SDIV, MVT::i32, Expand);
714 setOperationAction(ISD::UDIV, MVT::i32, Expand);
717 // FIXME: Also set divmod for SREM on EABI
718 setOperationAction(ISD::SREM, MVT::i32, Expand);
719 setOperationAction(ISD::UREM, MVT::i32, Expand);
720 // Register based DivRem for AEABI (RTABI 4.2)
721 if (Subtarget->isTargetAEABI()) {
722 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
723 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
724 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
725 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
726 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
727 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
728 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
729 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
731 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
732 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
733 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
734 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
735 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
736 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
737 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
738 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
740 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
741 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
743 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
744 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
747 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
748 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
749 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
750 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
751 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
753 setOperationAction(ISD::TRAP, MVT::Other, Legal);
755 // Use the default implementation.
756 setOperationAction(ISD::VASTART, MVT::Other, Custom);
757 setOperationAction(ISD::VAARG, MVT::Other, Expand);
758 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
759 setOperationAction(ISD::VAEND, MVT::Other, Expand);
760 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
761 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
763 if (!Subtarget->isTargetMachO()) {
764 // Non-MachO platforms may return values in these registers via the
765 // personality function.
766 setExceptionPointerRegister(ARM::R0);
767 setExceptionSelectorRegister(ARM::R1);
770 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
771 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
773 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
775 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
776 // the default expansion. If we are targeting a single threaded system,
777 // then set them all for expand so we can lower them later into their
779 if (TM.Options.ThreadModel == ThreadModel::Single)
780 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
781 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
782 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
783 // to ldrex/strex loops already.
784 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
786 // On v8, we have particularly efficient implementations of atomic fences
787 // if they can be combined with nearby atomic loads and stores.
788 if (!Subtarget->hasV8Ops()) {
789 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
790 setInsertFencesForAtomic(true);
793 // If there's anything we can use as a barrier, go through custom lowering
795 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
796 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
798 // Set them all for expansion, which will force libcalls.
799 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
800 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
801 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
802 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
803 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
804 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
805 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
806 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
807 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
808 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
809 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
810 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
811 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
812 // Unordered/Monotonic case.
813 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
814 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
817 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
819 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
820 if (!Subtarget->hasV6Ops()) {
821 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
822 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
824 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
826 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
827 !Subtarget->isThumb1Only()) {
828 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
829 // iff target supports vfp2.
830 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
831 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
834 // We want to custom lower some of our intrinsics.
835 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
836 if (Subtarget->isTargetDarwin()) {
837 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
838 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
839 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
842 setOperationAction(ISD::SETCC, MVT::i32, Expand);
843 setOperationAction(ISD::SETCC, MVT::f32, Expand);
844 setOperationAction(ISD::SETCC, MVT::f64, Expand);
845 setOperationAction(ISD::SELECT, MVT::i32, Custom);
846 setOperationAction(ISD::SELECT, MVT::f32, Custom);
847 setOperationAction(ISD::SELECT, MVT::f64, Custom);
848 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
849 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
850 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
852 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
853 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
854 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
855 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
856 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
858 // We don't support sin/cos/fmod/copysign/pow
859 setOperationAction(ISD::FSIN, MVT::f64, Expand);
860 setOperationAction(ISD::FSIN, MVT::f32, Expand);
861 setOperationAction(ISD::FCOS, MVT::f32, Expand);
862 setOperationAction(ISD::FCOS, MVT::f64, Expand);
863 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
864 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
865 setOperationAction(ISD::FREM, MVT::f64, Expand);
866 setOperationAction(ISD::FREM, MVT::f32, Expand);
867 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
868 !Subtarget->isThumb1Only()) {
869 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
870 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
872 setOperationAction(ISD::FPOW, MVT::f64, Expand);
873 setOperationAction(ISD::FPOW, MVT::f32, Expand);
875 if (!Subtarget->hasVFP4()) {
876 setOperationAction(ISD::FMA, MVT::f64, Expand);
877 setOperationAction(ISD::FMA, MVT::f32, Expand);
880 // Various VFP goodness
881 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
882 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
883 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
884 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
885 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
888 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
889 if (!Subtarget->hasFP16()) {
890 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
891 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
895 // Combine sin / cos into one node or libcall if possible.
896 if (Subtarget->hasSinCos()) {
897 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
898 setLibcallName(RTLIB::SINCOS_F64, "sincos");
899 if (Subtarget->getTargetTriple().isiOS()) {
900 // For iOS, we don't want to the normal expansion of a libcall to
901 // sincos. We want to issue a libcall to __sincos_stret.
902 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
903 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
907 // FP-ARMv8 implements a lot of rounding-like FP operations.
908 if (Subtarget->hasFPARMv8()) {
909 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
910 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
911 setOperationAction(ISD::FROUND, MVT::f32, Legal);
912 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
913 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
914 setOperationAction(ISD::FRINT, MVT::f32, Legal);
915 if (!Subtarget->isFPOnlySP()) {
916 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
917 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
918 setOperationAction(ISD::FROUND, MVT::f64, Legal);
919 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
920 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
921 setOperationAction(ISD::FRINT, MVT::f64, Legal);
924 // We have target-specific dag combine patterns for the following nodes:
925 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
926 setTargetDAGCombine(ISD::ADD);
927 setTargetDAGCombine(ISD::SUB);
928 setTargetDAGCombine(ISD::MUL);
929 setTargetDAGCombine(ISD::AND);
930 setTargetDAGCombine(ISD::OR);
931 setTargetDAGCombine(ISD::XOR);
933 if (Subtarget->hasV6Ops())
934 setTargetDAGCombine(ISD::SRL);
936 setStackPointerRegisterToSaveRestore(ARM::SP);
938 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
939 !Subtarget->hasVFP2())
940 setSchedulingPreference(Sched::RegPressure);
942 setSchedulingPreference(Sched::Hybrid);
944 //// temporary - rewrite interface to use type
945 MaxStoresPerMemset = 8;
946 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
947 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
948 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
949 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
950 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
952 // On ARM arguments smaller than 4 bytes are extended, so all arguments
953 // are at least 4 bytes aligned.
954 setMinStackArgumentAlignment(4);
956 // Prefer likely predicted branches to selects on out-of-order cores.
957 PredictableSelectIsExpensive = Subtarget->isLikeA9();
959 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
962 bool ARMTargetLowering::useSoftFloat() const {
963 return Subtarget->useSoftFloat();
966 // FIXME: It might make sense to define the representative register class as the
967 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
968 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
969 // SPR's representative would be DPR_VFP2. This should work well if register
970 // pressure tracking were modified such that a register use would increment the
971 // pressure of the register class's representative and all of it's super
972 // classes' representatives transitively. We have not implemented this because
973 // of the difficulty prior to coalescing of modeling operand register classes
974 // due to the common occurrence of cross class copies and subregister insertions
976 std::pair<const TargetRegisterClass *, uint8_t>
977 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
979 const TargetRegisterClass *RRC = nullptr;
981 switch (VT.SimpleTy) {
983 return TargetLowering::findRepresentativeClass(TRI, VT);
984 // Use DPR as representative register class for all floating point
985 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
986 // the cost is 1 for both f32 and f64.
987 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
988 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
989 RRC = &ARM::DPRRegClass;
990 // When NEON is used for SP, only half of the register file is available
991 // because operations that define both SP and DP results will be constrained
992 // to the VFP2 class (D0-D15). We currently model this constraint prior to
993 // coalescing by double-counting the SP regs. See the FIXME above.
994 if (Subtarget->useNEONForSinglePrecisionFP())
997 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
998 case MVT::v4f32: case MVT::v2f64:
999 RRC = &ARM::DPRRegClass;
1003 RRC = &ARM::DPRRegClass;
1007 RRC = &ARM::DPRRegClass;
1011 return std::make_pair(RRC, Cost);
1014 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1015 switch ((ARMISD::NodeType)Opcode) {
1016 case ARMISD::FIRST_NUMBER: break;
1017 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1018 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1019 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1020 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1021 case ARMISD::CALL: return "ARMISD::CALL";
1022 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1023 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1024 case ARMISD::tCALL: return "ARMISD::tCALL";
1025 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1026 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1027 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1028 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1029 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1030 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1031 case ARMISD::CMP: return "ARMISD::CMP";
1032 case ARMISD::CMN: return "ARMISD::CMN";
1033 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1034 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1035 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1036 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1037 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1039 case ARMISD::CMOV: return "ARMISD::CMOV";
1041 case ARMISD::RBIT: return "ARMISD::RBIT";
1043 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1044 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1045 case ARMISD::RRX: return "ARMISD::RRX";
1047 case ARMISD::ADDC: return "ARMISD::ADDC";
1048 case ARMISD::ADDE: return "ARMISD::ADDE";
1049 case ARMISD::SUBC: return "ARMISD::SUBC";
1050 case ARMISD::SUBE: return "ARMISD::SUBE";
1052 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1053 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1055 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1056 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1058 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1060 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1062 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1064 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1066 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1068 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1070 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1071 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1072 case ARMISD::VCGE: return "ARMISD::VCGE";
1073 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1074 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1075 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1076 case ARMISD::VCGT: return "ARMISD::VCGT";
1077 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1078 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1079 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1080 case ARMISD::VTST: return "ARMISD::VTST";
1082 case ARMISD::VSHL: return "ARMISD::VSHL";
1083 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1084 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1085 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1086 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1087 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1088 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1089 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1090 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1091 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1092 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1093 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1094 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1095 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1096 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1097 case ARMISD::VSLI: return "ARMISD::VSLI";
1098 case ARMISD::VSRI: return "ARMISD::VSRI";
1099 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1100 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1101 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1102 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1103 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1104 case ARMISD::VDUP: return "ARMISD::VDUP";
1105 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1106 case ARMISD::VEXT: return "ARMISD::VEXT";
1107 case ARMISD::VREV64: return "ARMISD::VREV64";
1108 case ARMISD::VREV32: return "ARMISD::VREV32";
1109 case ARMISD::VREV16: return "ARMISD::VREV16";
1110 case ARMISD::VZIP: return "ARMISD::VZIP";
1111 case ARMISD::VUZP: return "ARMISD::VUZP";
1112 case ARMISD::VTRN: return "ARMISD::VTRN";
1113 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1114 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1115 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1116 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1117 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1118 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1119 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1120 case ARMISD::FMAX: return "ARMISD::FMAX";
1121 case ARMISD::FMIN: return "ARMISD::FMIN";
1122 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1123 case ARMISD::VMINNM: return "ARMISD::VMIN";
1124 case ARMISD::BFI: return "ARMISD::BFI";
1125 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1126 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1127 case ARMISD::VBSL: return "ARMISD::VBSL";
1128 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1129 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1130 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1131 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1132 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1133 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1134 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1135 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1136 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1137 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1138 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1139 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1140 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1141 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1142 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1143 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1144 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1145 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1146 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1147 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1152 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1153 if (!VT.isVector()) return getPointerTy();
1154 return VT.changeVectorElementTypeToInteger();
1157 /// getRegClassFor - Return the register class that should be used for the
1158 /// specified value type.
1159 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1160 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1161 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1162 // load / store 4 to 8 consecutive D registers.
1163 if (Subtarget->hasNEON()) {
1164 if (VT == MVT::v4i64)
1165 return &ARM::QQPRRegClass;
1166 if (VT == MVT::v8i64)
1167 return &ARM::QQQQPRRegClass;
1169 return TargetLowering::getRegClassFor(VT);
1172 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1173 // source/dest is aligned and the copy size is large enough. We therefore want
1174 // to align such objects passed to memory intrinsics.
1175 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1176 unsigned &PrefAlign) const {
1177 if (!isa<MemIntrinsic>(CI))
1180 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1181 // cycle faster than 4-byte aligned LDM.
1182 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1186 // Create a fast isel object.
1188 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1189 const TargetLibraryInfo *libInfo) const {
1190 return ARM::createFastISel(funcInfo, libInfo);
1193 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1194 unsigned NumVals = N->getNumValues();
1196 return Sched::RegPressure;
1198 for (unsigned i = 0; i != NumVals; ++i) {
1199 EVT VT = N->getValueType(i);
1200 if (VT == MVT::Glue || VT == MVT::Other)
1202 if (VT.isFloatingPoint() || VT.isVector())
1206 if (!N->isMachineOpcode())
1207 return Sched::RegPressure;
1209 // Load are scheduled for latency even if there instruction itinerary
1210 // is not available.
1211 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1212 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1214 if (MCID.getNumDefs() == 0)
1215 return Sched::RegPressure;
1216 if (!Itins->isEmpty() &&
1217 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1220 return Sched::RegPressure;
1223 //===----------------------------------------------------------------------===//
1225 //===----------------------------------------------------------------------===//
1227 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1228 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1230 default: llvm_unreachable("Unknown condition code!");
1231 case ISD::SETNE: return ARMCC::NE;
1232 case ISD::SETEQ: return ARMCC::EQ;
1233 case ISD::SETGT: return ARMCC::GT;
1234 case ISD::SETGE: return ARMCC::GE;
1235 case ISD::SETLT: return ARMCC::LT;
1236 case ISD::SETLE: return ARMCC::LE;
1237 case ISD::SETUGT: return ARMCC::HI;
1238 case ISD::SETUGE: return ARMCC::HS;
1239 case ISD::SETULT: return ARMCC::LO;
1240 case ISD::SETULE: return ARMCC::LS;
1244 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1245 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1246 ARMCC::CondCodes &CondCode2) {
1247 CondCode2 = ARMCC::AL;
1249 default: llvm_unreachable("Unknown FP condition!");
1251 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1253 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1255 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1256 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1257 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1258 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1259 case ISD::SETO: CondCode = ARMCC::VC; break;
1260 case ISD::SETUO: CondCode = ARMCC::VS; break;
1261 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1262 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1263 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1265 case ISD::SETULT: CondCode = ARMCC::LT; break;
1267 case ISD::SETULE: CondCode = ARMCC::LE; break;
1269 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1273 //===----------------------------------------------------------------------===//
1274 // Calling Convention Implementation
1275 //===----------------------------------------------------------------------===//
1277 #include "ARMGenCallingConv.inc"
1279 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1280 /// account presence of floating point hardware and calling convention
1281 /// limitations, such as support for variadic functions.
1283 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1284 bool isVarArg) const {
1287 llvm_unreachable("Unsupported calling convention");
1288 case CallingConv::ARM_AAPCS:
1289 case CallingConv::ARM_APCS:
1290 case CallingConv::GHC:
1292 case CallingConv::ARM_AAPCS_VFP:
1293 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1294 case CallingConv::C:
1295 if (!Subtarget->isAAPCS_ABI())
1296 return CallingConv::ARM_APCS;
1297 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1298 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1300 return CallingConv::ARM_AAPCS_VFP;
1302 return CallingConv::ARM_AAPCS;
1303 case CallingConv::Fast:
1304 if (!Subtarget->isAAPCS_ABI()) {
1305 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1306 return CallingConv::Fast;
1307 return CallingConv::ARM_APCS;
1308 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1309 return CallingConv::ARM_AAPCS_VFP;
1311 return CallingConv::ARM_AAPCS;
1315 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1316 /// CallingConvention.
1317 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1319 bool isVarArg) const {
1320 switch (getEffectiveCallingConv(CC, isVarArg)) {
1322 llvm_unreachable("Unsupported calling convention");
1323 case CallingConv::ARM_APCS:
1324 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1325 case CallingConv::ARM_AAPCS:
1326 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1327 case CallingConv::ARM_AAPCS_VFP:
1328 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1329 case CallingConv::Fast:
1330 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1331 case CallingConv::GHC:
1332 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1336 /// LowerCallResult - Lower the result values of a call into the
1337 /// appropriate copies out of appropriate physical registers.
1339 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1340 CallingConv::ID CallConv, bool isVarArg,
1341 const SmallVectorImpl<ISD::InputArg> &Ins,
1342 SDLoc dl, SelectionDAG &DAG,
1343 SmallVectorImpl<SDValue> &InVals,
1344 bool isThisReturn, SDValue ThisVal) const {
1346 // Assign locations to each value returned by this call.
1347 SmallVector<CCValAssign, 16> RVLocs;
1348 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1349 *DAG.getContext(), Call);
1350 CCInfo.AnalyzeCallResult(Ins,
1351 CCAssignFnForNode(CallConv, /* Return*/ true,
1354 // Copy all of the result registers out of their specified physreg.
1355 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1356 CCValAssign VA = RVLocs[i];
1358 // Pass 'this' value directly from the argument to return value, to avoid
1359 // reg unit interference
1360 if (i == 0 && isThisReturn) {
1361 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1362 "unexpected return calling convention register assignment");
1363 InVals.push_back(ThisVal);
1368 if (VA.needsCustom()) {
1369 // Handle f64 or half of a v2f64.
1370 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1372 Chain = Lo.getValue(1);
1373 InFlag = Lo.getValue(2);
1374 VA = RVLocs[++i]; // skip ahead to next loc
1375 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1377 Chain = Hi.getValue(1);
1378 InFlag = Hi.getValue(2);
1379 if (!Subtarget->isLittle())
1381 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1383 if (VA.getLocVT() == MVT::v2f64) {
1384 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1385 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1386 DAG.getConstant(0, dl, MVT::i32));
1388 VA = RVLocs[++i]; // skip ahead to next loc
1389 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1390 Chain = Lo.getValue(1);
1391 InFlag = Lo.getValue(2);
1392 VA = RVLocs[++i]; // skip ahead to next loc
1393 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1394 Chain = Hi.getValue(1);
1395 InFlag = Hi.getValue(2);
1396 if (!Subtarget->isLittle())
1398 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1399 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1400 DAG.getConstant(1, dl, MVT::i32));
1403 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1405 Chain = Val.getValue(1);
1406 InFlag = Val.getValue(2);
1409 switch (VA.getLocInfo()) {
1410 default: llvm_unreachable("Unknown loc info!");
1411 case CCValAssign::Full: break;
1412 case CCValAssign::BCvt:
1413 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1417 InVals.push_back(Val);
1423 /// LowerMemOpCallTo - Store the argument to the stack.
1425 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1426 SDValue StackPtr, SDValue Arg,
1427 SDLoc dl, SelectionDAG &DAG,
1428 const CCValAssign &VA,
1429 ISD::ArgFlagsTy Flags) const {
1430 unsigned LocMemOffset = VA.getLocMemOffset();
1431 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1432 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1433 return DAG.getStore(Chain, dl, Arg, PtrOff,
1434 MachinePointerInfo::getStack(LocMemOffset),
1438 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1439 SDValue Chain, SDValue &Arg,
1440 RegsToPassVector &RegsToPass,
1441 CCValAssign &VA, CCValAssign &NextVA,
1443 SmallVectorImpl<SDValue> &MemOpChains,
1444 ISD::ArgFlagsTy Flags) const {
1446 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1447 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1448 unsigned id = Subtarget->isLittle() ? 0 : 1;
1449 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1451 if (NextVA.isRegLoc())
1452 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1454 assert(NextVA.isMemLoc());
1455 if (!StackPtr.getNode())
1456 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1458 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1464 /// LowerCall - Lowering a call into a callseq_start <-
1465 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1468 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1469 SmallVectorImpl<SDValue> &InVals) const {
1470 SelectionDAG &DAG = CLI.DAG;
1472 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1473 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1474 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1475 SDValue Chain = CLI.Chain;
1476 SDValue Callee = CLI.Callee;
1477 bool &isTailCall = CLI.IsTailCall;
1478 CallingConv::ID CallConv = CLI.CallConv;
1479 bool doesNotRet = CLI.DoesNotReturn;
1480 bool isVarArg = CLI.IsVarArg;
1482 MachineFunction &MF = DAG.getMachineFunction();
1483 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1484 bool isThisReturn = false;
1485 bool isSibCall = false;
1487 // Disable tail calls if they're not supported.
1488 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1492 // Check if it's really possible to do a tail call.
1493 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1494 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1495 Outs, OutVals, Ins, DAG);
1496 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1497 report_fatal_error("failed to perform tail call elimination on a call "
1498 "site marked musttail");
1499 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1500 // detected sibcalls.
1507 // Analyze operands of the call, assigning locations to each operand.
1508 SmallVector<CCValAssign, 16> ArgLocs;
1509 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1510 *DAG.getContext(), Call);
1511 CCInfo.AnalyzeCallOperands(Outs,
1512 CCAssignFnForNode(CallConv, /* Return*/ false,
1515 // Get a count of how many bytes are to be pushed on the stack.
1516 unsigned NumBytes = CCInfo.getNextStackOffset();
1518 // For tail calls, memory operands are available in our caller's stack.
1522 // Adjust the stack pointer for the new arguments...
1523 // These operations are automatically eliminated by the prolog/epilog pass
1525 Chain = DAG.getCALLSEQ_START(Chain,
1526 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1528 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1530 RegsToPassVector RegsToPass;
1531 SmallVector<SDValue, 8> MemOpChains;
1533 // Walk the register/memloc assignments, inserting copies/loads. In the case
1534 // of tail call optimization, arguments are handled later.
1535 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1537 ++i, ++realArgIdx) {
1538 CCValAssign &VA = ArgLocs[i];
1539 SDValue Arg = OutVals[realArgIdx];
1540 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1541 bool isByVal = Flags.isByVal();
1543 // Promote the value if needed.
1544 switch (VA.getLocInfo()) {
1545 default: llvm_unreachable("Unknown loc info!");
1546 case CCValAssign::Full: break;
1547 case CCValAssign::SExt:
1548 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1550 case CCValAssign::ZExt:
1551 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1553 case CCValAssign::AExt:
1554 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1556 case CCValAssign::BCvt:
1557 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1561 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1562 if (VA.needsCustom()) {
1563 if (VA.getLocVT() == MVT::v2f64) {
1564 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1565 DAG.getConstant(0, dl, MVT::i32));
1566 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1567 DAG.getConstant(1, dl, MVT::i32));
1569 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1570 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1572 VA = ArgLocs[++i]; // skip ahead to next loc
1573 if (VA.isRegLoc()) {
1574 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1575 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1577 assert(VA.isMemLoc());
1579 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1580 dl, DAG, VA, Flags));
1583 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1584 StackPtr, MemOpChains, Flags);
1586 } else if (VA.isRegLoc()) {
1587 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1588 assert(VA.getLocVT() == MVT::i32 &&
1589 "unexpected calling convention register assignment");
1590 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1591 "unexpected use of 'returned'");
1592 isThisReturn = true;
1594 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1595 } else if (isByVal) {
1596 assert(VA.isMemLoc());
1597 unsigned offset = 0;
1599 // True if this byval aggregate will be split between registers
1601 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1602 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1604 if (CurByValIdx < ByValArgsCount) {
1606 unsigned RegBegin, RegEnd;
1607 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1609 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1611 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1612 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1613 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1614 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1615 MachinePointerInfo(),
1616 false, false, false,
1617 DAG.InferPtrAlignment(AddArg));
1618 MemOpChains.push_back(Load.getValue(1));
1619 RegsToPass.push_back(std::make_pair(j, Load));
1622 // If parameter size outsides register area, "offset" value
1623 // helps us to calculate stack slot for remained part properly.
1624 offset = RegEnd - RegBegin;
1626 CCInfo.nextInRegsParam();
1629 if (Flags.getByValSize() > 4*offset) {
1630 unsigned LocMemOffset = VA.getLocMemOffset();
1631 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1632 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1634 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1635 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1636 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1638 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1641 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1642 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1643 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1646 } else if (!isSibCall) {
1647 assert(VA.isMemLoc());
1649 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1650 dl, DAG, VA, Flags));
1654 if (!MemOpChains.empty())
1655 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1657 // Build a sequence of copy-to-reg nodes chained together with token chain
1658 // and flag operands which copy the outgoing args into the appropriate regs.
1660 // Tail call byval lowering might overwrite argument registers so in case of
1661 // tail call optimization the copies to registers are lowered later.
1663 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1664 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1665 RegsToPass[i].second, InFlag);
1666 InFlag = Chain.getValue(1);
1669 // For tail calls lower the arguments to the 'real' stack slot.
1671 // Force all the incoming stack arguments to be loaded from the stack
1672 // before any new outgoing arguments are stored to the stack, because the
1673 // outgoing stack slots may alias the incoming argument stack slots, and
1674 // the alias isn't otherwise explicit. This is slightly more conservative
1675 // than necessary, because it means that each store effectively depends
1676 // on every argument instead of just those arguments it would clobber.
1678 // Do not flag preceding copytoreg stuff together with the following stuff.
1680 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1681 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1682 RegsToPass[i].second, InFlag);
1683 InFlag = Chain.getValue(1);
1688 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1689 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1690 // node so that legalize doesn't hack it.
1691 bool isDirect = false;
1692 bool isARMFunc = false;
1693 bool isLocalARMFunc = false;
1694 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1696 if (EnableARMLongCalls) {
1697 assert((Subtarget->isTargetWindows() ||
1698 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1699 "long-calls with non-static relocation model!");
1700 // Handle a global address or an external symbol. If it's not one of
1701 // those, the target's already in a register, so we don't need to do
1703 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1704 const GlobalValue *GV = G->getGlobal();
1705 // Create a constant pool entry for the callee address
1706 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1707 ARMConstantPoolValue *CPV =
1708 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1710 // Get the address of the callee into a register
1711 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1712 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1713 Callee = DAG.getLoad(getPointerTy(), dl,
1714 DAG.getEntryNode(), CPAddr,
1715 MachinePointerInfo::getConstantPool(),
1716 false, false, false, 0);
1717 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1718 const char *Sym = S->getSymbol();
1720 // Create a constant pool entry for the callee address
1721 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1722 ARMConstantPoolValue *CPV =
1723 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1724 ARMPCLabelIndex, 0);
1725 // Get the address of the callee into a register
1726 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1727 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1728 Callee = DAG.getLoad(getPointerTy(), dl,
1729 DAG.getEntryNode(), CPAddr,
1730 MachinePointerInfo::getConstantPool(),
1731 false, false, false, 0);
1733 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1734 const GlobalValue *GV = G->getGlobal();
1736 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1737 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1738 getTargetMachine().getRelocationModel() != Reloc::Static;
1739 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1740 // ARM call to a local ARM function is predicable.
1741 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1742 // tBX takes a register source operand.
1743 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1744 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1745 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1746 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1747 0, ARMII::MO_NONLAZY));
1748 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1749 MachinePointerInfo::getGOT(), false, false, true, 0);
1750 } else if (Subtarget->isTargetCOFF()) {
1751 assert(Subtarget->isTargetWindows() &&
1752 "Windows is the only supported COFF target");
1753 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1754 ? ARMII::MO_DLLIMPORT
1755 : ARMII::MO_NO_FLAG;
1756 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1758 if (GV->hasDLLImportStorageClass())
1759 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1760 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1761 Callee), MachinePointerInfo::getGOT(),
1762 false, false, false, 0);
1764 // On ELF targets for PIC code, direct calls should go through the PLT
1765 unsigned OpFlags = 0;
1766 if (Subtarget->isTargetELF() &&
1767 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1768 OpFlags = ARMII::MO_PLT;
1769 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1771 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1773 bool isStub = Subtarget->isTargetMachO() &&
1774 getTargetMachine().getRelocationModel() != Reloc::Static;
1775 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1776 // tBX takes a register source operand.
1777 const char *Sym = S->getSymbol();
1778 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1779 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1780 ARMConstantPoolValue *CPV =
1781 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1782 ARMPCLabelIndex, 4);
1783 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1784 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1785 Callee = DAG.getLoad(getPointerTy(), dl,
1786 DAG.getEntryNode(), CPAddr,
1787 MachinePointerInfo::getConstantPool(),
1788 false, false, false, 0);
1789 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1790 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1791 getPointerTy(), Callee, PICLabel);
1793 unsigned OpFlags = 0;
1794 // On ELF targets for PIC code, direct calls should go through the PLT
1795 if (Subtarget->isTargetELF() &&
1796 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1797 OpFlags = ARMII::MO_PLT;
1798 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1802 // FIXME: handle tail calls differently.
1804 bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1805 if (Subtarget->isThumb()) {
1806 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1807 CallOpc = ARMISD::CALL_NOLINK;
1809 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1811 if (!isDirect && !Subtarget->hasV5TOps())
1812 CallOpc = ARMISD::CALL_NOLINK;
1813 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1814 // Emit regular call when code size is the priority
1816 // "mov lr, pc; b _foo" to avoid confusing the RSP
1817 CallOpc = ARMISD::CALL_NOLINK;
1819 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1822 std::vector<SDValue> Ops;
1823 Ops.push_back(Chain);
1824 Ops.push_back(Callee);
1826 // Add argument registers to the end of the list so that they are known live
1828 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1829 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1830 RegsToPass[i].second.getValueType()));
1832 // Add a register mask operand representing the call-preserved registers.
1834 const uint32_t *Mask;
1835 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1837 // For 'this' returns, use the R0-preserving mask if applicable
1838 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1840 // Set isThisReturn to false if the calling convention is not one that
1841 // allows 'returned' to be modeled in this way, so LowerCallResult does
1842 // not try to pass 'this' straight through
1843 isThisReturn = false;
1844 Mask = ARI->getCallPreservedMask(MF, CallConv);
1847 Mask = ARI->getCallPreservedMask(MF, CallConv);
1849 assert(Mask && "Missing call preserved mask for calling convention");
1850 Ops.push_back(DAG.getRegisterMask(Mask));
1853 if (InFlag.getNode())
1854 Ops.push_back(InFlag);
1856 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1858 MF.getFrameInfo()->setHasTailCall();
1859 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1862 // Returns a chain and a flag for retval copy to use.
1863 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1864 InFlag = Chain.getValue(1);
1866 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1867 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1869 InFlag = Chain.getValue(1);
1871 // Handle result values, copying them out of physregs into vregs that we
1873 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1874 InVals, isThisReturn,
1875 isThisReturn ? OutVals[0] : SDValue());
1878 /// HandleByVal - Every parameter *after* a byval parameter is passed
1879 /// on the stack. Remember the next parameter register to allocate,
1880 /// and then confiscate the rest of the parameter registers to insure
1882 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1883 unsigned Align) const {
1884 assert((State->getCallOrPrologue() == Prologue ||
1885 State->getCallOrPrologue() == Call) &&
1886 "unhandled ParmContext");
1888 // Byval (as with any stack) slots are always at least 4 byte aligned.
1889 Align = std::max(Align, 4U);
1891 unsigned Reg = State->AllocateReg(GPRArgRegs);
1895 unsigned AlignInRegs = Align / 4;
1896 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1897 for (unsigned i = 0; i < Waste; ++i)
1898 Reg = State->AllocateReg(GPRArgRegs);
1903 unsigned Excess = 4 * (ARM::R4 - Reg);
1905 // Special case when NSAA != SP and parameter size greater than size of
1906 // all remained GPR regs. In that case we can't split parameter, we must
1907 // send it to stack. We also must set NCRN to R4, so waste all
1908 // remained registers.
1909 const unsigned NSAAOffset = State->getNextStackOffset();
1910 if (NSAAOffset != 0 && Size > Excess) {
1911 while (State->AllocateReg(GPRArgRegs))
1916 // First register for byval parameter is the first register that wasn't
1917 // allocated before this method call, so it would be "reg".
1918 // If parameter is small enough to be saved in range [reg, r4), then
1919 // the end (first after last) register would be reg + param-size-in-regs,
1920 // else parameter would be splitted between registers and stack,
1921 // end register would be r4 in this case.
1922 unsigned ByValRegBegin = Reg;
1923 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1924 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1925 // Note, first register is allocated in the beginning of function already,
1926 // allocate remained amount of registers we need.
1927 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1928 State->AllocateReg(GPRArgRegs);
1929 // A byval parameter that is split between registers and memory needs its
1930 // size truncated here.
1931 // In the case where the entire structure fits in registers, we set the
1932 // size in memory to zero.
1933 Size = std::max<int>(Size - Excess, 0);
1936 /// MatchingStackOffset - Return true if the given stack call argument is
1937 /// already available in the same position (relatively) of the caller's
1938 /// incoming argument stack.
1940 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1941 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1942 const TargetInstrInfo *TII) {
1943 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1945 if (Arg.getOpcode() == ISD::CopyFromReg) {
1946 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1947 if (!TargetRegisterInfo::isVirtualRegister(VR))
1949 MachineInstr *Def = MRI->getVRegDef(VR);
1952 if (!Flags.isByVal()) {
1953 if (!TII->isLoadFromStackSlot(Def, FI))
1958 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1959 if (Flags.isByVal())
1960 // ByVal argument is passed in as a pointer but it's now being
1961 // dereferenced. e.g.
1962 // define @foo(%struct.X* %A) {
1963 // tail call @bar(%struct.X* byval %A)
1966 SDValue Ptr = Ld->getBasePtr();
1967 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1970 FI = FINode->getIndex();
1974 assert(FI != INT_MAX);
1975 if (!MFI->isFixedObjectIndex(FI))
1977 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1980 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1981 /// for tail call optimization. Targets which want to do tail call
1982 /// optimization should implement this function.
1984 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1985 CallingConv::ID CalleeCC,
1987 bool isCalleeStructRet,
1988 bool isCallerStructRet,
1989 const SmallVectorImpl<ISD::OutputArg> &Outs,
1990 const SmallVectorImpl<SDValue> &OutVals,
1991 const SmallVectorImpl<ISD::InputArg> &Ins,
1992 SelectionDAG& DAG) const {
1993 const Function *CallerF = DAG.getMachineFunction().getFunction();
1994 CallingConv::ID CallerCC = CallerF->getCallingConv();
1995 bool CCMatch = CallerCC == CalleeCC;
1997 // Look for obvious safe cases to perform tail call optimization that do not
1998 // require ABI changes. This is what gcc calls sibcall.
2000 // Do not sibcall optimize vararg calls unless the call site is not passing
2002 if (isVarArg && !Outs.empty())
2005 // Exception-handling functions need a special set of instructions to indicate
2006 // a return to the hardware. Tail-calling another function would probably
2008 if (CallerF->hasFnAttribute("interrupt"))
2011 // Also avoid sibcall optimization if either caller or callee uses struct
2012 // return semantics.
2013 if (isCalleeStructRet || isCallerStructRet)
2016 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2017 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2018 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2019 // support in the assembler and linker to be used. This would need to be
2020 // fixed to fully support tail calls in Thumb1.
2022 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2023 // LR. This means if we need to reload LR, it takes an extra instructions,
2024 // which outweighs the value of the tail call; but here we don't know yet
2025 // whether LR is going to be used. Probably the right approach is to
2026 // generate the tail call here and turn it back into CALL/RET in
2027 // emitEpilogue if LR is used.
2029 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2030 // but we need to make sure there are enough registers; the only valid
2031 // registers are the 4 used for parameters. We don't currently do this
2033 if (Subtarget->isThumb1Only())
2036 // Externally-defined functions with weak linkage should not be
2037 // tail-called on ARM when the OS does not support dynamic
2038 // pre-emption of symbols, as the AAELF spec requires normal calls
2039 // to undefined weak functions to be replaced with a NOP or jump to the
2040 // next instruction. The behaviour of branch instructions in this
2041 // situation (as used for tail calls) is implementation-defined, so we
2042 // cannot rely on the linker replacing the tail call with a return.
2043 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2044 const GlobalValue *GV = G->getGlobal();
2045 const Triple TT(getTargetMachine().getTargetTriple());
2046 if (GV->hasExternalWeakLinkage() &&
2047 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2051 // If the calling conventions do not match, then we'd better make sure the
2052 // results are returned in the same way as what the caller expects.
2054 SmallVector<CCValAssign, 16> RVLocs1;
2055 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2056 *DAG.getContext(), Call);
2057 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2059 SmallVector<CCValAssign, 16> RVLocs2;
2060 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2061 *DAG.getContext(), Call);
2062 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2064 if (RVLocs1.size() != RVLocs2.size())
2066 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2067 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2069 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2071 if (RVLocs1[i].isRegLoc()) {
2072 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2075 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2081 // If Caller's vararg or byval argument has been split between registers and
2082 // stack, do not perform tail call, since part of the argument is in caller's
2084 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2085 getInfo<ARMFunctionInfo>();
2086 if (AFI_Caller->getArgRegsSaveSize())
2089 // If the callee takes no arguments then go on to check the results of the
2091 if (!Outs.empty()) {
2092 // Check if stack adjustment is needed. For now, do not do this if any
2093 // argument is passed on the stack.
2094 SmallVector<CCValAssign, 16> ArgLocs;
2095 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2096 *DAG.getContext(), Call);
2097 CCInfo.AnalyzeCallOperands(Outs,
2098 CCAssignFnForNode(CalleeCC, false, isVarArg));
2099 if (CCInfo.getNextStackOffset()) {
2100 MachineFunction &MF = DAG.getMachineFunction();
2102 // Check if the arguments are already laid out in the right way as
2103 // the caller's fixed stack objects.
2104 MachineFrameInfo *MFI = MF.getFrameInfo();
2105 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2106 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2107 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2109 ++i, ++realArgIdx) {
2110 CCValAssign &VA = ArgLocs[i];
2111 EVT RegVT = VA.getLocVT();
2112 SDValue Arg = OutVals[realArgIdx];
2113 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2114 if (VA.getLocInfo() == CCValAssign::Indirect)
2116 if (VA.needsCustom()) {
2117 // f64 and vector types are split into multiple registers or
2118 // register/stack-slot combinations. The types will not match
2119 // the registers; give up on memory f64 refs until we figure
2120 // out what to do about this.
2123 if (!ArgLocs[++i].isRegLoc())
2125 if (RegVT == MVT::v2f64) {
2126 if (!ArgLocs[++i].isRegLoc())
2128 if (!ArgLocs[++i].isRegLoc())
2131 } else if (!VA.isRegLoc()) {
2132 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2144 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2145 MachineFunction &MF, bool isVarArg,
2146 const SmallVectorImpl<ISD::OutputArg> &Outs,
2147 LLVMContext &Context) const {
2148 SmallVector<CCValAssign, 16> RVLocs;
2149 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2150 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2154 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2155 SDLoc DL, SelectionDAG &DAG) {
2156 const MachineFunction &MF = DAG.getMachineFunction();
2157 const Function *F = MF.getFunction();
2159 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2161 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2162 // version of the "preferred return address". These offsets affect the return
2163 // instruction if this is a return from PL1 without hypervisor extensions.
2164 // IRQ/FIQ: +4 "subs pc, lr, #4"
2165 // SWI: 0 "subs pc, lr, #0"
2166 // ABORT: +4 "subs pc, lr, #4"
2167 // UNDEF: +4/+2 "subs pc, lr, #0"
2168 // UNDEF varies depending on where the exception came from ARM or Thumb
2169 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2172 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2175 else if (IntKind == "SWI" || IntKind == "UNDEF")
2178 report_fatal_error("Unsupported interrupt attribute. If present, value "
2179 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2181 RetOps.insert(RetOps.begin() + 1,
2182 DAG.getConstant(LROffset, DL, MVT::i32, false));
2184 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2188 ARMTargetLowering::LowerReturn(SDValue Chain,
2189 CallingConv::ID CallConv, bool isVarArg,
2190 const SmallVectorImpl<ISD::OutputArg> &Outs,
2191 const SmallVectorImpl<SDValue> &OutVals,
2192 SDLoc dl, SelectionDAG &DAG) const {
2194 // CCValAssign - represent the assignment of the return value to a location.
2195 SmallVector<CCValAssign, 16> RVLocs;
2197 // CCState - Info about the registers and stack slots.
2198 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2199 *DAG.getContext(), Call);
2201 // Analyze outgoing return values.
2202 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2206 SmallVector<SDValue, 4> RetOps;
2207 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2208 bool isLittleEndian = Subtarget->isLittle();
2210 MachineFunction &MF = DAG.getMachineFunction();
2211 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2212 AFI->setReturnRegsCount(RVLocs.size());
2214 // Copy the result values into the output registers.
2215 for (unsigned i = 0, realRVLocIdx = 0;
2217 ++i, ++realRVLocIdx) {
2218 CCValAssign &VA = RVLocs[i];
2219 assert(VA.isRegLoc() && "Can only return in registers!");
2221 SDValue Arg = OutVals[realRVLocIdx];
2223 switch (VA.getLocInfo()) {
2224 default: llvm_unreachable("Unknown loc info!");
2225 case CCValAssign::Full: break;
2226 case CCValAssign::BCvt:
2227 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2231 if (VA.needsCustom()) {
2232 if (VA.getLocVT() == MVT::v2f64) {
2233 // Extract the first half and return it in two registers.
2234 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2235 DAG.getConstant(0, dl, MVT::i32));
2236 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2237 DAG.getVTList(MVT::i32, MVT::i32), Half);
2239 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2240 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2242 Flag = Chain.getValue(1);
2243 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2244 VA = RVLocs[++i]; // skip ahead to next loc
2245 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2246 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2248 Flag = Chain.getValue(1);
2249 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2250 VA = RVLocs[++i]; // skip ahead to next loc
2252 // Extract the 2nd half and fall through to handle it as an f64 value.
2253 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2254 DAG.getConstant(1, dl, MVT::i32));
2256 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2258 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2259 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2260 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2261 fmrrd.getValue(isLittleEndian ? 0 : 1),
2263 Flag = Chain.getValue(1);
2264 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2265 VA = RVLocs[++i]; // skip ahead to next loc
2266 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2267 fmrrd.getValue(isLittleEndian ? 1 : 0),
2270 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2272 // Guarantee that all emitted copies are
2273 // stuck together, avoiding something bad.
2274 Flag = Chain.getValue(1);
2275 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2278 // Update chain and glue.
2281 RetOps.push_back(Flag);
2283 // CPUs which aren't M-class use a special sequence to return from
2284 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2285 // though we use "subs pc, lr, #N").
2287 // M-class CPUs actually use a normal return sequence with a special
2288 // (hardware-provided) value in LR, so the normal code path works.
2289 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2290 !Subtarget->isMClass()) {
2291 if (Subtarget->isThumb1Only())
2292 report_fatal_error("interrupt attribute is not supported in Thumb1");
2293 return LowerInterruptReturn(RetOps, dl, DAG);
2296 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2299 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2300 if (N->getNumValues() != 1)
2302 if (!N->hasNUsesOfValue(1, 0))
2305 SDValue TCChain = Chain;
2306 SDNode *Copy = *N->use_begin();
2307 if (Copy->getOpcode() == ISD::CopyToReg) {
2308 // If the copy has a glue operand, we conservatively assume it isn't safe to
2309 // perform a tail call.
2310 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2312 TCChain = Copy->getOperand(0);
2313 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2314 SDNode *VMov = Copy;
2315 // f64 returned in a pair of GPRs.
2316 SmallPtrSet<SDNode*, 2> Copies;
2317 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2319 if (UI->getOpcode() != ISD::CopyToReg)
2323 if (Copies.size() > 2)
2326 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2328 SDValue UseChain = UI->getOperand(0);
2329 if (Copies.count(UseChain.getNode()))
2333 // We are at the top of this chain.
2334 // If the copy has a glue operand, we conservatively assume it
2335 // isn't safe to perform a tail call.
2336 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2342 } else if (Copy->getOpcode() == ISD::BITCAST) {
2343 // f32 returned in a single GPR.
2344 if (!Copy->hasOneUse())
2346 Copy = *Copy->use_begin();
2347 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2349 // If the copy has a glue operand, we conservatively assume it isn't safe to
2350 // perform a tail call.
2351 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2353 TCChain = Copy->getOperand(0);
2358 bool HasRet = false;
2359 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2361 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2362 UI->getOpcode() != ARMISD::INTRET_FLAG)
2374 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2375 if (!Subtarget->supportsTailCall())
2378 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2381 return !Subtarget->isThumb1Only();
2384 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2385 // and pass the lower and high parts through.
2386 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2388 SDValue WriteValue = Op->getOperand(2);
2390 // This function is only supposed to be called for i64 type argument.
2391 assert(WriteValue.getValueType() == MVT::i64
2392 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2394 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2395 DAG.getConstant(0, DL, MVT::i32));
2396 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2397 DAG.getConstant(1, DL, MVT::i32));
2398 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2399 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2402 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2403 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2404 // one of the above mentioned nodes. It has to be wrapped because otherwise
2405 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2406 // be used to form addressing mode. These wrapped nodes will be selected
2408 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2409 EVT PtrVT = Op.getValueType();
2410 // FIXME there is no actual debug info here
2412 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2414 if (CP->isMachineConstantPoolEntry())
2415 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2416 CP->getAlignment());
2418 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2419 CP->getAlignment());
2420 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2423 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2424 return MachineJumpTableInfo::EK_Inline;
2427 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2428 SelectionDAG &DAG) const {
2429 MachineFunction &MF = DAG.getMachineFunction();
2430 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2431 unsigned ARMPCLabelIndex = 0;
2433 EVT PtrVT = getPointerTy();
2434 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2435 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2437 if (RelocM == Reloc::Static) {
2438 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2440 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2441 ARMPCLabelIndex = AFI->createPICLabelUId();
2442 ARMConstantPoolValue *CPV =
2443 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2444 ARMCP::CPBlockAddress, PCAdj);
2445 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2447 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2448 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2449 MachinePointerInfo::getConstantPool(),
2450 false, false, false, 0);
2451 if (RelocM == Reloc::Static)
2453 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2454 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2457 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2459 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2460 SelectionDAG &DAG) const {
2462 EVT PtrVT = getPointerTy();
2463 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2464 MachineFunction &MF = DAG.getMachineFunction();
2465 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2466 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2467 ARMConstantPoolValue *CPV =
2468 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2469 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2470 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2471 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2472 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2473 MachinePointerInfo::getConstantPool(),
2474 false, false, false, 0);
2475 SDValue Chain = Argument.getValue(1);
2477 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2478 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2480 // call __tls_get_addr.
2483 Entry.Node = Argument;
2484 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2485 Args.push_back(Entry);
2487 // FIXME: is there useful debug info available here?
2488 TargetLowering::CallLoweringInfo CLI(DAG);
2489 CLI.setDebugLoc(dl).setChain(Chain)
2490 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2491 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2494 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2495 return CallResult.first;
2498 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2499 // "local exec" model.
2501 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2503 TLSModel::Model model) const {
2504 const GlobalValue *GV = GA->getGlobal();
2507 SDValue Chain = DAG.getEntryNode();
2508 EVT PtrVT = getPointerTy();
2509 // Get the Thread Pointer
2510 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2512 if (model == TLSModel::InitialExec) {
2513 MachineFunction &MF = DAG.getMachineFunction();
2514 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2515 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2516 // Initial exec model.
2517 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2518 ARMConstantPoolValue *CPV =
2519 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2520 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2522 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2523 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2524 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2525 MachinePointerInfo::getConstantPool(),
2526 false, false, false, 0);
2527 Chain = Offset.getValue(1);
2529 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2530 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2532 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2533 MachinePointerInfo::getConstantPool(),
2534 false, false, false, 0);
2537 assert(model == TLSModel::LocalExec);
2538 ARMConstantPoolValue *CPV =
2539 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2540 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2541 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2542 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2543 MachinePointerInfo::getConstantPool(),
2544 false, false, false, 0);
2547 // The address of the thread local variable is the add of the thread
2548 // pointer with the offset of the variable.
2549 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2553 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2554 // TODO: implement the "local dynamic" model
2555 assert(Subtarget->isTargetELF() &&
2556 "TLS not implemented for non-ELF targets");
2557 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2559 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2562 case TLSModel::GeneralDynamic:
2563 case TLSModel::LocalDynamic:
2564 return LowerToTLSGeneralDynamicModel(GA, DAG);
2565 case TLSModel::InitialExec:
2566 case TLSModel::LocalExec:
2567 return LowerToTLSExecModels(GA, DAG, model);
2569 llvm_unreachable("bogus TLS model");
2572 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2573 SelectionDAG &DAG) const {
2574 EVT PtrVT = getPointerTy();
2576 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2577 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2578 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2579 ARMConstantPoolValue *CPV =
2580 ARMConstantPoolConstant::Create(GV,
2581 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2582 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2583 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2584 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2586 MachinePointerInfo::getConstantPool(),
2587 false, false, false, 0);
2588 SDValue Chain = Result.getValue(1);
2589 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2590 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2592 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2593 MachinePointerInfo::getGOT(),
2594 false, false, false, 0);
2598 // If we have T2 ops, we can materialize the address directly via movt/movw
2599 // pair. This is always cheaper.
2600 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2602 // FIXME: Once remat is capable of dealing with instructions with register
2603 // operands, expand this into two nodes.
2604 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2605 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2607 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2608 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2609 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2610 MachinePointerInfo::getConstantPool(),
2611 false, false, false, 0);
2615 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2616 SelectionDAG &DAG) const {
2617 EVT PtrVT = getPointerTy();
2619 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2620 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2622 if (Subtarget->useMovt(DAG.getMachineFunction()))
2625 // FIXME: Once remat is capable of dealing with instructions with register
2626 // operands, expand this into multiple nodes
2628 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2630 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2631 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2633 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2634 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2635 MachinePointerInfo::getGOT(), false, false, false, 0);
2639 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2640 SelectionDAG &DAG) const {
2641 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2642 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2643 "Windows on ARM expects to use movw/movt");
2645 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2646 const ARMII::TOF TargetFlags =
2647 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2648 EVT PtrVT = getPointerTy();
2654 // FIXME: Once remat is capable of dealing with instructions with register
2655 // operands, expand this into two nodes.
2656 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2657 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2659 if (GV->hasDLLImportStorageClass())
2660 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2661 MachinePointerInfo::getGOT(), false, false, false, 0);
2665 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2666 SelectionDAG &DAG) const {
2667 assert(Subtarget->isTargetELF() &&
2668 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2669 MachineFunction &MF = DAG.getMachineFunction();
2670 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2671 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2672 EVT PtrVT = getPointerTy();
2674 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2675 ARMConstantPoolValue *CPV =
2676 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2677 ARMPCLabelIndex, PCAdj);
2678 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2679 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2680 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2681 MachinePointerInfo::getConstantPool(),
2682 false, false, false, 0);
2683 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2684 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2688 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2690 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2691 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2692 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2693 Op.getOperand(1), Val);
2697 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2699 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2700 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2704 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2705 const ARMSubtarget *Subtarget) const {
2706 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2709 default: return SDValue(); // Don't custom lower most intrinsics.
2710 case Intrinsic::arm_rbit: {
2711 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2712 "RBIT intrinsic must have i32 type!");
2713 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2715 case Intrinsic::arm_thread_pointer: {
2716 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2717 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2719 case Intrinsic::eh_sjlj_lsda: {
2720 MachineFunction &MF = DAG.getMachineFunction();
2721 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2722 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2723 EVT PtrVT = getPointerTy();
2724 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2726 unsigned PCAdj = (RelocM != Reloc::PIC_)
2727 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2728 ARMConstantPoolValue *CPV =
2729 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2730 ARMCP::CPLSDA, PCAdj);
2731 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2732 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2734 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2735 MachinePointerInfo::getConstantPool(),
2736 false, false, false, 0);
2738 if (RelocM == Reloc::PIC_) {
2739 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2740 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2744 case Intrinsic::arm_neon_vmulls:
2745 case Intrinsic::arm_neon_vmullu: {
2746 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2747 ? ARMISD::VMULLs : ARMISD::VMULLu;
2748 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2749 Op.getOperand(1), Op.getOperand(2));
2754 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2755 const ARMSubtarget *Subtarget) {
2756 // FIXME: handle "fence singlethread" more efficiently.
2758 if (!Subtarget->hasDataBarrier()) {
2759 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2760 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2762 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2763 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2764 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2765 DAG.getConstant(0, dl, MVT::i32));
2768 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2769 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2770 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2771 if (Subtarget->isMClass()) {
2772 // Only a full system barrier exists in the M-class architectures.
2773 Domain = ARM_MB::SY;
2774 } else if (Subtarget->isSwift() && Ord == Release) {
2775 // Swift happens to implement ISHST barriers in a way that's compatible with
2776 // Release semantics but weaker than ISH so we'd be fools not to use
2777 // it. Beware: other processors probably don't!
2778 Domain = ARM_MB::ISHST;
2781 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2782 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2783 DAG.getConstant(Domain, dl, MVT::i32));
2786 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2787 const ARMSubtarget *Subtarget) {
2788 // ARM pre v5TE and Thumb1 does not have preload instructions.
2789 if (!(Subtarget->isThumb2() ||
2790 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2791 // Just preserve the chain.
2792 return Op.getOperand(0);
2795 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2797 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2798 // ARMv7 with MP extension has PLDW.
2799 return Op.getOperand(0);
2801 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2802 if (Subtarget->isThumb()) {
2804 isRead = ~isRead & 1;
2805 isData = ~isData & 1;
2808 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2809 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2810 DAG.getConstant(isData, dl, MVT::i32));
2813 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2814 MachineFunction &MF = DAG.getMachineFunction();
2815 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2817 // vastart just stores the address of the VarArgsFrameIndex slot into the
2818 // memory location argument.
2820 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2821 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2822 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2823 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2824 MachinePointerInfo(SV), false, false, 0);
2828 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2829 SDValue &Root, SelectionDAG &DAG,
2831 MachineFunction &MF = DAG.getMachineFunction();
2832 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2834 const TargetRegisterClass *RC;
2835 if (AFI->isThumb1OnlyFunction())
2836 RC = &ARM::tGPRRegClass;
2838 RC = &ARM::GPRRegClass;
2840 // Transform the arguments stored in physical registers into virtual ones.
2841 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2842 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2845 if (NextVA.isMemLoc()) {
2846 MachineFrameInfo *MFI = MF.getFrameInfo();
2847 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2849 // Create load node to retrieve arguments from the stack.
2850 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2851 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2852 MachinePointerInfo::getFixedStack(FI),
2853 false, false, false, 0);
2855 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2856 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2858 if (!Subtarget->isLittle())
2859 std::swap (ArgValue, ArgValue2);
2860 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2863 // The remaining GPRs hold either the beginning of variable-argument
2864 // data, or the beginning of an aggregate passed by value (usually
2865 // byval). Either way, we allocate stack slots adjacent to the data
2866 // provided by our caller, and store the unallocated registers there.
2867 // If this is a variadic function, the va_list pointer will begin with
2868 // these values; otherwise, this reassembles a (byval) structure that
2869 // was split between registers and memory.
2870 // Return: The frame index registers were stored into.
2872 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2873 SDLoc dl, SDValue &Chain,
2874 const Value *OrigArg,
2875 unsigned InRegsParamRecordIdx,
2877 unsigned ArgSize) const {
2878 // Currently, two use-cases possible:
2879 // Case #1. Non-var-args function, and we meet first byval parameter.
2880 // Setup first unallocated register as first byval register;
2881 // eat all remained registers
2882 // (these two actions are performed by HandleByVal method).
2883 // Then, here, we initialize stack frame with
2884 // "store-reg" instructions.
2885 // Case #2. Var-args function, that doesn't contain byval parameters.
2886 // The same: eat all remained unallocated registers,
2887 // initialize stack frame.
2889 MachineFunction &MF = DAG.getMachineFunction();
2890 MachineFrameInfo *MFI = MF.getFrameInfo();
2891 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2892 unsigned RBegin, REnd;
2893 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2894 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2896 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2897 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2902 ArgOffset = -4 * (ARM::R4 - RBegin);
2904 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2905 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2907 SmallVector<SDValue, 4> MemOps;
2908 const TargetRegisterClass *RC =
2909 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2911 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2912 unsigned VReg = MF.addLiveIn(Reg, RC);
2913 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2915 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2916 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2917 MemOps.push_back(Store);
2918 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2919 DAG.getConstant(4, dl, getPointerTy()));
2922 if (!MemOps.empty())
2923 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2927 // Setup stack frame, the va_list pointer will start from.
2929 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2930 SDLoc dl, SDValue &Chain,
2932 unsigned TotalArgRegsSaveSize,
2933 bool ForceMutable) const {
2934 MachineFunction &MF = DAG.getMachineFunction();
2935 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2937 // Try to store any remaining integer argument regs
2938 // to their spots on the stack so that they may be loaded by deferencing
2939 // the result of va_next.
2940 // If there is no regs to be stored, just point address after last
2941 // argument passed via stack.
2942 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2943 CCInfo.getInRegsParamsCount(),
2944 CCInfo.getNextStackOffset(), 4);
2945 AFI->setVarArgsFrameIndex(FrameIndex);
2949 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2950 CallingConv::ID CallConv, bool isVarArg,
2951 const SmallVectorImpl<ISD::InputArg>
2953 SDLoc dl, SelectionDAG &DAG,
2954 SmallVectorImpl<SDValue> &InVals)
2956 MachineFunction &MF = DAG.getMachineFunction();
2957 MachineFrameInfo *MFI = MF.getFrameInfo();
2959 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2961 // Assign locations to all of the incoming arguments.
2962 SmallVector<CCValAssign, 16> ArgLocs;
2963 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2964 *DAG.getContext(), Prologue);
2965 CCInfo.AnalyzeFormalArguments(Ins,
2966 CCAssignFnForNode(CallConv, /* Return*/ false,
2969 SmallVector<SDValue, 16> ArgValues;
2971 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2972 unsigned CurArgIdx = 0;
2974 // Initially ArgRegsSaveSize is zero.
2975 // Then we increase this value each time we meet byval parameter.
2976 // We also increase this value in case of varargs function.
2977 AFI->setArgRegsSaveSize(0);
2979 // Calculate the amount of stack space that we need to allocate to store
2980 // byval and variadic arguments that are passed in registers.
2981 // We need to know this before we allocate the first byval or variadic
2982 // argument, as they will be allocated a stack slot below the CFA (Canonical
2983 // Frame Address, the stack pointer at entry to the function).
2984 unsigned ArgRegBegin = ARM::R4;
2985 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2986 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2989 CCValAssign &VA = ArgLocs[i];
2990 unsigned Index = VA.getValNo();
2991 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2992 if (!Flags.isByVal())
2995 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2996 unsigned RBegin, REnd;
2997 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
2998 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3000 CCInfo.nextInRegsParam();
3002 CCInfo.rewindByValRegsInfo();
3004 int lastInsIndex = -1;
3005 if (isVarArg && MFI->hasVAStart()) {
3006 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3007 if (RegIdx != array_lengthof(GPRArgRegs))
3008 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3011 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3012 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3014 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3015 CCValAssign &VA = ArgLocs[i];
3016 if (Ins[VA.getValNo()].isOrigArg()) {
3017 std::advance(CurOrigArg,
3018 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3019 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3021 // Arguments stored in registers.
3022 if (VA.isRegLoc()) {
3023 EVT RegVT = VA.getLocVT();
3025 if (VA.needsCustom()) {
3026 // f64 and vector types are split up into multiple registers or
3027 // combinations of registers and stack slots.
3028 if (VA.getLocVT() == MVT::v2f64) {
3029 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3031 VA = ArgLocs[++i]; // skip ahead to next loc
3033 if (VA.isMemLoc()) {
3034 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3035 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3036 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3037 MachinePointerInfo::getFixedStack(FI),
3038 false, false, false, 0);
3040 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3043 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3044 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3045 ArgValue, ArgValue1,
3046 DAG.getIntPtrConstant(0, dl));
3047 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3048 ArgValue, ArgValue2,
3049 DAG.getIntPtrConstant(1, dl));
3051 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3054 const TargetRegisterClass *RC;
3056 if (RegVT == MVT::f32)
3057 RC = &ARM::SPRRegClass;
3058 else if (RegVT == MVT::f64)
3059 RC = &ARM::DPRRegClass;
3060 else if (RegVT == MVT::v2f64)
3061 RC = &ARM::QPRRegClass;
3062 else if (RegVT == MVT::i32)
3063 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3064 : &ARM::GPRRegClass;
3066 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3068 // Transform the arguments in physical registers into virtual ones.
3069 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3070 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3073 // If this is an 8 or 16-bit value, it is really passed promoted
3074 // to 32 bits. Insert an assert[sz]ext to capture this, then
3075 // truncate to the right size.
3076 switch (VA.getLocInfo()) {
3077 default: llvm_unreachable("Unknown loc info!");
3078 case CCValAssign::Full: break;
3079 case CCValAssign::BCvt:
3080 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3082 case CCValAssign::SExt:
3083 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3084 DAG.getValueType(VA.getValVT()));
3085 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3087 case CCValAssign::ZExt:
3088 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3089 DAG.getValueType(VA.getValVT()));
3090 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3094 InVals.push_back(ArgValue);
3096 } else { // VA.isRegLoc()
3099 assert(VA.isMemLoc());
3100 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3102 int index = VA.getValNo();
3104 // Some Ins[] entries become multiple ArgLoc[] entries.
3105 // Process them only once.
3106 if (index != lastInsIndex)
3108 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3109 // FIXME: For now, all byval parameter objects are marked mutable.
3110 // This can be changed with more analysis.
3111 // In case of tail call optimization mark all arguments mutable.
3112 // Since they could be overwritten by lowering of arguments in case of
3114 if (Flags.isByVal()) {
3115 assert(Ins[index].isOrigArg() &&
3116 "Byval arguments cannot be implicit");
3117 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3119 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3120 CurByValIndex, VA.getLocMemOffset(),
3121 Flags.getByValSize());
3122 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3123 CCInfo.nextInRegsParam();
3125 unsigned FIOffset = VA.getLocMemOffset();
3126 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3129 // Create load nodes to retrieve arguments from the stack.
3130 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3131 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3132 MachinePointerInfo::getFixedStack(FI),
3133 false, false, false, 0));
3135 lastInsIndex = index;
3141 if (isVarArg && MFI->hasVAStart())
3142 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3143 CCInfo.getNextStackOffset(),
3144 TotalArgRegsSaveSize);
3146 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3151 /// isFloatingPointZero - Return true if this is +0.0.
3152 static bool isFloatingPointZero(SDValue Op) {
3153 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3154 return CFP->getValueAPF().isPosZero();
3155 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3156 // Maybe this has already been legalized into the constant pool?
3157 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3158 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3159 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3160 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3161 return CFP->getValueAPF().isPosZero();
3163 } else if (Op->getOpcode() == ISD::BITCAST &&
3164 Op->getValueType(0) == MVT::f64) {
3165 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3166 // created by LowerConstantFP().
3167 SDValue BitcastOp = Op->getOperand(0);
3168 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3169 SDValue MoveOp = BitcastOp->getOperand(0);
3170 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3171 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3179 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3180 /// the given operands.
3182 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3183 SDValue &ARMcc, SelectionDAG &DAG,
3185 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3186 unsigned C = RHSC->getZExtValue();
3187 if (!isLegalICmpImmediate(C)) {
3188 // Constant does not fit, try adjusting it by one?
3193 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3194 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3195 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3200 if (C != 0 && isLegalICmpImmediate(C-1)) {
3201 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3202 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3207 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3208 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3209 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3214 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3215 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3216 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3223 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3224 ARMISD::NodeType CompareType;
3227 CompareType = ARMISD::CMP;
3232 CompareType = ARMISD::CMPZ;
3235 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3236 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3239 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3241 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3243 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3245 if (!isFloatingPointZero(RHS))
3246 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3248 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3249 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3252 /// duplicateCmp - Glue values can have only one use, so this function
3253 /// duplicates a comparison node.
3255 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3256 unsigned Opc = Cmp.getOpcode();
3258 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3259 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3261 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3262 Cmp = Cmp.getOperand(0);
3263 Opc = Cmp.getOpcode();
3264 if (Opc == ARMISD::CMPFP)
3265 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3267 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3268 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3270 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3273 std::pair<SDValue, SDValue>
3274 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3275 SDValue &ARMcc) const {
3276 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3278 SDValue Value, OverflowCmp;
3279 SDValue LHS = Op.getOperand(0);
3280 SDValue RHS = Op.getOperand(1);
3283 // FIXME: We are currently always generating CMPs because we don't support
3284 // generating CMN through the backend. This is not as good as the natural
3285 // CMP case because it causes a register dependency and cannot be folded
3288 switch (Op.getOpcode()) {
3290 llvm_unreachable("Unknown overflow instruction!");
3292 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3293 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3294 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3297 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3298 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3299 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3302 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3303 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3304 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3307 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3308 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3309 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3313 return std::make_pair(Value, OverflowCmp);
3318 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3319 // Let legalize expand this if it isn't a legal type yet.
3320 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3323 SDValue Value, OverflowCmp;
3325 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3326 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3328 // We use 0 and 1 as false and true values.
3329 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3330 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3331 EVT VT = Op.getValueType();
3333 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3334 ARMcc, CCR, OverflowCmp);
3336 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3337 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3341 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3342 SDValue Cond = Op.getOperand(0);
3343 SDValue SelectTrue = Op.getOperand(1);
3344 SDValue SelectFalse = Op.getOperand(2);
3346 unsigned Opc = Cond.getOpcode();
3348 if (Cond.getResNo() == 1 &&
3349 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3350 Opc == ISD::USUBO)) {
3351 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3354 SDValue Value, OverflowCmp;
3356 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3357 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3358 EVT VT = Op.getValueType();
3360 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3366 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3367 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3369 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3370 const ConstantSDNode *CMOVTrue =
3371 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3372 const ConstantSDNode *CMOVFalse =
3373 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3375 if (CMOVTrue && CMOVFalse) {
3376 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3377 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3381 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3383 False = SelectFalse;
3384 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3389 if (True.getNode() && False.getNode()) {
3390 EVT VT = Op.getValueType();
3391 SDValue ARMcc = Cond.getOperand(2);
3392 SDValue CCR = Cond.getOperand(3);
3393 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3394 assert(True.getValueType() == VT);
3395 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3400 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3401 // undefined bits before doing a full-word comparison with zero.
3402 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3403 DAG.getConstant(1, dl, Cond.getValueType()));
3405 return DAG.getSelectCC(dl, Cond,
3406 DAG.getConstant(0, dl, Cond.getValueType()),
3407 SelectTrue, SelectFalse, ISD::SETNE);
3410 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3411 bool &swpCmpOps, bool &swpVselOps) {
3412 // Start by selecting the GE condition code for opcodes that return true for
3414 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3416 CondCode = ARMCC::GE;
3418 // and GT for opcodes that return false for 'equality'.
3419 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3421 CondCode = ARMCC::GT;
3423 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3424 // to swap the compare operands.
3425 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3429 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3430 // If we have an unordered opcode, we need to swap the operands to the VSEL
3431 // instruction (effectively negating the condition).
3433 // This also has the effect of swapping which one of 'less' or 'greater'
3434 // returns true, so we also swap the compare operands. It also switches
3435 // whether we return true for 'equality', so we compensate by picking the
3436 // opposite condition code to our original choice.
3437 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3438 CC == ISD::SETUGT) {
3439 swpCmpOps = !swpCmpOps;
3440 swpVselOps = !swpVselOps;
3441 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3444 // 'ordered' is 'anything but unordered', so use the VS condition code and
3445 // swap the VSEL operands.
3446 if (CC == ISD::SETO) {
3447 CondCode = ARMCC::VS;
3451 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3452 // code and swap the VSEL operands.
3453 if (CC == ISD::SETUNE) {
3454 CondCode = ARMCC::EQ;
3459 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3460 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3461 SDValue Cmp, SelectionDAG &DAG) const {
3462 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3463 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3464 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3465 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3466 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3468 SDValue TrueLow = TrueVal.getValue(0);
3469 SDValue TrueHigh = TrueVal.getValue(1);
3470 SDValue FalseLow = FalseVal.getValue(0);
3471 SDValue FalseHigh = FalseVal.getValue(1);
3473 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3475 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3476 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3478 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3480 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3485 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3486 EVT VT = Op.getValueType();
3487 SDValue LHS = Op.getOperand(0);
3488 SDValue RHS = Op.getOperand(1);
3489 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3490 SDValue TrueVal = Op.getOperand(2);
3491 SDValue FalseVal = Op.getOperand(3);
3494 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3495 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3498 // If softenSetCCOperands only returned one value, we should compare it to
3500 if (!RHS.getNode()) {
3501 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3506 if (LHS.getValueType() == MVT::i32) {
3507 // Try to generate VSEL on ARMv8.
3508 // The VSEL instruction can't use all the usual ARM condition
3509 // codes: it only has two bits to select the condition code, so it's
3510 // constrained to use only GE, GT, VS and EQ.
3512 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3513 // swap the operands of the previous compare instruction (effectively
3514 // inverting the compare condition, swapping 'less' and 'greater') and
3515 // sometimes need to swap the operands to the VSEL (which inverts the
3516 // condition in the sense of firing whenever the previous condition didn't)
3517 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3518 TrueVal.getValueType() == MVT::f64)) {
3519 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3520 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3521 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3522 CC = ISD::getSetCCInverse(CC, true);
3523 std::swap(TrueVal, FalseVal);
3528 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3529 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3530 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3533 ARMCC::CondCodes CondCode, CondCode2;
3534 FPCCToARMCC(CC, CondCode, CondCode2);
3536 // Try to generate VMAXNM/VMINNM on ARMv8.
3537 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3538 TrueVal.getValueType() == MVT::f64)) {
3539 // We can use VMAXNM/VMINNM for a compare followed by a select with the
3540 // same operands, as follows:
3541 // c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3543 // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3544 bool swapSides = false;
3545 if (!getTargetMachine().Options.NoNaNsFPMath) {
3546 // transformability may depend on which way around we compare
3554 // the non-NaN should be RHS
3555 swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3561 // the non-NaN should be LHS
3562 swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3566 swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3568 CC = ISD::getSetCCSwappedOperands(CC);
3569 std::swap(LHS, RHS);
3571 if (LHS == TrueVal && RHS == FalseVal) {
3572 bool canTransform = true;
3573 // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3574 if (!getTargetMachine().Options.UnsafeFPMath &&
3575 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3576 const ConstantFPSDNode *Zero;
3583 // RHS must not be -0
3584 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3585 !Zero->isNegative();
3590 // LHS must not be -0
3591 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3592 !Zero->isNegative();
3597 // RHS must not be +0
3598 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3604 // LHS must not be +0
3605 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3611 // Note: If one of the elements in a pair is a number and the other
3612 // element is NaN, the corresponding result element is the number.
3613 // This is consistent with the IEEE 754-2008 standard.
3614 // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3620 if (!DAG.isKnownNeverNaN(RHS))
3622 return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3625 if (!DAG.isKnownNeverNaN(LHS))
3629 return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3632 if (!DAG.isKnownNeverNaN(RHS))
3634 return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3637 if (!DAG.isKnownNeverNaN(LHS))
3641 return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3646 bool swpCmpOps = false;
3647 bool swpVselOps = false;
3648 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3650 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3651 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3653 std::swap(LHS, RHS);
3655 std::swap(TrueVal, FalseVal);
3659 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3660 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3661 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3662 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3663 if (CondCode2 != ARMCC::AL) {
3664 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3665 // FIXME: Needs another CMP because flag can have but one use.
3666 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3667 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3672 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3673 /// to morph to an integer compare sequence.
3674 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3675 const ARMSubtarget *Subtarget) {
3676 SDNode *N = Op.getNode();
3677 if (!N->hasOneUse())
3678 // Otherwise it requires moving the value from fp to integer registers.
3680 if (!N->getNumValues())
3682 EVT VT = Op.getValueType();
3683 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3684 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3685 // vmrs are very slow, e.g. cortex-a8.
3688 if (isFloatingPointZero(Op)) {
3692 return ISD::isNormalLoad(N);
3695 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3696 if (isFloatingPointZero(Op))
3697 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3699 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3700 return DAG.getLoad(MVT::i32, SDLoc(Op),
3701 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3702 Ld->isVolatile(), Ld->isNonTemporal(),
3703 Ld->isInvariant(), Ld->getAlignment());
3705 llvm_unreachable("Unknown VFP cmp argument!");
3708 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3709 SDValue &RetVal1, SDValue &RetVal2) {
3712 if (isFloatingPointZero(Op)) {
3713 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3714 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3718 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3719 SDValue Ptr = Ld->getBasePtr();
3720 RetVal1 = DAG.getLoad(MVT::i32, dl,
3721 Ld->getChain(), Ptr,
3722 Ld->getPointerInfo(),
3723 Ld->isVolatile(), Ld->isNonTemporal(),
3724 Ld->isInvariant(), Ld->getAlignment());
3726 EVT PtrType = Ptr.getValueType();
3727 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3728 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3729 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3730 RetVal2 = DAG.getLoad(MVT::i32, dl,
3731 Ld->getChain(), NewPtr,
3732 Ld->getPointerInfo().getWithOffset(4),
3733 Ld->isVolatile(), Ld->isNonTemporal(),
3734 Ld->isInvariant(), NewAlign);
3738 llvm_unreachable("Unknown VFP cmp argument!");
3741 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3742 /// f32 and even f64 comparisons to integer ones.
3744 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3745 SDValue Chain = Op.getOperand(0);
3746 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3747 SDValue LHS = Op.getOperand(2);
3748 SDValue RHS = Op.getOperand(3);
3749 SDValue Dest = Op.getOperand(4);
3752 bool LHSSeenZero = false;
3753 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3754 bool RHSSeenZero = false;
3755 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3756 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3757 // If unsafe fp math optimization is enabled and there are no other uses of
3758 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3759 // to an integer comparison.
3760 if (CC == ISD::SETOEQ)
3762 else if (CC == ISD::SETUNE)
3765 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3767 if (LHS.getValueType() == MVT::f32) {
3768 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3769 bitcastf32Toi32(LHS, DAG), Mask);
3770 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3771 bitcastf32Toi32(RHS, DAG), Mask);
3772 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3773 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3774 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3775 Chain, Dest, ARMcc, CCR, Cmp);
3780 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3781 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3782 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3783 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3784 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3785 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3786 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3787 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3788 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3794 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3795 SDValue Chain = Op.getOperand(0);
3796 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3797 SDValue LHS = Op.getOperand(2);
3798 SDValue RHS = Op.getOperand(3);
3799 SDValue Dest = Op.getOperand(4);
3802 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3803 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3806 // If softenSetCCOperands only returned one value, we should compare it to
3808 if (!RHS.getNode()) {
3809 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3814 if (LHS.getValueType() == MVT::i32) {
3816 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3817 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3818 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3819 Chain, Dest, ARMcc, CCR, Cmp);
3822 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3824 if (getTargetMachine().Options.UnsafeFPMath &&
3825 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3826 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3827 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3828 if (Result.getNode())
3832 ARMCC::CondCodes CondCode, CondCode2;
3833 FPCCToARMCC(CC, CondCode, CondCode2);
3835 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3836 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3837 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3838 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3839 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3840 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3841 if (CondCode2 != ARMCC::AL) {
3842 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3843 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3844 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3849 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3850 SDValue Chain = Op.getOperand(0);
3851 SDValue Table = Op.getOperand(1);
3852 SDValue Index = Op.getOperand(2);
3855 EVT PTy = getPointerTy();
3856 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3857 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3858 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3859 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3860 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3861 if (Subtarget->isThumb2()) {
3862 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3863 // which does another jump to the destination. This also makes it easier
3864 // to translate it to TBB / TBH later.
3865 // FIXME: This might not work if the function is extremely large.
3866 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3867 Addr, Op.getOperand(2), JTI);
3869 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3870 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3871 MachinePointerInfo::getJumpTable(),
3872 false, false, false, 0);
3873 Chain = Addr.getValue(1);
3874 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3875 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3877 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3878 MachinePointerInfo::getJumpTable(),
3879 false, false, false, 0);
3880 Chain = Addr.getValue(1);
3881 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3885 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3886 EVT VT = Op.getValueType();
3889 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3890 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3892 return DAG.UnrollVectorOp(Op.getNode());
3895 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3896 "Invalid type for custom lowering!");
3897 if (VT != MVT::v4i16)
3898 return DAG.UnrollVectorOp(Op.getNode());
3900 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3901 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3904 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3905 EVT VT = Op.getValueType();
3907 return LowerVectorFP_TO_INT(Op, DAG);
3908 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3910 if (Op.getOpcode() == ISD::FP_TO_SINT)
3911 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3914 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3916 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3917 /*isSigned*/ false, SDLoc(Op)).first;
3923 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3924 EVT VT = Op.getValueType();
3927 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3928 if (VT.getVectorElementType() == MVT::f32)
3930 return DAG.UnrollVectorOp(Op.getNode());
3933 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3934 "Invalid type for custom lowering!");
3935 if (VT != MVT::v4f32)
3936 return DAG.UnrollVectorOp(Op.getNode());
3940 switch (Op.getOpcode()) {
3941 default: llvm_unreachable("Invalid opcode!");
3942 case ISD::SINT_TO_FP:
3943 CastOpc = ISD::SIGN_EXTEND;
3944 Opc = ISD::SINT_TO_FP;
3946 case ISD::UINT_TO_FP:
3947 CastOpc = ISD::ZERO_EXTEND;
3948 Opc = ISD::UINT_TO_FP;
3952 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3953 return DAG.getNode(Opc, dl, VT, Op);
3956 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3957 EVT VT = Op.getValueType();
3959 return LowerVectorINT_TO_FP(Op, DAG);
3960 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3962 if (Op.getOpcode() == ISD::SINT_TO_FP)
3963 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3966 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3968 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3969 /*isSigned*/ false, SDLoc(Op)).first;
3975 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3976 // Implement fcopysign with a fabs and a conditional fneg.
3977 SDValue Tmp0 = Op.getOperand(0);
3978 SDValue Tmp1 = Op.getOperand(1);
3980 EVT VT = Op.getValueType();
3981 EVT SrcVT = Tmp1.getValueType();
3982 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3983 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3984 bool UseNEON = !InGPR && Subtarget->hasNEON();
3987 // Use VBSL to copy the sign bit.
3988 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3989 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3990 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3991 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3993 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3994 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3995 DAG.getConstant(32, dl, MVT::i32));
3996 else /*if (VT == MVT::f32)*/
3997 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3998 if (SrcVT == MVT::f32) {
3999 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4001 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4002 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4003 DAG.getConstant(32, dl, MVT::i32));
4004 } else if (VT == MVT::f32)
4005 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4006 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4007 DAG.getConstant(32, dl, MVT::i32));
4008 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4009 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4011 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4013 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4014 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4015 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4017 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4018 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4019 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4020 if (VT == MVT::f32) {
4021 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4022 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4023 DAG.getConstant(0, dl, MVT::i32));
4025 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4031 // Bitcast operand 1 to i32.
4032 if (SrcVT == MVT::f64)
4033 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4035 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4037 // Or in the signbit with integer operations.
4038 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4039 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4040 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4041 if (VT == MVT::f32) {
4042 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4043 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4044 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4045 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4048 // f64: Or the high part with signbit and then combine two parts.
4049 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4051 SDValue Lo = Tmp0.getValue(0);
4052 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4053 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4054 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4057 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4058 MachineFunction &MF = DAG.getMachineFunction();
4059 MachineFrameInfo *MFI = MF.getFrameInfo();
4060 MFI->setReturnAddressIsTaken(true);
4062 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4065 EVT VT = Op.getValueType();
4067 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4069 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4070 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4071 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4072 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4073 MachinePointerInfo(), false, false, false, 0);
4076 // Return LR, which contains the return address. Mark it an implicit live-in.
4077 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4078 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4081 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4082 const ARMBaseRegisterInfo &ARI =
4083 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4084 MachineFunction &MF = DAG.getMachineFunction();
4085 MachineFrameInfo *MFI = MF.getFrameInfo();
4086 MFI->setFrameAddressIsTaken(true);
4088 EVT VT = Op.getValueType();
4089 SDLoc dl(Op); // FIXME probably not meaningful
4090 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4091 unsigned FrameReg = ARI.getFrameRegister(MF);
4092 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4094 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4095 MachinePointerInfo(),
4096 false, false, false, 0);
4100 // FIXME? Maybe this could be a TableGen attribute on some registers and
4101 // this table could be generated automatically from RegInfo.
4102 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4104 unsigned Reg = StringSwitch<unsigned>(RegName)
4105 .Case("sp", ARM::SP)
4109 report_fatal_error(Twine("Invalid register name \""
4110 + StringRef(RegName) + "\"."));
4113 // Result is 64 bit value so split into two 32 bit values and return as a
4115 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4116 SelectionDAG &DAG) {
4119 // This function is only supposed to be called for i64 type destination.
4120 assert(N->getValueType(0) == MVT::i64
4121 && "ExpandREAD_REGISTER called for non-i64 type result.");
4123 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4124 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4128 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4130 Results.push_back(Read.getOperand(0));
4133 /// ExpandBITCAST - If the target supports VFP, this function is called to
4134 /// expand a bit convert where either the source or destination type is i64 to
4135 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4136 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4137 /// vectors), since the legalizer won't know what to do with that.
4138 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4139 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4141 SDValue Op = N->getOperand(0);
4143 // This function is only supposed to be called for i64 types, either as the
4144 // source or destination of the bit convert.
4145 EVT SrcVT = Op.getValueType();
4146 EVT DstVT = N->getValueType(0);
4147 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4148 "ExpandBITCAST called for non-i64 type");
4150 // Turn i64->f64 into VMOVDRR.
4151 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4152 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4153 DAG.getConstant(0, dl, MVT::i32));
4154 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4155 DAG.getConstant(1, dl, MVT::i32));
4156 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4157 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4160 // Turn f64->i64 into VMOVRRD.
4161 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4163 if (TLI.isBigEndian() && SrcVT.isVector() &&
4164 SrcVT.getVectorNumElements() > 1)
4165 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4166 DAG.getVTList(MVT::i32, MVT::i32),
4167 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4169 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4170 DAG.getVTList(MVT::i32, MVT::i32), Op);
4171 // Merge the pieces into a single i64 value.
4172 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4178 /// getZeroVector - Returns a vector of specified type with all zero elements.
4179 /// Zero vectors are used to represent vector negation and in those cases
4180 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4181 /// not support i64 elements, so sometimes the zero vectors will need to be
4182 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4184 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4185 assert(VT.isVector() && "Expected a vector type");
4186 // The canonical modified immediate encoding of a zero vector is....0!
4187 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4188 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4189 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4190 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4193 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4194 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4195 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4196 SelectionDAG &DAG) const {
4197 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4198 EVT VT = Op.getValueType();
4199 unsigned VTBits = VT.getSizeInBits();
4201 SDValue ShOpLo = Op.getOperand(0);
4202 SDValue ShOpHi = Op.getOperand(1);
4203 SDValue ShAmt = Op.getOperand(2);
4205 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4207 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4209 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4210 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4211 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4212 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4213 DAG.getConstant(VTBits, dl, MVT::i32));
4214 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4215 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4216 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4218 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4219 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4220 ISD::SETGE, ARMcc, DAG, dl);
4221 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4222 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4225 SDValue Ops[2] = { Lo, Hi };
4226 return DAG.getMergeValues(Ops, dl);
4229 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4230 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4231 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4232 SelectionDAG &DAG) const {
4233 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4234 EVT VT = Op.getValueType();
4235 unsigned VTBits = VT.getSizeInBits();
4237 SDValue ShOpLo = Op.getOperand(0);
4238 SDValue ShOpHi = Op.getOperand(1);
4239 SDValue ShAmt = Op.getOperand(2);
4242 assert(Op.getOpcode() == ISD::SHL_PARTS);
4243 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4244 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4245 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4246 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4247 DAG.getConstant(VTBits, dl, MVT::i32));
4248 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4249 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4251 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4252 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4253 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4254 ISD::SETGE, ARMcc, DAG, dl);
4255 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4256 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4259 SDValue Ops[2] = { Lo, Hi };
4260 return DAG.getMergeValues(Ops, dl);
4263 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4264 SelectionDAG &DAG) const {
4265 // The rounding mode is in bits 23:22 of the FPSCR.
4266 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4267 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4268 // so that the shift + and get folded into a bitfield extract.
4270 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4271 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4273 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4274 DAG.getConstant(1U << 22, dl, MVT::i32));
4275 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4276 DAG.getConstant(22, dl, MVT::i32));
4277 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4278 DAG.getConstant(3, dl, MVT::i32));
4281 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4282 const ARMSubtarget *ST) {
4283 EVT VT = N->getValueType(0);
4286 if (!ST->hasV6T2Ops())
4289 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4290 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4293 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4294 /// for each 16-bit element from operand, repeated. The basic idea is to
4295 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4297 /// Trace for v4i16:
4298 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4299 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4300 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4301 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4302 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4303 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4304 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4305 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4306 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4307 EVT VT = N->getValueType(0);
4310 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4311 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4312 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4313 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4314 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4315 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4318 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4319 /// bit-count for each 16-bit element from the operand. We need slightly
4320 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4321 /// 64/128-bit registers.
4323 /// Trace for v4i16:
4324 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4325 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4326 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4327 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4328 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4329 EVT VT = N->getValueType(0);
4332 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4333 if (VT.is64BitVector()) {
4334 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4335 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4336 DAG.getIntPtrConstant(0, DL));
4338 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4339 BitCounts, DAG.getIntPtrConstant(0, DL));
4340 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4344 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4345 /// bit-count for each 32-bit element from the operand. The idea here is
4346 /// to split the vector into 16-bit elements, leverage the 16-bit count
4347 /// routine, and then combine the results.
4349 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4350 /// input = [v0 v1 ] (vi: 32-bit elements)
4351 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4352 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4353 /// vrev: N0 = [k1 k0 k3 k2 ]
4355 /// N1 =+[k1 k0 k3 k2 ]
4357 /// N2 =+[k1 k3 k0 k2 ]
4359 /// Extended =+[k1 k3 k0 k2 ]
4361 /// Extracted=+[k1 k3 ]
4363 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4364 EVT VT = N->getValueType(0);
4367 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4369 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4370 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4371 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4372 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4373 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4375 if (VT.is64BitVector()) {
4376 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4377 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4378 DAG.getIntPtrConstant(0, DL));
4380 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4381 DAG.getIntPtrConstant(0, DL));
4382 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4386 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4387 const ARMSubtarget *ST) {
4388 EVT VT = N->getValueType(0);
4390 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4391 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4392 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4393 "Unexpected type for custom ctpop lowering");
4395 if (VT.getVectorElementType() == MVT::i32)
4396 return lowerCTPOP32BitElements(N, DAG);
4398 return lowerCTPOP16BitElements(N, DAG);
4401 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4402 const ARMSubtarget *ST) {
4403 EVT VT = N->getValueType(0);
4409 // Lower vector shifts on NEON to use VSHL.
4410 assert(ST->hasNEON() && "unexpected vector shift");
4412 // Left shifts translate directly to the vshiftu intrinsic.
4413 if (N->getOpcode() == ISD::SHL)
4414 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4415 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4417 N->getOperand(0), N->getOperand(1));
4419 assert((N->getOpcode() == ISD::SRA ||
4420 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4422 // NEON uses the same intrinsics for both left and right shifts. For
4423 // right shifts, the shift amounts are negative, so negate the vector of
4425 EVT ShiftVT = N->getOperand(1).getValueType();
4426 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4427 getZeroVector(ShiftVT, DAG, dl),
4429 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4430 Intrinsic::arm_neon_vshifts :
4431 Intrinsic::arm_neon_vshiftu);
4432 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4433 DAG.getConstant(vshiftInt, dl, MVT::i32),
4434 N->getOperand(0), NegatedCount);
4437 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4438 const ARMSubtarget *ST) {
4439 EVT VT = N->getValueType(0);
4442 // We can get here for a node like i32 = ISD::SHL i32, i64
4446 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4447 "Unknown shift to lower!");
4449 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4450 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4451 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4454 // If we are in thumb mode, we don't have RRX.
4455 if (ST->isThumb1Only()) return SDValue();
4457 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4458 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4459 DAG.getConstant(0, dl, MVT::i32));
4460 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4461 DAG.getConstant(1, dl, MVT::i32));
4463 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4464 // captures the result into a carry flag.
4465 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4466 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4468 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4469 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4471 // Merge the pieces into a single i64 value.
4472 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4475 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4476 SDValue TmpOp0, TmpOp1;
4477 bool Invert = false;
4481 SDValue Op0 = Op.getOperand(0);
4482 SDValue Op1 = Op.getOperand(1);
4483 SDValue CC = Op.getOperand(2);
4484 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4485 EVT VT = Op.getValueType();
4486 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4489 if (Op1.getValueType().isFloatingPoint()) {
4490 switch (SetCCOpcode) {
4491 default: llvm_unreachable("Illegal FP comparison");
4493 case ISD::SETNE: Invert = true; // Fallthrough
4495 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4497 case ISD::SETLT: Swap = true; // Fallthrough
4499 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4501 case ISD::SETLE: Swap = true; // Fallthrough
4503 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4504 case ISD::SETUGE: Swap = true; // Fallthrough
4505 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4506 case ISD::SETUGT: Swap = true; // Fallthrough
4507 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4508 case ISD::SETUEQ: Invert = true; // Fallthrough
4510 // Expand this to (OLT | OGT).
4514 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4515 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4517 case ISD::SETUO: Invert = true; // Fallthrough
4519 // Expand this to (OLT | OGE).
4523 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4524 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4528 // Integer comparisons.
4529 switch (SetCCOpcode) {
4530 default: llvm_unreachable("Illegal integer comparison");
4531 case ISD::SETNE: Invert = true;
4532 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4533 case ISD::SETLT: Swap = true;
4534 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4535 case ISD::SETLE: Swap = true;
4536 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4537 case ISD::SETULT: Swap = true;
4538 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4539 case ISD::SETULE: Swap = true;
4540 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4543 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4544 if (Opc == ARMISD::VCEQ) {
4547 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4549 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4552 // Ignore bitconvert.
4553 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4554 AndOp = AndOp.getOperand(0);
4556 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4558 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4559 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4566 std::swap(Op0, Op1);
4568 // If one of the operands is a constant vector zero, attempt to fold the
4569 // comparison to a specialized compare-against-zero form.
4571 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4573 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4574 if (Opc == ARMISD::VCGE)
4575 Opc = ARMISD::VCLEZ;
4576 else if (Opc == ARMISD::VCGT)
4577 Opc = ARMISD::VCLTZ;
4582 if (SingleOp.getNode()) {
4585 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4587 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4589 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4591 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4593 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4595 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4598 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4601 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4604 Result = DAG.getNOT(dl, Result, VT);
4609 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4610 /// valid vector constant for a NEON instruction with a "modified immediate"
4611 /// operand (e.g., VMOV). If so, return the encoded value.
4612 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4613 unsigned SplatBitSize, SelectionDAG &DAG,
4614 SDLoc dl, EVT &VT, bool is128Bits,
4615 NEONModImmType type) {
4616 unsigned OpCmode, Imm;
4618 // SplatBitSize is set to the smallest size that splats the vector, so a
4619 // zero vector will always have SplatBitSize == 8. However, NEON modified
4620 // immediate instructions others than VMOV do not support the 8-bit encoding
4621 // of a zero vector, and the default encoding of zero is supposed to be the
4626 switch (SplatBitSize) {
4628 if (type != VMOVModImm)
4630 // Any 1-byte value is OK. Op=0, Cmode=1110.
4631 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4634 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4638 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4639 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4640 if ((SplatBits & ~0xff) == 0) {
4641 // Value = 0x00nn: Op=x, Cmode=100x.
4646 if ((SplatBits & ~0xff00) == 0) {
4647 // Value = 0xnn00: Op=x, Cmode=101x.
4649 Imm = SplatBits >> 8;
4655 // NEON's 32-bit VMOV supports splat values where:
4656 // * only one byte is nonzero, or
4657 // * the least significant byte is 0xff and the second byte is nonzero, or
4658 // * the least significant 2 bytes are 0xff and the third is nonzero.
4659 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4660 if ((SplatBits & ~0xff) == 0) {
4661 // Value = 0x000000nn: Op=x, Cmode=000x.
4666 if ((SplatBits & ~0xff00) == 0) {
4667 // Value = 0x0000nn00: Op=x, Cmode=001x.
4669 Imm = SplatBits >> 8;
4672 if ((SplatBits & ~0xff0000) == 0) {
4673 // Value = 0x00nn0000: Op=x, Cmode=010x.
4675 Imm = SplatBits >> 16;
4678 if ((SplatBits & ~0xff000000) == 0) {
4679 // Value = 0xnn000000: Op=x, Cmode=011x.
4681 Imm = SplatBits >> 24;
4685 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4686 if (type == OtherModImm) return SDValue();
4688 if ((SplatBits & ~0xffff) == 0 &&
4689 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4690 // Value = 0x0000nnff: Op=x, Cmode=1100.
4692 Imm = SplatBits >> 8;
4696 if ((SplatBits & ~0xffffff) == 0 &&
4697 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4698 // Value = 0x00nnffff: Op=x, Cmode=1101.
4700 Imm = SplatBits >> 16;
4704 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4705 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4706 // VMOV.I32. A (very) minor optimization would be to replicate the value
4707 // and fall through here to test for a valid 64-bit splat. But, then the
4708 // caller would also need to check and handle the change in size.
4712 if (type != VMOVModImm)
4714 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4715 uint64_t BitMask = 0xff;
4717 unsigned ImmMask = 1;
4719 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4720 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4723 } else if ((SplatBits & BitMask) != 0) {
4730 if (DAG.getTargetLoweringInfo().isBigEndian())
4731 // swap higher and lower 32 bit word
4732 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4734 // Op=1, Cmode=1110.
4736 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4741 llvm_unreachable("unexpected size for isNEONModifiedImm");
4744 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4745 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4748 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4749 const ARMSubtarget *ST) const {
4753 bool IsDouble = Op.getValueType() == MVT::f64;
4754 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4756 // Use the default (constant pool) lowering for double constants when we have
4758 if (IsDouble && Subtarget->isFPOnlySP())
4761 // Try splatting with a VMOV.f32...
4762 APFloat FPVal = CFP->getValueAPF();
4763 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4766 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4767 // We have code in place to select a valid ConstantFP already, no need to
4772 // It's a float and we are trying to use NEON operations where
4773 // possible. Lower it to a splat followed by an extract.
4775 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4776 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4778 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4779 DAG.getConstant(0, DL, MVT::i32));
4782 // The rest of our options are NEON only, make sure that's allowed before
4784 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4788 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4790 // It wouldn't really be worth bothering for doubles except for one very
4791 // important value, which does happen to match: 0.0. So make sure we don't do
4793 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4796 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4797 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4798 VMovVT, false, VMOVModImm);
4799 if (NewVal != SDValue()) {
4801 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4804 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4806 // It's a float: cast and extract a vector element.
4807 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4809 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4810 DAG.getConstant(0, DL, MVT::i32));
4813 // Finally, try a VMVN.i32
4814 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4816 if (NewVal != SDValue()) {
4818 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4821 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4823 // It's a float: cast and extract a vector element.
4824 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4826 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4827 DAG.getConstant(0, DL, MVT::i32));
4833 // check if an VEXT instruction can handle the shuffle mask when the
4834 // vector sources of the shuffle are the same.
4835 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4836 unsigned NumElts = VT.getVectorNumElements();
4838 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4844 // If this is a VEXT shuffle, the immediate value is the index of the first
4845 // element. The other shuffle indices must be the successive elements after
4847 unsigned ExpectedElt = Imm;
4848 for (unsigned i = 1; i < NumElts; ++i) {
4849 // Increment the expected index. If it wraps around, just follow it
4850 // back to index zero and keep going.
4852 if (ExpectedElt == NumElts)
4855 if (M[i] < 0) continue; // ignore UNDEF indices
4856 if (ExpectedElt != static_cast<unsigned>(M[i]))
4864 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4865 bool &ReverseVEXT, unsigned &Imm) {
4866 unsigned NumElts = VT.getVectorNumElements();
4867 ReverseVEXT = false;
4869 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4875 // If this is a VEXT shuffle, the immediate value is the index of the first
4876 // element. The other shuffle indices must be the successive elements after
4878 unsigned ExpectedElt = Imm;
4879 for (unsigned i = 1; i < NumElts; ++i) {
4880 // Increment the expected index. If it wraps around, it may still be
4881 // a VEXT but the source vectors must be swapped.
4883 if (ExpectedElt == NumElts * 2) {
4888 if (M[i] < 0) continue; // ignore UNDEF indices
4889 if (ExpectedElt != static_cast<unsigned>(M[i]))
4893 // Adjust the index value if the source operands will be swapped.
4900 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4901 /// instruction with the specified blocksize. (The order of the elements
4902 /// within each block of the vector is reversed.)
4903 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4904 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4905 "Only possible block sizes for VREV are: 16, 32, 64");
4907 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4911 unsigned NumElts = VT.getVectorNumElements();
4912 unsigned BlockElts = M[0] + 1;
4913 // If the first shuffle index is UNDEF, be optimistic.
4915 BlockElts = BlockSize / EltSz;
4917 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4920 for (unsigned i = 0; i < NumElts; ++i) {
4921 if (M[i] < 0) continue; // ignore UNDEF indices
4922 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4929 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4930 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4931 // range, then 0 is placed into the resulting vector. So pretty much any mask
4932 // of 8 elements can work here.
4933 return VT == MVT::v8i8 && M.size() == 8;
4936 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4937 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4941 unsigned NumElts = VT.getVectorNumElements();
4942 WhichResult = (M[0] == 0 ? 0 : 1);
4943 for (unsigned i = 0; i < NumElts; i += 2) {
4944 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4945 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4951 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4952 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4953 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4954 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4955 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4959 unsigned NumElts = VT.getVectorNumElements();
4960 WhichResult = (M[0] == 0 ? 0 : 1);
4961 for (unsigned i = 0; i < NumElts; i += 2) {
4962 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4963 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4969 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4970 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4974 unsigned NumElts = VT.getVectorNumElements();
4975 WhichResult = (M[0] == 0 ? 0 : 1);
4976 for (unsigned i = 0; i != NumElts; ++i) {
4977 if (M[i] < 0) continue; // ignore UNDEF indices
4978 if ((unsigned) M[i] != 2 * i + WhichResult)
4982 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4983 if (VT.is64BitVector() && EltSz == 32)
4989 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4990 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4991 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4992 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4993 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4997 unsigned Half = VT.getVectorNumElements() / 2;
4998 WhichResult = (M[0] == 0 ? 0 : 1);
4999 for (unsigned j = 0; j != 2; ++j) {
5000 unsigned Idx = WhichResult;
5001 for (unsigned i = 0; i != Half; ++i) {
5002 int MIdx = M[i + j * Half];
5003 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5009 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5010 if (VT.is64BitVector() && EltSz == 32)
5016 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5017 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5021 unsigned NumElts = VT.getVectorNumElements();
5022 WhichResult = (M[0] == 0 ? 0 : 1);
5023 unsigned Idx = WhichResult * NumElts / 2;
5024 for (unsigned i = 0; i != NumElts; i += 2) {
5025 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5026 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5031 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5032 if (VT.is64BitVector() && EltSz == 32)
5038 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5039 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5040 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5041 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5042 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5046 unsigned NumElts = VT.getVectorNumElements();
5047 WhichResult = (M[0] == 0 ? 0 : 1);
5048 unsigned Idx = WhichResult * NumElts / 2;
5049 for (unsigned i = 0; i != NumElts; i += 2) {
5050 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5051 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5056 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5057 if (VT.is64BitVector() && EltSz == 32)
5063 /// \return true if this is a reverse operation on an vector.
5064 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5065 unsigned NumElts = VT.getVectorNumElements();
5066 // Make sure the mask has the right size.
5067 if (NumElts != M.size())
5070 // Look for <15, ..., 3, -1, 1, 0>.
5071 for (unsigned i = 0; i != NumElts; ++i)
5072 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5078 // If N is an integer constant that can be moved into a register in one
5079 // instruction, return an SDValue of such a constant (will become a MOV
5080 // instruction). Otherwise return null.
5081 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5082 const ARMSubtarget *ST, SDLoc dl) {
5084 if (!isa<ConstantSDNode>(N))
5086 Val = cast<ConstantSDNode>(N)->getZExtValue();
5088 if (ST->isThumb1Only()) {
5089 if (Val <= 255 || ~Val <= 255)
5090 return DAG.getConstant(Val, dl, MVT::i32);
5092 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5093 return DAG.getConstant(Val, dl, MVT::i32);
5098 // If this is a case we can't handle, return null and let the default
5099 // expansion code take care of it.
5100 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5101 const ARMSubtarget *ST) const {
5102 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5104 EVT VT = Op.getValueType();
5106 APInt SplatBits, SplatUndef;
5107 unsigned SplatBitSize;
5109 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5110 if (SplatBitSize <= 64) {
5111 // Check if an immediate VMOV works.
5113 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5114 SplatUndef.getZExtValue(), SplatBitSize,
5115 DAG, dl, VmovVT, VT.is128BitVector(),
5117 if (Val.getNode()) {
5118 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5119 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5122 // Try an immediate VMVN.
5123 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5124 Val = isNEONModifiedImm(NegatedImm,
5125 SplatUndef.getZExtValue(), SplatBitSize,
5126 DAG, dl, VmovVT, VT.is128BitVector(),
5128 if (Val.getNode()) {
5129 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5130 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5133 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5134 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5135 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5137 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5138 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5144 // Scan through the operands to see if only one value is used.
5146 // As an optimisation, even if more than one value is used it may be more
5147 // profitable to splat with one value then change some lanes.
5149 // Heuristically we decide to do this if the vector has a "dominant" value,
5150 // defined as splatted to more than half of the lanes.
5151 unsigned NumElts = VT.getVectorNumElements();
5152 bool isOnlyLowElement = true;
5153 bool usesOnlyOneValue = true;
5154 bool hasDominantValue = false;
5155 bool isConstant = true;
5157 // Map of the number of times a particular SDValue appears in the
5159 DenseMap<SDValue, unsigned> ValueCounts;
5161 for (unsigned i = 0; i < NumElts; ++i) {
5162 SDValue V = Op.getOperand(i);
5163 if (V.getOpcode() == ISD::UNDEF)
5166 isOnlyLowElement = false;
5167 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5170 ValueCounts.insert(std::make_pair(V, 0));
5171 unsigned &Count = ValueCounts[V];
5173 // Is this value dominant? (takes up more than half of the lanes)
5174 if (++Count > (NumElts / 2)) {
5175 hasDominantValue = true;
5179 if (ValueCounts.size() != 1)
5180 usesOnlyOneValue = false;
5181 if (!Value.getNode() && ValueCounts.size() > 0)
5182 Value = ValueCounts.begin()->first;
5184 if (ValueCounts.size() == 0)
5185 return DAG.getUNDEF(VT);
5187 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5188 // Keep going if we are hitting this case.
5189 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5190 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5192 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5194 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5195 // i32 and try again.
5196 if (hasDominantValue && EltSize <= 32) {
5200 // If we are VDUPing a value that comes directly from a vector, that will
5201 // cause an unnecessary move to and from a GPR, where instead we could
5202 // just use VDUPLANE. We can only do this if the lane being extracted
5203 // is at a constant index, as the VDUP from lane instructions only have
5204 // constant-index forms.
5205 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5206 isa<ConstantSDNode>(Value->getOperand(1))) {
5207 // We need to create a new undef vector to use for the VDUPLANE if the
5208 // size of the vector from which we get the value is different than the
5209 // size of the vector that we need to create. We will insert the element
5210 // such that the register coalescer will remove unnecessary copies.
5211 if (VT != Value->getOperand(0).getValueType()) {
5212 ConstantSDNode *constIndex;
5213 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5214 assert(constIndex && "The index is not a constant!");
5215 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5216 VT.getVectorNumElements();
5217 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5218 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5219 Value, DAG.getConstant(index, dl, MVT::i32)),
5220 DAG.getConstant(index, dl, MVT::i32));
5222 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5223 Value->getOperand(0), Value->getOperand(1));
5225 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5227 if (!usesOnlyOneValue) {
5228 // The dominant value was splatted as 'N', but we now have to insert
5229 // all differing elements.
5230 for (unsigned I = 0; I < NumElts; ++I) {
5231 if (Op.getOperand(I) == Value)
5233 SmallVector<SDValue, 3> Ops;
5235 Ops.push_back(Op.getOperand(I));
5236 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5237 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5242 if (VT.getVectorElementType().isFloatingPoint()) {
5243 SmallVector<SDValue, 8> Ops;
5244 for (unsigned i = 0; i < NumElts; ++i)
5245 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5247 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5248 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5249 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5251 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5253 if (usesOnlyOneValue) {
5254 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5255 if (isConstant && Val.getNode())
5256 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5260 // If all elements are constants and the case above didn't get hit, fall back
5261 // to the default expansion, which will generate a load from the constant
5266 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5268 SDValue shuffle = ReconstructShuffle(Op, DAG);
5269 if (shuffle != SDValue())
5273 // Vectors with 32- or 64-bit elements can be built by directly assigning
5274 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5275 // will be legalized.
5276 if (EltSize >= 32) {
5277 // Do the expansion with floating-point types, since that is what the VFP
5278 // registers are defined to use, and since i64 is not legal.
5279 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5280 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5281 SmallVector<SDValue, 8> Ops;
5282 for (unsigned i = 0; i < NumElts; ++i)
5283 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5284 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5285 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5288 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5289 // know the default expansion would otherwise fall back on something even
5290 // worse. For a vector with one or two non-undef values, that's
5291 // scalar_to_vector for the elements followed by a shuffle (provided the
5292 // shuffle is valid for the target) and materialization element by element
5293 // on the stack followed by a load for everything else.
5294 if (!isConstant && !usesOnlyOneValue) {
5295 SDValue Vec = DAG.getUNDEF(VT);
5296 for (unsigned i = 0 ; i < NumElts; ++i) {
5297 SDValue V = Op.getOperand(i);
5298 if (V.getOpcode() == ISD::UNDEF)
5300 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5301 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5309 // Gather data to see if the operation can be modelled as a
5310 // shuffle in combination with VEXTs.
5311 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5312 SelectionDAG &DAG) const {
5314 EVT VT = Op.getValueType();
5315 unsigned NumElts = VT.getVectorNumElements();
5317 SmallVector<SDValue, 2> SourceVecs;
5318 SmallVector<unsigned, 2> MinElts;
5319 SmallVector<unsigned, 2> MaxElts;
5321 for (unsigned i = 0; i < NumElts; ++i) {
5322 SDValue V = Op.getOperand(i);
5323 if (V.getOpcode() == ISD::UNDEF)
5325 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5326 // A shuffle can only come from building a vector from various
5327 // elements of other vectors.
5329 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5330 VT.getVectorElementType()) {
5331 // This code doesn't know how to handle shuffles where the vector
5332 // element types do not match (this happens because type legalization
5333 // promotes the return type of EXTRACT_VECTOR_ELT).
5334 // FIXME: It might be appropriate to extend this code to handle
5335 // mismatched types.
5339 // Record this extraction against the appropriate vector if possible...
5340 SDValue SourceVec = V.getOperand(0);
5341 // If the element number isn't a constant, we can't effectively
5342 // analyze what's going on.
5343 if (!isa<ConstantSDNode>(V.getOperand(1)))
5345 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5346 bool FoundSource = false;
5347 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5348 if (SourceVecs[j] == SourceVec) {
5349 if (MinElts[j] > EltNo)
5351 if (MaxElts[j] < EltNo)
5358 // Or record a new source if not...
5360 SourceVecs.push_back(SourceVec);
5361 MinElts.push_back(EltNo);
5362 MaxElts.push_back(EltNo);
5366 // Currently only do something sane when at most two source vectors
5368 if (SourceVecs.size() > 2)
5371 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5372 int VEXTOffsets[2] = {0, 0};
5374 // This loop extracts the usage patterns of the source vectors
5375 // and prepares appropriate SDValues for a shuffle if possible.
5376 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5377 if (SourceVecs[i].getValueType() == VT) {
5378 // No VEXT necessary
5379 ShuffleSrcs[i] = SourceVecs[i];
5382 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5383 // It probably isn't worth padding out a smaller vector just to
5384 // break it down again in a shuffle.
5388 // Since only 64-bit and 128-bit vectors are legal on ARM and
5389 // we've eliminated the other cases...
5390 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5391 "unexpected vector sizes in ReconstructShuffle");
5393 if (MaxElts[i] - MinElts[i] >= NumElts) {
5394 // Span too large for a VEXT to cope
5398 if (MinElts[i] >= NumElts) {
5399 // The extraction can just take the second half
5400 VEXTOffsets[i] = NumElts;
5401 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5403 DAG.getIntPtrConstant(NumElts, dl));
5404 } else if (MaxElts[i] < NumElts) {
5405 // The extraction can just take the first half
5407 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5409 DAG.getIntPtrConstant(0, dl));
5411 // An actual VEXT is needed
5412 VEXTOffsets[i] = MinElts[i];
5413 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5415 DAG.getIntPtrConstant(0, dl));
5416 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5418 DAG.getIntPtrConstant(NumElts, dl));
5419 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5420 DAG.getConstant(VEXTOffsets[i], dl,
5425 SmallVector<int, 8> Mask;
5427 for (unsigned i = 0; i < NumElts; ++i) {
5428 SDValue Entry = Op.getOperand(i);
5429 if (Entry.getOpcode() == ISD::UNDEF) {
5434 SDValue ExtractVec = Entry.getOperand(0);
5435 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5436 .getOperand(1))->getSExtValue();
5437 if (ExtractVec == SourceVecs[0]) {
5438 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5440 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5444 // Final check before we try to produce nonsense...
5445 if (isShuffleMaskLegal(Mask, VT))
5446 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5452 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5453 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5454 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5455 /// are assumed to be legal.
5457 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5459 if (VT.getVectorNumElements() == 4 &&
5460 (VT.is128BitVector() || VT.is64BitVector())) {
5461 unsigned PFIndexes[4];
5462 for (unsigned i = 0; i != 4; ++i) {
5466 PFIndexes[i] = M[i];
5469 // Compute the index in the perfect shuffle table.
5470 unsigned PFTableIndex =
5471 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5472 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5473 unsigned Cost = (PFEntry >> 30);
5480 unsigned Imm, WhichResult;
5482 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5483 return (EltSize >= 32 ||
5484 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5485 isVREVMask(M, VT, 64) ||
5486 isVREVMask(M, VT, 32) ||
5487 isVREVMask(M, VT, 16) ||
5488 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5489 isVTBLMask(M, VT) ||
5490 isVTRNMask(M, VT, WhichResult) ||
5491 isVUZPMask(M, VT, WhichResult) ||
5492 isVZIPMask(M, VT, WhichResult) ||
5493 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5494 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5495 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5496 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5499 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5500 /// the specified operations to build the shuffle.
5501 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5502 SDValue RHS, SelectionDAG &DAG,
5504 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5505 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5506 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5509 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5518 OP_VUZPL, // VUZP, left result
5519 OP_VUZPR, // VUZP, right result
5520 OP_VZIPL, // VZIP, left result
5521 OP_VZIPR, // VZIP, right result
5522 OP_VTRNL, // VTRN, left result
5523 OP_VTRNR // VTRN, right result
5526 if (OpNum == OP_COPY) {
5527 if (LHSID == (1*9+2)*9+3) return LHS;
5528 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5532 SDValue OpLHS, OpRHS;
5533 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5534 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5535 EVT VT = OpLHS.getValueType();
5538 default: llvm_unreachable("Unknown shuffle opcode!");
5540 // VREV divides the vector in half and swaps within the half.
5541 if (VT.getVectorElementType() == MVT::i32 ||
5542 VT.getVectorElementType() == MVT::f32)
5543 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5544 // vrev <4 x i16> -> VREV32
5545 if (VT.getVectorElementType() == MVT::i16)
5546 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5547 // vrev <4 x i8> -> VREV16
5548 assert(VT.getVectorElementType() == MVT::i8);
5549 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5554 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5555 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5559 return DAG.getNode(ARMISD::VEXT, dl, VT,
5561 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5564 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5565 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5568 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5569 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5572 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5573 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5577 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5578 ArrayRef<int> ShuffleMask,
5579 SelectionDAG &DAG) {
5580 // Check to see if we can use the VTBL instruction.
5581 SDValue V1 = Op.getOperand(0);
5582 SDValue V2 = Op.getOperand(1);
5585 SmallVector<SDValue, 8> VTBLMask;
5586 for (ArrayRef<int>::iterator
5587 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5588 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5590 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5591 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5592 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5594 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5595 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5598 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5599 SelectionDAG &DAG) {
5601 SDValue OpLHS = Op.getOperand(0);
5602 EVT VT = OpLHS.getValueType();
5604 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5605 "Expect an v8i16/v16i8 type");
5606 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5607 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5608 // extract the first 8 bytes into the top double word and the last 8 bytes
5609 // into the bottom double word. The v8i16 case is similar.
5610 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5611 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5612 DAG.getConstant(ExtractNum, DL, MVT::i32));
5615 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5616 SDValue V1 = Op.getOperand(0);
5617 SDValue V2 = Op.getOperand(1);
5619 EVT VT = Op.getValueType();
5620 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5622 // Convert shuffles that are directly supported on NEON to target-specific
5623 // DAG nodes, instead of keeping them as shuffles and matching them again
5624 // during code selection. This is more efficient and avoids the possibility
5625 // of inconsistencies between legalization and selection.
5626 // FIXME: floating-point vectors should be canonicalized to integer vectors
5627 // of the same time so that they get CSEd properly.
5628 ArrayRef<int> ShuffleMask = SVN->getMask();
5630 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5631 if (EltSize <= 32) {
5632 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5633 int Lane = SVN->getSplatIndex();
5634 // If this is undef splat, generate it via "just" vdup, if possible.
5635 if (Lane == -1) Lane = 0;
5637 // Test if V1 is a SCALAR_TO_VECTOR.
5638 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5639 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5641 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5642 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5644 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5645 !isa<ConstantSDNode>(V1.getOperand(0))) {
5646 bool IsScalarToVector = true;
5647 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5648 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5649 IsScalarToVector = false;
5652 if (IsScalarToVector)
5653 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5655 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5656 DAG.getConstant(Lane, dl, MVT::i32));
5661 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5664 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5665 DAG.getConstant(Imm, dl, MVT::i32));
5668 if (isVREVMask(ShuffleMask, VT, 64))
5669 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5670 if (isVREVMask(ShuffleMask, VT, 32))
5671 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5672 if (isVREVMask(ShuffleMask, VT, 16))
5673 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5675 if (V2->getOpcode() == ISD::UNDEF &&
5676 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5677 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5678 DAG.getConstant(Imm, dl, MVT::i32));
5681 // Check for Neon shuffles that modify both input vectors in place.
5682 // If both results are used, i.e., if there are two shuffles with the same
5683 // source operands and with masks corresponding to both results of one of
5684 // these operations, DAG memoization will ensure that a single node is
5685 // used for both shuffles.
5686 unsigned WhichResult;
5687 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5688 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5689 V1, V2).getValue(WhichResult);
5690 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5691 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5692 V1, V2).getValue(WhichResult);
5693 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5694 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5695 V1, V2).getValue(WhichResult);
5697 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5698 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5699 V1, V1).getValue(WhichResult);
5700 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5701 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5702 V1, V1).getValue(WhichResult);
5703 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5704 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5705 V1, V1).getValue(WhichResult);
5708 // If the shuffle is not directly supported and it has 4 elements, use
5709 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5710 unsigned NumElts = VT.getVectorNumElements();
5712 unsigned PFIndexes[4];
5713 for (unsigned i = 0; i != 4; ++i) {
5714 if (ShuffleMask[i] < 0)
5717 PFIndexes[i] = ShuffleMask[i];
5720 // Compute the index in the perfect shuffle table.
5721 unsigned PFTableIndex =
5722 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5723 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5724 unsigned Cost = (PFEntry >> 30);
5727 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5730 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5731 if (EltSize >= 32) {
5732 // Do the expansion with floating-point types, since that is what the VFP
5733 // registers are defined to use, and since i64 is not legal.
5734 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5735 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5736 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5737 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5738 SmallVector<SDValue, 8> Ops;
5739 for (unsigned i = 0; i < NumElts; ++i) {
5740 if (ShuffleMask[i] < 0)
5741 Ops.push_back(DAG.getUNDEF(EltVT));
5743 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5744 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5745 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5748 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5749 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5752 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5753 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5755 if (VT == MVT::v8i8) {
5756 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5757 if (NewOp.getNode())
5764 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5765 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5766 SDValue Lane = Op.getOperand(2);
5767 if (!isa<ConstantSDNode>(Lane))
5773 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5774 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5775 SDValue Lane = Op.getOperand(1);
5776 if (!isa<ConstantSDNode>(Lane))
5779 SDValue Vec = Op.getOperand(0);
5780 if (Op.getValueType() == MVT::i32 &&
5781 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5783 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5789 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5790 // The only time a CONCAT_VECTORS operation can have legal types is when
5791 // two 64-bit vectors are concatenated to a 128-bit vector.
5792 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5793 "unexpected CONCAT_VECTORS");
5795 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5796 SDValue Op0 = Op.getOperand(0);
5797 SDValue Op1 = Op.getOperand(1);
5798 if (Op0.getOpcode() != ISD::UNDEF)
5799 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5800 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5801 DAG.getIntPtrConstant(0, dl));
5802 if (Op1.getOpcode() != ISD::UNDEF)
5803 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5804 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5805 DAG.getIntPtrConstant(1, dl));
5806 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5809 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5810 /// element has been zero/sign-extended, depending on the isSigned parameter,
5811 /// from an integer type half its size.
5812 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5814 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5815 EVT VT = N->getValueType(0);
5816 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5817 SDNode *BVN = N->getOperand(0).getNode();
5818 if (BVN->getValueType(0) != MVT::v4i32 ||
5819 BVN->getOpcode() != ISD::BUILD_VECTOR)
5821 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5822 unsigned HiElt = 1 - LoElt;
5823 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5824 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5825 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5826 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5827 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5830 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5831 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5834 if (Hi0->isNullValue() && Hi1->isNullValue())
5840 if (N->getOpcode() != ISD::BUILD_VECTOR)
5843 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5844 SDNode *Elt = N->getOperand(i).getNode();
5845 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5846 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5847 unsigned HalfSize = EltSize / 2;
5849 if (!isIntN(HalfSize, C->getSExtValue()))
5852 if (!isUIntN(HalfSize, C->getZExtValue()))
5863 /// isSignExtended - Check if a node is a vector value that is sign-extended
5864 /// or a constant BUILD_VECTOR with sign-extended elements.
5865 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5866 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5868 if (isExtendedBUILD_VECTOR(N, DAG, true))
5873 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5874 /// or a constant BUILD_VECTOR with zero-extended elements.
5875 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5876 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5878 if (isExtendedBUILD_VECTOR(N, DAG, false))
5883 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5884 if (OrigVT.getSizeInBits() >= 64)
5887 assert(OrigVT.isSimple() && "Expecting a simple value type");
5889 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5890 switch (OrigSimpleTy) {
5891 default: llvm_unreachable("Unexpected Vector Type");
5900 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5901 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5902 /// We insert the required extension here to get the vector to fill a D register.
5903 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5906 unsigned ExtOpcode) {
5907 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5908 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5909 // 64-bits we need to insert a new extension so that it will be 64-bits.
5910 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5911 if (OrigTy.getSizeInBits() >= 64)
5914 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5915 EVT NewVT = getExtensionTo64Bits(OrigTy);
5917 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5920 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5921 /// does not do any sign/zero extension. If the original vector is less
5922 /// than 64 bits, an appropriate extension will be added after the load to
5923 /// reach a total size of 64 bits. We have to add the extension separately
5924 /// because ARM does not have a sign/zero extending load for vectors.
5925 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5926 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5928 // The load already has the right type.
5929 if (ExtendedTy == LD->getMemoryVT())
5930 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5931 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5932 LD->isNonTemporal(), LD->isInvariant(),
5933 LD->getAlignment());
5935 // We need to create a zextload/sextload. We cannot just create a load
5936 // followed by a zext/zext node because LowerMUL is also run during normal
5937 // operation legalization where we can't create illegal types.
5938 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5939 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5940 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5941 LD->isNonTemporal(), LD->getAlignment());
5944 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5945 /// extending load, or BUILD_VECTOR with extended elements, return the
5946 /// unextended value. The unextended vector should be 64 bits so that it can
5947 /// be used as an operand to a VMULL instruction. If the original vector size
5948 /// before extension is less than 64 bits we add a an extension to resize
5949 /// the vector to 64 bits.
5950 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5951 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5952 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5953 N->getOperand(0)->getValueType(0),
5957 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5958 return SkipLoadExtensionForVMULL(LD, DAG);
5960 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5961 // have been legalized as a BITCAST from v4i32.
5962 if (N->getOpcode() == ISD::BITCAST) {
5963 SDNode *BVN = N->getOperand(0).getNode();
5964 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5965 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5966 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5967 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5968 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5970 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5971 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5972 EVT VT = N->getValueType(0);
5973 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5974 unsigned NumElts = VT.getVectorNumElements();
5975 MVT TruncVT = MVT::getIntegerVT(EltSize);
5976 SmallVector<SDValue, 8> Ops;
5978 for (unsigned i = 0; i != NumElts; ++i) {
5979 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5980 const APInt &CInt = C->getAPIntValue();
5981 // Element types smaller than 32 bits are not legal, so use i32 elements.
5982 // The values are implicitly truncated so sext vs. zext doesn't matter.
5983 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
5985 return DAG.getNode(ISD::BUILD_VECTOR, dl,
5986 MVT::getVectorVT(TruncVT, NumElts), Ops);
5989 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5990 unsigned Opcode = N->getOpcode();
5991 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5992 SDNode *N0 = N->getOperand(0).getNode();
5993 SDNode *N1 = N->getOperand(1).getNode();
5994 return N0->hasOneUse() && N1->hasOneUse() &&
5995 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6000 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6001 unsigned Opcode = N->getOpcode();
6002 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6003 SDNode *N0 = N->getOperand(0).getNode();
6004 SDNode *N1 = N->getOperand(1).getNode();
6005 return N0->hasOneUse() && N1->hasOneUse() &&
6006 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6011 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6012 // Multiplications are only custom-lowered for 128-bit vectors so that
6013 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6014 EVT VT = Op.getValueType();
6015 assert(VT.is128BitVector() && VT.isInteger() &&
6016 "unexpected type for custom-lowering ISD::MUL");
6017 SDNode *N0 = Op.getOperand(0).getNode();
6018 SDNode *N1 = Op.getOperand(1).getNode();
6019 unsigned NewOpc = 0;
6021 bool isN0SExt = isSignExtended(N0, DAG);
6022 bool isN1SExt = isSignExtended(N1, DAG);
6023 if (isN0SExt && isN1SExt)
6024 NewOpc = ARMISD::VMULLs;
6026 bool isN0ZExt = isZeroExtended(N0, DAG);
6027 bool isN1ZExt = isZeroExtended(N1, DAG);
6028 if (isN0ZExt && isN1ZExt)
6029 NewOpc = ARMISD::VMULLu;
6030 else if (isN1SExt || isN1ZExt) {
6031 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6032 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6033 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6034 NewOpc = ARMISD::VMULLs;
6036 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6037 NewOpc = ARMISD::VMULLu;
6039 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6041 NewOpc = ARMISD::VMULLu;
6047 if (VT == MVT::v2i64)
6048 // Fall through to expand this. It is not legal.
6051 // Other vector multiplications are legal.
6056 // Legalize to a VMULL instruction.
6059 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6061 Op0 = SkipExtensionForVMULL(N0, DAG);
6062 assert(Op0.getValueType().is64BitVector() &&
6063 Op1.getValueType().is64BitVector() &&
6064 "unexpected types for extended operands to VMULL");
6065 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6068 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6069 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6076 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6077 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6078 EVT Op1VT = Op1.getValueType();
6079 return DAG.getNode(N0->getOpcode(), DL, VT,
6080 DAG.getNode(NewOpc, DL, VT,
6081 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6082 DAG.getNode(NewOpc, DL, VT,
6083 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6087 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6089 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6090 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6091 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6092 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6093 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6094 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6095 // Get reciprocal estimate.
6096 // float4 recip = vrecpeq_f32(yf);
6097 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6098 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6100 // Because char has a smaller range than uchar, we can actually get away
6101 // without any newton steps. This requires that we use a weird bias
6102 // of 0xb000, however (again, this has been exhaustively tested).
6103 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6104 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6105 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6106 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6107 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6108 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6109 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6110 // Convert back to short.
6111 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6112 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6117 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6119 // Convert to float.
6120 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6121 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6122 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6123 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6124 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6125 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6127 // Use reciprocal estimate and one refinement step.
6128 // float4 recip = vrecpeq_f32(yf);
6129 // recip *= vrecpsq_f32(yf, recip);
6130 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6131 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6133 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6134 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6136 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6137 // Because short has a smaller range than ushort, we can actually get away
6138 // with only a single newton step. This requires that we use a weird bias
6139 // of 89, however (again, this has been exhaustively tested).
6140 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6141 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6142 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6143 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6144 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6145 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6146 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6147 // Convert back to integer and return.
6148 // return vmovn_s32(vcvt_s32_f32(result));
6149 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6150 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6154 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6155 EVT VT = Op.getValueType();
6156 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6157 "unexpected type for custom-lowering ISD::SDIV");
6160 SDValue N0 = Op.getOperand(0);
6161 SDValue N1 = Op.getOperand(1);
6164 if (VT == MVT::v8i8) {
6165 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6166 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6168 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6169 DAG.getIntPtrConstant(4, dl));
6170 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6171 DAG.getIntPtrConstant(4, dl));
6172 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6173 DAG.getIntPtrConstant(0, dl));
6174 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6175 DAG.getIntPtrConstant(0, dl));
6177 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6178 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6180 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6181 N0 = LowerCONCAT_VECTORS(N0, DAG);
6183 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6186 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6189 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6190 EVT VT = Op.getValueType();
6191 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6192 "unexpected type for custom-lowering ISD::UDIV");
6195 SDValue N0 = Op.getOperand(0);
6196 SDValue N1 = Op.getOperand(1);
6199 if (VT == MVT::v8i8) {
6200 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6201 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6203 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6204 DAG.getIntPtrConstant(4, dl));
6205 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6206 DAG.getIntPtrConstant(4, dl));
6207 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6208 DAG.getIntPtrConstant(0, dl));
6209 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6210 DAG.getIntPtrConstant(0, dl));
6212 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6213 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6215 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6216 N0 = LowerCONCAT_VECTORS(N0, DAG);
6218 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6219 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6225 // v4i16 sdiv ... Convert to float.
6226 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6227 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6228 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6229 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6230 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6231 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6233 // Use reciprocal estimate and two refinement steps.
6234 // float4 recip = vrecpeq_f32(yf);
6235 // recip *= vrecpsq_f32(yf, recip);
6236 // recip *= vrecpsq_f32(yf, recip);
6237 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6238 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6240 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6241 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6243 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6244 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6245 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6247 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6248 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6249 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6250 // and that it will never cause us to return an answer too large).
6251 // float4 result = as_float4(as_int4(xf*recip) + 2);
6252 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6253 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6254 N1 = DAG.getConstant(2, dl, MVT::i32);
6255 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6256 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6257 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6258 // Convert back to integer and return.
6259 // return vmovn_u32(vcvt_s32_f32(result));
6260 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6261 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6265 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6266 EVT VT = Op.getNode()->getValueType(0);
6267 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6270 bool ExtraOp = false;
6271 switch (Op.getOpcode()) {
6272 default: llvm_unreachable("Invalid code");
6273 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6274 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6275 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6276 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6280 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6282 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6283 Op.getOperand(1), Op.getOperand(2));
6286 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6287 assert(Subtarget->isTargetDarwin());
6289 // For iOS, we want to call an alternative entry point: __sincos_stret,
6290 // return values are passed via sret.
6292 SDValue Arg = Op.getOperand(0);
6293 EVT ArgVT = Arg.getValueType();
6294 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6296 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6297 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6299 // Pair of floats / doubles used to pass the result.
6300 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6302 // Create stack object for sret.
6303 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6304 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6305 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6306 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6312 Entry.Ty = RetTy->getPointerTo();
6313 Entry.isSExt = false;
6314 Entry.isZExt = false;
6315 Entry.isSRet = true;
6316 Args.push_back(Entry);
6320 Entry.isSExt = false;
6321 Entry.isZExt = false;
6322 Args.push_back(Entry);
6324 const char *LibcallName = (ArgVT == MVT::f64)
6325 ? "__sincos_stret" : "__sincosf_stret";
6326 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6328 TargetLowering::CallLoweringInfo CLI(DAG);
6329 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6330 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6332 .setDiscardResult();
6334 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6336 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6337 MachinePointerInfo(), false, false, false, 0);
6339 // Address of cos field.
6340 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6341 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6342 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6343 MachinePointerInfo(), false, false, false, 0);
6345 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6346 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6347 LoadSin.getValue(0), LoadCos.getValue(0));
6350 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6351 // Monotonic load/store is legal for all targets
6352 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6355 // Acquire/Release load/store is not legal for targets without a
6356 // dmb or equivalent available.
6360 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6361 SmallVectorImpl<SDValue> &Results,
6363 const ARMSubtarget *Subtarget) {
6365 SDValue Cycles32, OutChain;
6367 if (Subtarget->hasPerfMon()) {
6368 // Under Power Management extensions, the cycle-count is:
6369 // mrc p15, #0, <Rt>, c9, c13, #0
6370 SDValue Ops[] = { N->getOperand(0), // Chain
6371 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6372 DAG.getConstant(15, DL, MVT::i32),
6373 DAG.getConstant(0, DL, MVT::i32),
6374 DAG.getConstant(9, DL, MVT::i32),
6375 DAG.getConstant(13, DL, MVT::i32),
6376 DAG.getConstant(0, DL, MVT::i32)
6379 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6380 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6381 OutChain = Cycles32.getValue(1);
6383 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6384 // there are older ARM CPUs that have implementation-specific ways of
6385 // obtaining this information (FIXME!).
6386 Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6387 OutChain = DAG.getEntryNode();
6391 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6392 Cycles32, DAG.getConstant(0, DL, MVT::i32));
6393 Results.push_back(Cycles64);
6394 Results.push_back(OutChain);
6397 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6398 switch (Op.getOpcode()) {
6399 default: llvm_unreachable("Don't know how to custom lower this!");
6400 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6401 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6402 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6403 case ISD::GlobalAddress:
6404 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6405 default: llvm_unreachable("unknown object format");
6407 return LowerGlobalAddressWindows(Op, DAG);
6409 return LowerGlobalAddressELF(Op, DAG);
6411 return LowerGlobalAddressDarwin(Op, DAG);
6413 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6414 case ISD::SELECT: return LowerSELECT(Op, DAG);
6415 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6416 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6417 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6418 case ISD::VASTART: return LowerVASTART(Op, DAG);
6419 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6420 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6421 case ISD::SINT_TO_FP:
6422 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6423 case ISD::FP_TO_SINT:
6424 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6425 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6426 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6427 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6428 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6429 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6430 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6431 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6433 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6436 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6437 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6438 case ISD::SRL_PARTS:
6439 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6440 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6441 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6442 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6443 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6444 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6445 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6446 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6447 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6448 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6449 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6450 case ISD::MUL: return LowerMUL(Op, DAG);
6451 case ISD::SDIV: return LowerSDIV(Op, DAG);
6452 case ISD::UDIV: return LowerUDIV(Op, DAG);
6456 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6461 return LowerXALUO(Op, DAG);
6462 case ISD::ATOMIC_LOAD:
6463 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6464 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6466 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6467 case ISD::DYNAMIC_STACKALLOC:
6468 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6469 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6470 llvm_unreachable("Don't know how to custom lower this!");
6471 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6472 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6476 /// ReplaceNodeResults - Replace the results of node with an illegal result
6477 /// type with new values built out of custom code.
6478 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6479 SmallVectorImpl<SDValue>&Results,
6480 SelectionDAG &DAG) const {
6482 switch (N->getOpcode()) {
6484 llvm_unreachable("Don't know how to custom expand this!");
6485 case ISD::READ_REGISTER:
6486 ExpandREAD_REGISTER(N, Results, DAG);
6489 Res = ExpandBITCAST(N, DAG);
6493 Res = Expand64BitShift(N, DAG, Subtarget);
6495 case ISD::READCYCLECOUNTER:
6496 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6500 Results.push_back(Res);
6503 //===----------------------------------------------------------------------===//
6504 // ARM Scheduler Hooks
6505 //===----------------------------------------------------------------------===//
6507 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6508 /// registers the function context.
6509 void ARMTargetLowering::
6510 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6511 MachineBasicBlock *DispatchBB, int FI) const {
6512 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6513 DebugLoc dl = MI->getDebugLoc();
6514 MachineFunction *MF = MBB->getParent();
6515 MachineRegisterInfo *MRI = &MF->getRegInfo();
6516 MachineConstantPool *MCP = MF->getConstantPool();
6517 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6518 const Function *F = MF->getFunction();
6520 bool isThumb = Subtarget->isThumb();
6521 bool isThumb2 = Subtarget->isThumb2();
6523 unsigned PCLabelId = AFI->createPICLabelUId();
6524 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6525 ARMConstantPoolValue *CPV =
6526 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6527 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6529 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6530 : &ARM::GPRRegClass;
6532 // Grab constant pool and fixed stack memory operands.
6533 MachineMemOperand *CPMMO =
6534 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6535 MachineMemOperand::MOLoad, 4, 4);
6537 MachineMemOperand *FIMMOSt =
6538 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6539 MachineMemOperand::MOStore, 4, 4);
6541 // Load the address of the dispatch MBB into the jump buffer.
6543 // Incoming value: jbuf
6544 // ldr.n r5, LCPI1_1
6547 // str r5, [$jbuf, #+4] ; &jbuf[1]
6548 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6549 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6550 .addConstantPoolIndex(CPI)
6551 .addMemOperand(CPMMO));
6552 // Set the low bit because of thumb mode.
6553 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6555 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6556 .addReg(NewVReg1, RegState::Kill)
6558 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6559 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6560 .addReg(NewVReg2, RegState::Kill)
6562 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6563 .addReg(NewVReg3, RegState::Kill)
6565 .addImm(36) // &jbuf[1] :: pc
6566 .addMemOperand(FIMMOSt));
6567 } else if (isThumb) {
6568 // Incoming value: jbuf
6569 // ldr.n r1, LCPI1_4
6573 // add r2, $jbuf, #+4 ; &jbuf[1]
6575 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6576 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6577 .addConstantPoolIndex(CPI)
6578 .addMemOperand(CPMMO));
6579 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6580 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6581 .addReg(NewVReg1, RegState::Kill)
6583 // Set the low bit because of thumb mode.
6584 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6585 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6586 .addReg(ARM::CPSR, RegState::Define)
6588 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6589 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6590 .addReg(ARM::CPSR, RegState::Define)
6591 .addReg(NewVReg2, RegState::Kill)
6592 .addReg(NewVReg3, RegState::Kill));
6593 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6594 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6596 .addImm(36); // &jbuf[1] :: pc
6597 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6598 .addReg(NewVReg4, RegState::Kill)
6599 .addReg(NewVReg5, RegState::Kill)
6601 .addMemOperand(FIMMOSt));
6603 // Incoming value: jbuf
6606 // str r1, [$jbuf, #+4] ; &jbuf[1]
6607 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6608 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6609 .addConstantPoolIndex(CPI)
6611 .addMemOperand(CPMMO));
6612 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6613 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6614 .addReg(NewVReg1, RegState::Kill)
6615 .addImm(PCLabelId));
6616 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6617 .addReg(NewVReg2, RegState::Kill)
6619 .addImm(36) // &jbuf[1] :: pc
6620 .addMemOperand(FIMMOSt));
6624 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6625 MachineBasicBlock *MBB) const {
6626 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6627 DebugLoc dl = MI->getDebugLoc();
6628 MachineFunction *MF = MBB->getParent();
6629 MachineRegisterInfo *MRI = &MF->getRegInfo();
6630 MachineFrameInfo *MFI = MF->getFrameInfo();
6631 int FI = MFI->getFunctionContextIndex();
6633 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6634 : &ARM::GPRnopcRegClass;
6636 // Get a mapping of the call site numbers to all of the landing pads they're
6638 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6639 unsigned MaxCSNum = 0;
6640 MachineModuleInfo &MMI = MF->getMMI();
6641 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6643 if (!BB->isLandingPad()) continue;
6645 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6647 for (MachineBasicBlock::iterator
6648 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6649 if (!II->isEHLabel()) continue;
6651 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6652 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6654 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6655 for (SmallVectorImpl<unsigned>::iterator
6656 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6657 CSI != CSE; ++CSI) {
6658 CallSiteNumToLPad[*CSI].push_back(BB);
6659 MaxCSNum = std::max(MaxCSNum, *CSI);
6665 // Get an ordered list of the machine basic blocks for the jump table.
6666 std::vector<MachineBasicBlock*> LPadList;
6667 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6668 LPadList.reserve(CallSiteNumToLPad.size());
6669 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6670 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6671 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6672 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6673 LPadList.push_back(*II);
6674 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6678 assert(!LPadList.empty() &&
6679 "No landing pad destinations for the dispatch jump table!");
6681 // Create the jump table and associated information.
6682 MachineJumpTableInfo *JTI =
6683 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6684 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6685 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6687 // Create the MBBs for the dispatch code.
6689 // Shove the dispatch's address into the return slot in the function context.
6690 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6691 DispatchBB->setIsLandingPad();
6693 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6694 unsigned trap_opcode;
6695 if (Subtarget->isThumb())
6696 trap_opcode = ARM::tTRAP;
6698 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6700 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6701 DispatchBB->addSuccessor(TrapBB);
6703 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6704 DispatchBB->addSuccessor(DispContBB);
6707 MF->insert(MF->end(), DispatchBB);
6708 MF->insert(MF->end(), DispContBB);
6709 MF->insert(MF->end(), TrapBB);
6711 // Insert code into the entry block that creates and registers the function
6713 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6715 MachineMemOperand *FIMMOLd =
6716 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6717 MachineMemOperand::MOLoad |
6718 MachineMemOperand::MOVolatile, 4, 4);
6720 MachineInstrBuilder MIB;
6721 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6723 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6724 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6726 // Add a register mask with no preserved registers. This results in all
6727 // registers being marked as clobbered.
6728 MIB.addRegMask(RI.getNoPreservedMask());
6730 unsigned NumLPads = LPadList.size();
6731 if (Subtarget->isThumb2()) {
6732 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6733 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6736 .addMemOperand(FIMMOLd));
6738 if (NumLPads < 256) {
6739 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6741 .addImm(LPadList.size()));
6743 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6744 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6745 .addImm(NumLPads & 0xFFFF));
6747 unsigned VReg2 = VReg1;
6748 if ((NumLPads & 0xFFFF0000) != 0) {
6749 VReg2 = MRI->createVirtualRegister(TRC);
6750 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6752 .addImm(NumLPads >> 16));
6755 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6760 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6765 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6766 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6767 .addJumpTableIndex(MJTI));
6769 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6772 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6773 .addReg(NewVReg3, RegState::Kill)
6775 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6777 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6778 .addReg(NewVReg4, RegState::Kill)
6780 .addJumpTableIndex(MJTI);
6781 } else if (Subtarget->isThumb()) {
6782 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6783 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6786 .addMemOperand(FIMMOLd));
6788 if (NumLPads < 256) {
6789 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6793 MachineConstantPool *ConstantPool = MF->getConstantPool();
6794 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6795 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6797 // MachineConstantPool wants an explicit alignment.
6798 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6800 Align = getDataLayout()->getTypeAllocSize(C->getType());
6801 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6803 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6804 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6805 .addReg(VReg1, RegState::Define)
6806 .addConstantPoolIndex(Idx));
6807 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6812 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6817 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6818 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6819 .addReg(ARM::CPSR, RegState::Define)
6823 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6824 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6825 .addJumpTableIndex(MJTI));
6827 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6828 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6829 .addReg(ARM::CPSR, RegState::Define)
6830 .addReg(NewVReg2, RegState::Kill)
6833 MachineMemOperand *JTMMOLd =
6834 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6835 MachineMemOperand::MOLoad, 4, 4);
6837 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6838 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6839 .addReg(NewVReg4, RegState::Kill)
6841 .addMemOperand(JTMMOLd));
6843 unsigned NewVReg6 = NewVReg5;
6844 if (RelocM == Reloc::PIC_) {
6845 NewVReg6 = MRI->createVirtualRegister(TRC);
6846 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6847 .addReg(ARM::CPSR, RegState::Define)
6848 .addReg(NewVReg5, RegState::Kill)
6852 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6853 .addReg(NewVReg6, RegState::Kill)
6854 .addJumpTableIndex(MJTI);
6856 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6857 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6860 .addMemOperand(FIMMOLd));
6862 if (NumLPads < 256) {
6863 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6866 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6867 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6868 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6869 .addImm(NumLPads & 0xFFFF));
6871 unsigned VReg2 = VReg1;
6872 if ((NumLPads & 0xFFFF0000) != 0) {
6873 VReg2 = MRI->createVirtualRegister(TRC);
6874 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6876 .addImm(NumLPads >> 16));
6879 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6883 MachineConstantPool *ConstantPool = MF->getConstantPool();
6884 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6885 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6887 // MachineConstantPool wants an explicit alignment.
6888 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6890 Align = getDataLayout()->getTypeAllocSize(C->getType());
6891 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6893 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6894 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6895 .addReg(VReg1, RegState::Define)
6896 .addConstantPoolIndex(Idx)
6898 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6900 .addReg(VReg1, RegState::Kill));
6903 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6908 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6910 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6912 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6913 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6914 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6915 .addJumpTableIndex(MJTI));
6917 MachineMemOperand *JTMMOLd =
6918 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6919 MachineMemOperand::MOLoad, 4, 4);
6920 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6922 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6923 .addReg(NewVReg3, RegState::Kill)
6926 .addMemOperand(JTMMOLd));
6928 if (RelocM == Reloc::PIC_) {
6929 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6930 .addReg(NewVReg5, RegState::Kill)
6932 .addJumpTableIndex(MJTI);
6934 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6935 .addReg(NewVReg5, RegState::Kill)
6936 .addJumpTableIndex(MJTI);
6940 // Add the jump table entries as successors to the MBB.
6941 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6942 for (std::vector<MachineBasicBlock*>::iterator
6943 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6944 MachineBasicBlock *CurMBB = *I;
6945 if (SeenMBBs.insert(CurMBB).second)
6946 DispContBB->addSuccessor(CurMBB);
6949 // N.B. the order the invoke BBs are processed in doesn't matter here.
6950 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6951 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6952 for (MachineBasicBlock *BB : InvokeBBs) {
6954 // Remove the landing pad successor from the invoke block and replace it
6955 // with the new dispatch block.
6956 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6958 while (!Successors.empty()) {
6959 MachineBasicBlock *SMBB = Successors.pop_back_val();
6960 if (SMBB->isLandingPad()) {
6961 BB->removeSuccessor(SMBB);
6962 MBBLPads.push_back(SMBB);
6966 BB->addSuccessor(DispatchBB);
6968 // Find the invoke call and mark all of the callee-saved registers as
6969 // 'implicit defined' so that they're spilled. This prevents code from
6970 // moving instructions to before the EH block, where they will never be
6972 for (MachineBasicBlock::reverse_iterator
6973 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6974 if (!II->isCall()) continue;
6976 DenseMap<unsigned, bool> DefRegs;
6977 for (MachineInstr::mop_iterator
6978 OI = II->operands_begin(), OE = II->operands_end();
6980 if (!OI->isReg()) continue;
6981 DefRegs[OI->getReg()] = true;
6984 MachineInstrBuilder MIB(*MF, &*II);
6986 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6987 unsigned Reg = SavedRegs[i];
6988 if (Subtarget->isThumb2() &&
6989 !ARM::tGPRRegClass.contains(Reg) &&
6990 !ARM::hGPRRegClass.contains(Reg))
6992 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6994 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6997 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7004 // Mark all former landing pads as non-landing pads. The dispatch is the only
7006 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7007 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7008 (*I)->setIsLandingPad(false);
7010 // The instruction is gone now.
7011 MI->eraseFromParent();
7015 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7016 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7017 E = MBB->succ_end(); I != E; ++I)
7020 llvm_unreachable("Expecting a BB with two successors!");
7023 /// Return the load opcode for a given load size. If load size >= 8,
7024 /// neon opcode will be returned.
7025 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7027 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7028 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7030 return LdSize == 4 ? ARM::tLDRi
7031 : LdSize == 2 ? ARM::tLDRHi
7032 : LdSize == 1 ? ARM::tLDRBi : 0;
7034 return LdSize == 4 ? ARM::t2LDR_POST
7035 : LdSize == 2 ? ARM::t2LDRH_POST
7036 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7037 return LdSize == 4 ? ARM::LDR_POST_IMM
7038 : LdSize == 2 ? ARM::LDRH_POST
7039 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7042 /// Return the store opcode for a given store size. If store size >= 8,
7043 /// neon opcode will be returned.
7044 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7046 return StSize == 16 ? ARM::VST1q32wb_fixed
7047 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7049 return StSize == 4 ? ARM::tSTRi
7050 : StSize == 2 ? ARM::tSTRHi
7051 : StSize == 1 ? ARM::tSTRBi : 0;
7053 return StSize == 4 ? ARM::t2STR_POST
7054 : StSize == 2 ? ARM::t2STRH_POST
7055 : StSize == 1 ? ARM::t2STRB_POST : 0;
7056 return StSize == 4 ? ARM::STR_POST_IMM
7057 : StSize == 2 ? ARM::STRH_POST
7058 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7061 /// Emit a post-increment load operation with given size. The instructions
7062 /// will be added to BB at Pos.
7063 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7064 const TargetInstrInfo *TII, DebugLoc dl,
7065 unsigned LdSize, unsigned Data, unsigned AddrIn,
7066 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7067 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7068 assert(LdOpc != 0 && "Should have a load opcode");
7070 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7071 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7073 } else if (IsThumb1) {
7074 // load + update AddrIn
7075 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7076 .addReg(AddrIn).addImm(0));
7077 MachineInstrBuilder MIB =
7078 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7079 MIB = AddDefaultT1CC(MIB);
7080 MIB.addReg(AddrIn).addImm(LdSize);
7081 AddDefaultPred(MIB);
7082 } else if (IsThumb2) {
7083 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7084 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7087 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7088 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7089 .addReg(0).addImm(LdSize));
7093 /// Emit a post-increment store operation with given size. The instructions
7094 /// will be added to BB at Pos.
7095 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7096 const TargetInstrInfo *TII, DebugLoc dl,
7097 unsigned StSize, unsigned Data, unsigned AddrIn,
7098 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7099 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7100 assert(StOpc != 0 && "Should have a store opcode");
7102 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7103 .addReg(AddrIn).addImm(0).addReg(Data));
7104 } else if (IsThumb1) {
7105 // store + update AddrIn
7106 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7107 .addReg(AddrIn).addImm(0));
7108 MachineInstrBuilder MIB =
7109 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7110 MIB = AddDefaultT1CC(MIB);
7111 MIB.addReg(AddrIn).addImm(StSize);
7112 AddDefaultPred(MIB);
7113 } else if (IsThumb2) {
7114 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7115 .addReg(Data).addReg(AddrIn).addImm(StSize));
7117 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7118 .addReg(Data).addReg(AddrIn).addReg(0)
7124 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7125 MachineBasicBlock *BB) const {
7126 // This pseudo instruction has 3 operands: dst, src, size
7127 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7128 // Otherwise, we will generate unrolled scalar copies.
7129 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7130 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7131 MachineFunction::iterator It = BB;
7134 unsigned dest = MI->getOperand(0).getReg();
7135 unsigned src = MI->getOperand(1).getReg();
7136 unsigned SizeVal = MI->getOperand(2).getImm();
7137 unsigned Align = MI->getOperand(3).getImm();
7138 DebugLoc dl = MI->getDebugLoc();
7140 MachineFunction *MF = BB->getParent();
7141 MachineRegisterInfo &MRI = MF->getRegInfo();
7142 unsigned UnitSize = 0;
7143 const TargetRegisterClass *TRC = nullptr;
7144 const TargetRegisterClass *VecTRC = nullptr;
7146 bool IsThumb1 = Subtarget->isThumb1Only();
7147 bool IsThumb2 = Subtarget->isThumb2();
7151 } else if (Align & 2) {
7154 // Check whether we can use NEON instructions.
7155 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7156 Subtarget->hasNEON()) {
7157 if ((Align % 16 == 0) && SizeVal >= 16)
7159 else if ((Align % 8 == 0) && SizeVal >= 8)
7162 // Can't use NEON instructions.
7167 // Select the correct opcode and register class for unit size load/store
7168 bool IsNeon = UnitSize >= 8;
7169 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7171 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7172 : UnitSize == 8 ? &ARM::DPRRegClass
7175 unsigned BytesLeft = SizeVal % UnitSize;
7176 unsigned LoopSize = SizeVal - BytesLeft;
7178 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7179 // Use LDR and STR to copy.
7180 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7181 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7182 unsigned srcIn = src;
7183 unsigned destIn = dest;
7184 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7185 unsigned srcOut = MRI.createVirtualRegister(TRC);
7186 unsigned destOut = MRI.createVirtualRegister(TRC);
7187 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7188 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7189 IsThumb1, IsThumb2);
7190 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7191 IsThumb1, IsThumb2);
7196 // Handle the leftover bytes with LDRB and STRB.
7197 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7198 // [destOut] = STRB_POST(scratch, destIn, 1)
7199 for (unsigned i = 0; i < BytesLeft; i++) {
7200 unsigned srcOut = MRI.createVirtualRegister(TRC);
7201 unsigned destOut = MRI.createVirtualRegister(TRC);
7202 unsigned scratch = MRI.createVirtualRegister(TRC);
7203 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7204 IsThumb1, IsThumb2);
7205 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7206 IsThumb1, IsThumb2);
7210 MI->eraseFromParent(); // The instruction is gone now.
7214 // Expand the pseudo op to a loop.
7217 // movw varEnd, # --> with thumb2
7219 // ldrcp varEnd, idx --> without thumb2
7220 // fallthrough --> loopMBB
7222 // PHI varPhi, varEnd, varLoop
7223 // PHI srcPhi, src, srcLoop
7224 // PHI destPhi, dst, destLoop
7225 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7226 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7227 // subs varLoop, varPhi, #UnitSize
7229 // fallthrough --> exitMBB
7231 // epilogue to handle left-over bytes
7232 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7233 // [destOut] = STRB_POST(scratch, destLoop, 1)
7234 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7235 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7236 MF->insert(It, loopMBB);
7237 MF->insert(It, exitMBB);
7239 // Transfer the remainder of BB and its successor edges to exitMBB.
7240 exitMBB->splice(exitMBB->begin(), BB,
7241 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7242 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7244 // Load an immediate to varEnd.
7245 unsigned varEnd = MRI.createVirtualRegister(TRC);
7246 if (Subtarget->useMovt(*MF)) {
7247 unsigned Vtmp = varEnd;
7248 if ((LoopSize & 0xFFFF0000) != 0)
7249 Vtmp = MRI.createVirtualRegister(TRC);
7250 AddDefaultPred(BuildMI(BB, dl,
7251 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7252 Vtmp).addImm(LoopSize & 0xFFFF));
7254 if ((LoopSize & 0xFFFF0000) != 0)
7255 AddDefaultPred(BuildMI(BB, dl,
7256 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7259 .addImm(LoopSize >> 16));
7261 MachineConstantPool *ConstantPool = MF->getConstantPool();
7262 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7263 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7265 // MachineConstantPool wants an explicit alignment.
7266 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7268 Align = getDataLayout()->getTypeAllocSize(C->getType());
7269 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7272 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7273 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7275 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7276 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7278 BB->addSuccessor(loopMBB);
7280 // Generate the loop body:
7281 // varPhi = PHI(varLoop, varEnd)
7282 // srcPhi = PHI(srcLoop, src)
7283 // destPhi = PHI(destLoop, dst)
7284 MachineBasicBlock *entryBB = BB;
7286 unsigned varLoop = MRI.createVirtualRegister(TRC);
7287 unsigned varPhi = MRI.createVirtualRegister(TRC);
7288 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7289 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7290 unsigned destLoop = MRI.createVirtualRegister(TRC);
7291 unsigned destPhi = MRI.createVirtualRegister(TRC);
7293 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7294 .addReg(varLoop).addMBB(loopMBB)
7295 .addReg(varEnd).addMBB(entryBB);
7296 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7297 .addReg(srcLoop).addMBB(loopMBB)
7298 .addReg(src).addMBB(entryBB);
7299 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7300 .addReg(destLoop).addMBB(loopMBB)
7301 .addReg(dest).addMBB(entryBB);
7303 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7304 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7305 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7306 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7307 IsThumb1, IsThumb2);
7308 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7309 IsThumb1, IsThumb2);
7311 // Decrement loop variable by UnitSize.
7313 MachineInstrBuilder MIB =
7314 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7315 MIB = AddDefaultT1CC(MIB);
7316 MIB.addReg(varPhi).addImm(UnitSize);
7317 AddDefaultPred(MIB);
7319 MachineInstrBuilder MIB =
7320 BuildMI(*BB, BB->end(), dl,
7321 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7322 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7323 MIB->getOperand(5).setReg(ARM::CPSR);
7324 MIB->getOperand(5).setIsDef(true);
7326 BuildMI(*BB, BB->end(), dl,
7327 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7328 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7330 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7331 BB->addSuccessor(loopMBB);
7332 BB->addSuccessor(exitMBB);
7334 // Add epilogue to handle BytesLeft.
7336 MachineInstr *StartOfExit = exitMBB->begin();
7338 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7339 // [destOut] = STRB_POST(scratch, destLoop, 1)
7340 unsigned srcIn = srcLoop;
7341 unsigned destIn = destLoop;
7342 for (unsigned i = 0; i < BytesLeft; i++) {
7343 unsigned srcOut = MRI.createVirtualRegister(TRC);
7344 unsigned destOut = MRI.createVirtualRegister(TRC);
7345 unsigned scratch = MRI.createVirtualRegister(TRC);
7346 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7347 IsThumb1, IsThumb2);
7348 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7349 IsThumb1, IsThumb2);
7354 MI->eraseFromParent(); // The instruction is gone now.
7359 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7360 MachineBasicBlock *MBB) const {
7361 const TargetMachine &TM = getTargetMachine();
7362 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7363 DebugLoc DL = MI->getDebugLoc();
7365 assert(Subtarget->isTargetWindows() &&
7366 "__chkstk is only supported on Windows");
7367 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7369 // __chkstk takes the number of words to allocate on the stack in R4, and
7370 // returns the stack adjustment in number of bytes in R4. This will not
7371 // clober any other registers (other than the obvious lr).
7373 // Although, technically, IP should be considered a register which may be
7374 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7375 // thumb-2 environment, so there is no interworking required. As a result, we
7376 // do not expect a veneer to be emitted by the linker, clobbering IP.
7378 // Each module receives its own copy of __chkstk, so no import thunk is
7379 // required, again, ensuring that IP is not clobbered.
7381 // Finally, although some linkers may theoretically provide a trampoline for
7382 // out of range calls (which is quite common due to a 32M range limitation of
7383 // branches for Thumb), we can generate the long-call version via
7384 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7387 switch (TM.getCodeModel()) {
7388 case CodeModel::Small:
7389 case CodeModel::Medium:
7390 case CodeModel::Default:
7391 case CodeModel::Kernel:
7392 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7393 .addImm((unsigned)ARMCC::AL).addReg(0)
7394 .addExternalSymbol("__chkstk")
7395 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7396 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7397 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7399 case CodeModel::Large:
7400 case CodeModel::JITDefault: {
7401 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7402 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7404 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7405 .addExternalSymbol("__chkstk");
7406 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7407 .addImm((unsigned)ARMCC::AL).addReg(0)
7408 .addReg(Reg, RegState::Kill)
7409 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7410 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7411 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7416 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7418 .addReg(ARM::SP).addReg(ARM::R4)));
7420 MI->eraseFromParent();
7425 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7426 MachineBasicBlock *BB) const {
7427 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7428 DebugLoc dl = MI->getDebugLoc();
7429 bool isThumb2 = Subtarget->isThumb2();
7430 switch (MI->getOpcode()) {
7433 llvm_unreachable("Unexpected instr type to insert");
7435 // The Thumb2 pre-indexed stores have the same MI operands, they just
7436 // define them differently in the .td files from the isel patterns, so
7437 // they need pseudos.
7438 case ARM::t2STR_preidx:
7439 MI->setDesc(TII->get(ARM::t2STR_PRE));
7441 case ARM::t2STRB_preidx:
7442 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7444 case ARM::t2STRH_preidx:
7445 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7448 case ARM::STRi_preidx:
7449 case ARM::STRBi_preidx: {
7450 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7451 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7452 // Decode the offset.
7453 unsigned Offset = MI->getOperand(4).getImm();
7454 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7455 Offset = ARM_AM::getAM2Offset(Offset);
7459 MachineMemOperand *MMO = *MI->memoperands_begin();
7460 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7461 .addOperand(MI->getOperand(0)) // Rn_wb
7462 .addOperand(MI->getOperand(1)) // Rt
7463 .addOperand(MI->getOperand(2)) // Rn
7464 .addImm(Offset) // offset (skip GPR==zero_reg)
7465 .addOperand(MI->getOperand(5)) // pred
7466 .addOperand(MI->getOperand(6))
7467 .addMemOperand(MMO);
7468 MI->eraseFromParent();
7471 case ARM::STRr_preidx:
7472 case ARM::STRBr_preidx:
7473 case ARM::STRH_preidx: {
7475 switch (MI->getOpcode()) {
7476 default: llvm_unreachable("unexpected opcode!");
7477 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7478 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7479 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7481 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7482 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7483 MIB.addOperand(MI->getOperand(i));
7484 MI->eraseFromParent();
7488 case ARM::tMOVCCr_pseudo: {
7489 // To "insert" a SELECT_CC instruction, we actually have to insert the
7490 // diamond control-flow pattern. The incoming instruction knows the
7491 // destination vreg to set, the condition code register to branch on, the
7492 // true/false values to select between, and a branch opcode to use.
7493 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7494 MachineFunction::iterator It = BB;
7500 // cmpTY ccX, r1, r2
7502 // fallthrough --> copy0MBB
7503 MachineBasicBlock *thisMBB = BB;
7504 MachineFunction *F = BB->getParent();
7505 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7506 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7507 F->insert(It, copy0MBB);
7508 F->insert(It, sinkMBB);
7510 // Transfer the remainder of BB and its successor edges to sinkMBB.
7511 sinkMBB->splice(sinkMBB->begin(), BB,
7512 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7513 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7515 BB->addSuccessor(copy0MBB);
7516 BB->addSuccessor(sinkMBB);
7518 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7519 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7522 // %FalseValue = ...
7523 // # fallthrough to sinkMBB
7526 // Update machine-CFG edges
7527 BB->addSuccessor(sinkMBB);
7530 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7533 BuildMI(*BB, BB->begin(), dl,
7534 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7535 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7536 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7538 MI->eraseFromParent(); // The pseudo instruction is gone now.
7543 case ARM::BCCZi64: {
7544 // If there is an unconditional branch to the other successor, remove it.
7545 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7547 // Compare both parts that make up the double comparison separately for
7549 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7551 unsigned LHS1 = MI->getOperand(1).getReg();
7552 unsigned LHS2 = MI->getOperand(2).getReg();
7554 AddDefaultPred(BuildMI(BB, dl,
7555 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7556 .addReg(LHS1).addImm(0));
7557 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7558 .addReg(LHS2).addImm(0)
7559 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7561 unsigned RHS1 = MI->getOperand(3).getReg();
7562 unsigned RHS2 = MI->getOperand(4).getReg();
7563 AddDefaultPred(BuildMI(BB, dl,
7564 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7565 .addReg(LHS1).addReg(RHS1));
7566 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7567 .addReg(LHS2).addReg(RHS2)
7568 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7571 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7572 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7573 if (MI->getOperand(0).getImm() == ARMCC::NE)
7574 std::swap(destMBB, exitMBB);
7576 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7577 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7579 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7581 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7583 MI->eraseFromParent(); // The pseudo instruction is gone now.
7587 case ARM::Int_eh_sjlj_setjmp:
7588 case ARM::Int_eh_sjlj_setjmp_nofp:
7589 case ARM::tInt_eh_sjlj_setjmp:
7590 case ARM::t2Int_eh_sjlj_setjmp:
7591 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7592 EmitSjLjDispatchBlock(MI, BB);
7597 // To insert an ABS instruction, we have to insert the
7598 // diamond control-flow pattern. The incoming instruction knows the
7599 // source vreg to test against 0, the destination vreg to set,
7600 // the condition code register to branch on, the
7601 // true/false values to select between, and a branch opcode to use.
7606 // BCC (branch to SinkBB if V0 >= 0)
7607 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7608 // SinkBB: V1 = PHI(V2, V3)
7609 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7610 MachineFunction::iterator BBI = BB;
7612 MachineFunction *Fn = BB->getParent();
7613 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7614 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7615 Fn->insert(BBI, RSBBB);
7616 Fn->insert(BBI, SinkBB);
7618 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7619 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7620 bool ABSSrcKIll = MI->getOperand(1).isKill();
7621 bool isThumb2 = Subtarget->isThumb2();
7622 MachineRegisterInfo &MRI = Fn->getRegInfo();
7623 // In Thumb mode S must not be specified if source register is the SP or
7624 // PC and if destination register is the SP, so restrict register class
7625 unsigned NewRsbDstReg =
7626 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7628 // Transfer the remainder of BB and its successor edges to sinkMBB.
7629 SinkBB->splice(SinkBB->begin(), BB,
7630 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7631 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7633 BB->addSuccessor(RSBBB);
7634 BB->addSuccessor(SinkBB);
7636 // fall through to SinkMBB
7637 RSBBB->addSuccessor(SinkBB);
7639 // insert a cmp at the end of BB
7640 AddDefaultPred(BuildMI(BB, dl,
7641 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7642 .addReg(ABSSrcReg).addImm(0));
7644 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7646 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7647 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7649 // insert rsbri in RSBBB
7650 // Note: BCC and rsbri will be converted into predicated rsbmi
7651 // by if-conversion pass
7652 BuildMI(*RSBBB, RSBBB->begin(), dl,
7653 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7654 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7655 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7657 // insert PHI in SinkBB,
7658 // reuse ABSDstReg to not change uses of ABS instruction
7659 BuildMI(*SinkBB, SinkBB->begin(), dl,
7660 TII->get(ARM::PHI), ABSDstReg)
7661 .addReg(NewRsbDstReg).addMBB(RSBBB)
7662 .addReg(ABSSrcReg).addMBB(BB);
7664 // remove ABS instruction
7665 MI->eraseFromParent();
7667 // return last added BB
7670 case ARM::COPY_STRUCT_BYVAL_I32:
7672 return EmitStructByval(MI, BB);
7673 case ARM::WIN__CHKSTK:
7674 return EmitLowered__chkstk(MI, BB);
7678 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7679 SDNode *Node) const {
7680 const MCInstrDesc *MCID = &MI->getDesc();
7681 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7682 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7683 // operand is still set to noreg. If needed, set the optional operand's
7684 // register to CPSR, and remove the redundant implicit def.
7686 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7688 // Rename pseudo opcodes.
7689 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7691 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7692 MCID = &TII->get(NewOpc);
7694 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7695 "converted opcode should be the same except for cc_out");
7699 // Add the optional cc_out operand
7700 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7702 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7704 // Any ARM instruction that sets the 's' bit should specify an optional
7705 // "cc_out" operand in the last operand position.
7706 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7707 assert(!NewOpc && "Optional cc_out operand required");
7710 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7711 // since we already have an optional CPSR def.
7712 bool definesCPSR = false;
7713 bool deadCPSR = false;
7714 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7716 const MachineOperand &MO = MI->getOperand(i);
7717 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7721 MI->RemoveOperand(i);
7726 assert(!NewOpc && "Optional cc_out operand required");
7729 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7731 assert(!MI->getOperand(ccOutIdx).getReg() &&
7732 "expect uninitialized optional cc_out operand");
7736 // If this instruction was defined with an optional CPSR def and its dag node
7737 // had a live implicit CPSR def, then activate the optional CPSR def.
7738 MachineOperand &MO = MI->getOperand(ccOutIdx);
7739 MO.setReg(ARM::CPSR);
7743 //===----------------------------------------------------------------------===//
7744 // ARM Optimization Hooks
7745 //===----------------------------------------------------------------------===//
7747 // Helper function that checks if N is a null or all ones constant.
7748 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7749 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7752 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7755 // Return true if N is conditionally 0 or all ones.
7756 // Detects these expressions where cc is an i1 value:
7758 // (select cc 0, y) [AllOnes=0]
7759 // (select cc y, 0) [AllOnes=0]
7760 // (zext cc) [AllOnes=0]
7761 // (sext cc) [AllOnes=0/1]
7762 // (select cc -1, y) [AllOnes=1]
7763 // (select cc y, -1) [AllOnes=1]
7765 // Invert is set when N is the null/all ones constant when CC is false.
7766 // OtherOp is set to the alternative value of N.
7767 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7768 SDValue &CC, bool &Invert,
7770 SelectionDAG &DAG) {
7771 switch (N->getOpcode()) {
7772 default: return false;
7774 CC = N->getOperand(0);
7775 SDValue N1 = N->getOperand(1);
7776 SDValue N2 = N->getOperand(2);
7777 if (isZeroOrAllOnes(N1, AllOnes)) {
7782 if (isZeroOrAllOnes(N2, AllOnes)) {
7789 case ISD::ZERO_EXTEND:
7790 // (zext cc) can never be the all ones value.
7794 case ISD::SIGN_EXTEND: {
7796 EVT VT = N->getValueType(0);
7797 CC = N->getOperand(0);
7798 if (CC.getValueType() != MVT::i1)
7802 // When looking for an AllOnes constant, N is an sext, and the 'other'
7804 OtherOp = DAG.getConstant(0, dl, VT);
7805 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7806 // When looking for a 0 constant, N can be zext or sext.
7807 OtherOp = DAG.getConstant(1, dl, VT);
7809 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7816 // Combine a constant select operand into its use:
7818 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7819 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7820 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7821 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7822 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7824 // The transform is rejected if the select doesn't have a constant operand that
7825 // is null, or all ones when AllOnes is set.
7827 // Also recognize sext/zext from i1:
7829 // (add (zext cc), x) -> (select cc (add x, 1), x)
7830 // (add (sext cc), x) -> (select cc (add x, -1), x)
7832 // These transformations eventually create predicated instructions.
7834 // @param N The node to transform.
7835 // @param Slct The N operand that is a select.
7836 // @param OtherOp The other N operand (x above).
7837 // @param DCI Context.
7838 // @param AllOnes Require the select constant to be all ones instead of null.
7839 // @returns The new node, or SDValue() on failure.
7841 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7842 TargetLowering::DAGCombinerInfo &DCI,
7843 bool AllOnes = false) {
7844 SelectionDAG &DAG = DCI.DAG;
7845 EVT VT = N->getValueType(0);
7846 SDValue NonConstantVal;
7849 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7850 NonConstantVal, DAG))
7853 // Slct is now know to be the desired identity constant when CC is true.
7854 SDValue TrueVal = OtherOp;
7855 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7856 OtherOp, NonConstantVal);
7857 // Unless SwapSelectOps says CC should be false.
7859 std::swap(TrueVal, FalseVal);
7861 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7862 CCOp, TrueVal, FalseVal);
7865 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7867 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7868 TargetLowering::DAGCombinerInfo &DCI) {
7869 SDValue N0 = N->getOperand(0);
7870 SDValue N1 = N->getOperand(1);
7871 if (N0.getNode()->hasOneUse()) {
7872 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7873 if (Result.getNode())
7876 if (N1.getNode()->hasOneUse()) {
7877 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7878 if (Result.getNode())
7884 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7885 // (only after legalization).
7886 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7887 TargetLowering::DAGCombinerInfo &DCI,
7888 const ARMSubtarget *Subtarget) {
7890 // Only perform optimization if after legalize, and if NEON is available. We
7891 // also expected both operands to be BUILD_VECTORs.
7892 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7893 || N0.getOpcode() != ISD::BUILD_VECTOR
7894 || N1.getOpcode() != ISD::BUILD_VECTOR)
7897 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7898 EVT VT = N->getValueType(0);
7899 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7902 // Check that the vector operands are of the right form.
7903 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7904 // operands, where N is the size of the formed vector.
7905 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7906 // index such that we have a pair wise add pattern.
7908 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7909 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7911 SDValue Vec = N0->getOperand(0)->getOperand(0);
7912 SDNode *V = Vec.getNode();
7913 unsigned nextIndex = 0;
7915 // For each operands to the ADD which are BUILD_VECTORs,
7916 // check to see if each of their operands are an EXTRACT_VECTOR with
7917 // the same vector and appropriate index.
7918 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7919 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7920 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7922 SDValue ExtVec0 = N0->getOperand(i);
7923 SDValue ExtVec1 = N1->getOperand(i);
7925 // First operand is the vector, verify its the same.
7926 if (V != ExtVec0->getOperand(0).getNode() ||
7927 V != ExtVec1->getOperand(0).getNode())
7930 // Second is the constant, verify its correct.
7931 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7932 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7934 // For the constant, we want to see all the even or all the odd.
7935 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7936 || C1->getZExtValue() != nextIndex+1)
7945 // Create VPADDL node.
7946 SelectionDAG &DAG = DCI.DAG;
7947 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7951 // Build operand list.
7952 SmallVector<SDValue, 8> Ops;
7953 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
7954 TLI.getPointerTy()));
7956 // Input is the vector.
7959 // Get widened type and narrowed type.
7961 unsigned numElem = VT.getVectorNumElements();
7963 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7964 switch (inputLaneType.getSimpleVT().SimpleTy) {
7965 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7966 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7967 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7969 llvm_unreachable("Invalid vector element type for padd optimization.");
7972 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
7973 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7974 return DAG.getNode(ExtOp, dl, VT, tmp);
7977 static SDValue findMUL_LOHI(SDValue V) {
7978 if (V->getOpcode() == ISD::UMUL_LOHI ||
7979 V->getOpcode() == ISD::SMUL_LOHI)
7984 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7985 TargetLowering::DAGCombinerInfo &DCI,
7986 const ARMSubtarget *Subtarget) {
7988 if (Subtarget->isThumb1Only()) return SDValue();
7990 // Only perform the checks after legalize when the pattern is available.
7991 if (DCI.isBeforeLegalize()) return SDValue();
7993 // Look for multiply add opportunities.
7994 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7995 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7996 // a glue link from the first add to the second add.
7997 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7998 // a S/UMLAL instruction.
8001 // / \ [no multiline comment]
8007 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8008 SDValue AddcOp0 = AddcNode->getOperand(0);
8009 SDValue AddcOp1 = AddcNode->getOperand(1);
8011 // Check if the two operands are from the same mul_lohi node.
8012 if (AddcOp0.getNode() == AddcOp1.getNode())
8015 assert(AddcNode->getNumValues() == 2 &&
8016 AddcNode->getValueType(0) == MVT::i32 &&
8017 "Expect ADDC with two result values. First: i32");
8019 // Check that we have a glued ADDC node.
8020 if (AddcNode->getValueType(1) != MVT::Glue)
8023 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8024 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8025 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8026 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8027 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8030 // Look for the glued ADDE.
8031 SDNode* AddeNode = AddcNode->getGluedUser();
8035 // Make sure it is really an ADDE.
8036 if (AddeNode->getOpcode() != ISD::ADDE)
8039 assert(AddeNode->getNumOperands() == 3 &&
8040 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8041 "ADDE node has the wrong inputs");
8043 // Check for the triangle shape.
8044 SDValue AddeOp0 = AddeNode->getOperand(0);
8045 SDValue AddeOp1 = AddeNode->getOperand(1);
8047 // Make sure that the ADDE operands are not coming from the same node.
8048 if (AddeOp0.getNode() == AddeOp1.getNode())
8051 // Find the MUL_LOHI node walking up ADDE's operands.
8052 bool IsLeftOperandMUL = false;
8053 SDValue MULOp = findMUL_LOHI(AddeOp0);
8054 if (MULOp == SDValue())
8055 MULOp = findMUL_LOHI(AddeOp1);
8057 IsLeftOperandMUL = true;
8058 if (MULOp == SDValue())
8061 // Figure out the right opcode.
8062 unsigned Opc = MULOp->getOpcode();
8063 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8065 // Figure out the high and low input values to the MLAL node.
8066 SDValue* HiAdd = nullptr;
8067 SDValue* LoMul = nullptr;
8068 SDValue* LowAdd = nullptr;
8070 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8071 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8074 if (IsLeftOperandMUL)
8080 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8081 // whose low result is fed to the ADDC we are checking.
8083 if (AddcOp0 == MULOp.getValue(0)) {
8087 if (AddcOp1 == MULOp.getValue(0)) {
8095 // Create the merged node.
8096 SelectionDAG &DAG = DCI.DAG;
8098 // Build operand list.
8099 SmallVector<SDValue, 8> Ops;
8100 Ops.push_back(LoMul->getOperand(0));
8101 Ops.push_back(LoMul->getOperand(1));
8102 Ops.push_back(*LowAdd);
8103 Ops.push_back(*HiAdd);
8105 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8106 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8108 // Replace the ADDs' nodes uses by the MLA node's values.
8109 SDValue HiMLALResult(MLALNode.getNode(), 1);
8110 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8112 SDValue LoMLALResult(MLALNode.getNode(), 0);
8113 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8115 // Return original node to notify the driver to stop replacing.
8116 SDValue resNode(AddcNode, 0);
8120 /// PerformADDCCombine - Target-specific dag combine transform from
8121 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8122 static SDValue PerformADDCCombine(SDNode *N,
8123 TargetLowering::DAGCombinerInfo &DCI,
8124 const ARMSubtarget *Subtarget) {
8126 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8130 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8131 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8132 /// called with the default operands, and if that fails, with commuted
8134 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8135 TargetLowering::DAGCombinerInfo &DCI,
8136 const ARMSubtarget *Subtarget){
8138 // Attempt to create vpaddl for this add.
8139 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8140 if (Result.getNode())
8143 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8144 if (N0.getNode()->hasOneUse()) {
8145 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8146 if (Result.getNode()) return Result;
8151 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8153 static SDValue PerformADDCombine(SDNode *N,
8154 TargetLowering::DAGCombinerInfo &DCI,
8155 const ARMSubtarget *Subtarget) {
8156 SDValue N0 = N->getOperand(0);
8157 SDValue N1 = N->getOperand(1);
8159 // First try with the default operand order.
8160 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8161 if (Result.getNode())
8164 // If that didn't work, try again with the operands commuted.
8165 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8168 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8170 static SDValue PerformSUBCombine(SDNode *N,
8171 TargetLowering::DAGCombinerInfo &DCI) {
8172 SDValue N0 = N->getOperand(0);
8173 SDValue N1 = N->getOperand(1);
8175 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8176 if (N1.getNode()->hasOneUse()) {
8177 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8178 if (Result.getNode()) return Result;
8184 /// PerformVMULCombine
8185 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8186 /// special multiplier accumulator forwarding.
8192 // However, for (A + B) * (A + B),
8199 static SDValue PerformVMULCombine(SDNode *N,
8200 TargetLowering::DAGCombinerInfo &DCI,
8201 const ARMSubtarget *Subtarget) {
8202 if (!Subtarget->hasVMLxForwarding())
8205 SelectionDAG &DAG = DCI.DAG;
8206 SDValue N0 = N->getOperand(0);
8207 SDValue N1 = N->getOperand(1);
8208 unsigned Opcode = N0.getOpcode();
8209 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8210 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8211 Opcode = N1.getOpcode();
8212 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8213 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8221 EVT VT = N->getValueType(0);
8223 SDValue N00 = N0->getOperand(0);
8224 SDValue N01 = N0->getOperand(1);
8225 return DAG.getNode(Opcode, DL, VT,
8226 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8227 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8230 static SDValue PerformMULCombine(SDNode *N,
8231 TargetLowering::DAGCombinerInfo &DCI,
8232 const ARMSubtarget *Subtarget) {
8233 SelectionDAG &DAG = DCI.DAG;
8235 if (Subtarget->isThumb1Only())
8238 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8241 EVT VT = N->getValueType(0);
8242 if (VT.is64BitVector() || VT.is128BitVector())
8243 return PerformVMULCombine(N, DCI, Subtarget);
8247 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8251 int64_t MulAmt = C->getSExtValue();
8252 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8254 ShiftAmt = ShiftAmt & (32 - 1);
8255 SDValue V = N->getOperand(0);
8259 MulAmt >>= ShiftAmt;
8262 if (isPowerOf2_32(MulAmt - 1)) {
8263 // (mul x, 2^N + 1) => (add (shl x, N), x)
8264 Res = DAG.getNode(ISD::ADD, DL, VT,
8266 DAG.getNode(ISD::SHL, DL, VT,
8268 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8270 } else if (isPowerOf2_32(MulAmt + 1)) {
8271 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8272 Res = DAG.getNode(ISD::SUB, DL, VT,
8273 DAG.getNode(ISD::SHL, DL, VT,
8275 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8281 uint64_t MulAmtAbs = -MulAmt;
8282 if (isPowerOf2_32(MulAmtAbs + 1)) {
8283 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8284 Res = DAG.getNode(ISD::SUB, DL, VT,
8286 DAG.getNode(ISD::SHL, DL, VT,
8288 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8290 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8291 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8292 Res = DAG.getNode(ISD::ADD, DL, VT,
8294 DAG.getNode(ISD::SHL, DL, VT,
8296 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8298 Res = DAG.getNode(ISD::SUB, DL, VT,
8299 DAG.getConstant(0, DL, MVT::i32), Res);
8306 Res = DAG.getNode(ISD::SHL, DL, VT,
8307 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8309 // Do not add new nodes to DAG combiner worklist.
8310 DCI.CombineTo(N, Res, false);
8314 static SDValue PerformANDCombine(SDNode *N,
8315 TargetLowering::DAGCombinerInfo &DCI,
8316 const ARMSubtarget *Subtarget) {
8318 // Attempt to use immediate-form VBIC
8319 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8321 EVT VT = N->getValueType(0);
8322 SelectionDAG &DAG = DCI.DAG;
8324 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8327 APInt SplatBits, SplatUndef;
8328 unsigned SplatBitSize;
8331 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8332 if (SplatBitSize <= 64) {
8334 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8335 SplatUndef.getZExtValue(), SplatBitSize,
8336 DAG, dl, VbicVT, VT.is128BitVector(),
8338 if (Val.getNode()) {
8340 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8341 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8342 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8347 if (!Subtarget->isThumb1Only()) {
8348 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8349 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8350 if (Result.getNode())
8357 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8358 static SDValue PerformORCombine(SDNode *N,
8359 TargetLowering::DAGCombinerInfo &DCI,
8360 const ARMSubtarget *Subtarget) {
8361 // Attempt to use immediate-form VORR
8362 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8364 EVT VT = N->getValueType(0);
8365 SelectionDAG &DAG = DCI.DAG;
8367 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8370 APInt SplatBits, SplatUndef;
8371 unsigned SplatBitSize;
8373 if (BVN && Subtarget->hasNEON() &&
8374 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8375 if (SplatBitSize <= 64) {
8377 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8378 SplatUndef.getZExtValue(), SplatBitSize,
8379 DAG, dl, VorrVT, VT.is128BitVector(),
8381 if (Val.getNode()) {
8383 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8384 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8385 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8390 if (!Subtarget->isThumb1Only()) {
8391 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8392 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8393 if (Result.getNode())
8397 // The code below optimizes (or (and X, Y), Z).
8398 // The AND operand needs to have a single user to make these optimizations
8400 SDValue N0 = N->getOperand(0);
8401 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8403 SDValue N1 = N->getOperand(1);
8405 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8406 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8407 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8409 unsigned SplatBitSize;
8412 APInt SplatBits0, SplatBits1;
8413 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8414 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8415 // Ensure that the second operand of both ands are constants
8416 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8417 HasAnyUndefs) && !HasAnyUndefs) {
8418 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8419 HasAnyUndefs) && !HasAnyUndefs) {
8420 // Ensure that the bit width of the constants are the same and that
8421 // the splat arguments are logical inverses as per the pattern we
8422 // are trying to simplify.
8423 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8424 SplatBits0 == ~SplatBits1) {
8425 // Canonicalize the vector type to make instruction selection
8427 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8428 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8432 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8438 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8441 // BFI is only available on V6T2+
8442 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8446 // 1) or (and A, mask), val => ARMbfi A, val, mask
8447 // iff (val & mask) == val
8449 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8450 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8451 // && mask == ~mask2
8452 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8453 // && ~mask == mask2
8454 // (i.e., copy a bitfield value into another bitfield of the same width)
8459 SDValue N00 = N0.getOperand(0);
8461 // The value and the mask need to be constants so we can verify this is
8462 // actually a bitfield set. If the mask is 0xffff, we can do better
8463 // via a movt instruction, so don't use BFI in that case.
8464 SDValue MaskOp = N0.getOperand(1);
8465 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8468 unsigned Mask = MaskC->getZExtValue();
8472 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8473 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8475 unsigned Val = N1C->getZExtValue();
8476 if ((Val & ~Mask) != Val)
8479 if (ARM::isBitFieldInvertedMask(Mask)) {
8480 Val >>= countTrailingZeros(~Mask);
8482 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8483 DAG.getConstant(Val, DL, MVT::i32),
8484 DAG.getConstant(Mask, DL, MVT::i32));
8486 // Do not add new nodes to DAG combiner worklist.
8487 DCI.CombineTo(N, Res, false);
8490 } else if (N1.getOpcode() == ISD::AND) {
8491 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8492 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8495 unsigned Mask2 = N11C->getZExtValue();
8497 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8499 if (ARM::isBitFieldInvertedMask(Mask) &&
8501 // The pack halfword instruction works better for masks that fit it,
8502 // so use that when it's available.
8503 if (Subtarget->hasT2ExtractPack() &&
8504 (Mask == 0xffff || Mask == 0xffff0000))
8507 unsigned amt = countTrailingZeros(Mask2);
8508 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8509 DAG.getConstant(amt, DL, MVT::i32));
8510 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8511 DAG.getConstant(Mask, DL, MVT::i32));
8512 // Do not add new nodes to DAG combiner worklist.
8513 DCI.CombineTo(N, Res, false);
8515 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8517 // The pack halfword instruction works better for masks that fit it,
8518 // so use that when it's available.
8519 if (Subtarget->hasT2ExtractPack() &&
8520 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8523 unsigned lsb = countTrailingZeros(Mask);
8524 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8525 DAG.getConstant(lsb, DL, MVT::i32));
8526 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8527 DAG.getConstant(Mask2, DL, MVT::i32));
8528 // Do not add new nodes to DAG combiner worklist.
8529 DCI.CombineTo(N, Res, false);
8534 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8535 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8536 ARM::isBitFieldInvertedMask(~Mask)) {
8537 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8538 // where lsb(mask) == #shamt and masked bits of B are known zero.
8539 SDValue ShAmt = N00.getOperand(1);
8540 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8541 unsigned LSB = countTrailingZeros(Mask);
8545 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8546 DAG.getConstant(~Mask, DL, MVT::i32));
8548 // Do not add new nodes to DAG combiner worklist.
8549 DCI.CombineTo(N, Res, false);
8555 static SDValue PerformXORCombine(SDNode *N,
8556 TargetLowering::DAGCombinerInfo &DCI,
8557 const ARMSubtarget *Subtarget) {
8558 EVT VT = N->getValueType(0);
8559 SelectionDAG &DAG = DCI.DAG;
8561 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8564 if (!Subtarget->isThumb1Only()) {
8565 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8566 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8567 if (Result.getNode())
8574 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8575 /// the bits being cleared by the AND are not demanded by the BFI.
8576 static SDValue PerformBFICombine(SDNode *N,
8577 TargetLowering::DAGCombinerInfo &DCI) {
8578 SDValue N1 = N->getOperand(1);
8579 if (N1.getOpcode() == ISD::AND) {
8580 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8583 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8584 unsigned LSB = countTrailingZeros(~InvMask);
8585 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8587 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8588 "undefined behavior");
8589 unsigned Mask = (1u << Width) - 1;
8590 unsigned Mask2 = N11C->getZExtValue();
8591 if ((Mask & (~Mask2)) == 0)
8592 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8593 N->getOperand(0), N1.getOperand(0),
8599 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8600 /// ARMISD::VMOVRRD.
8601 static SDValue PerformVMOVRRDCombine(SDNode *N,
8602 TargetLowering::DAGCombinerInfo &DCI,
8603 const ARMSubtarget *Subtarget) {
8604 // vmovrrd(vmovdrr x, y) -> x,y
8605 SDValue InDouble = N->getOperand(0);
8606 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8607 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8609 // vmovrrd(load f64) -> (load i32), (load i32)
8610 SDNode *InNode = InDouble.getNode();
8611 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8612 InNode->getValueType(0) == MVT::f64 &&
8613 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8614 !cast<LoadSDNode>(InNode)->isVolatile()) {
8615 // TODO: Should this be done for non-FrameIndex operands?
8616 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8618 SelectionDAG &DAG = DCI.DAG;
8620 SDValue BasePtr = LD->getBasePtr();
8621 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8622 LD->getPointerInfo(), LD->isVolatile(),
8623 LD->isNonTemporal(), LD->isInvariant(),
8624 LD->getAlignment());
8626 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8627 DAG.getConstant(4, DL, MVT::i32));
8628 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8629 LD->getPointerInfo(), LD->isVolatile(),
8630 LD->isNonTemporal(), LD->isInvariant(),
8631 std::min(4U, LD->getAlignment() / 2));
8633 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8634 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8635 std::swap (NewLD1, NewLD2);
8636 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8643 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8644 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8645 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8646 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8647 SDValue Op0 = N->getOperand(0);
8648 SDValue Op1 = N->getOperand(1);
8649 if (Op0.getOpcode() == ISD::BITCAST)
8650 Op0 = Op0.getOperand(0);
8651 if (Op1.getOpcode() == ISD::BITCAST)
8652 Op1 = Op1.getOperand(0);
8653 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8654 Op0.getNode() == Op1.getNode() &&
8655 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8656 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8657 N->getValueType(0), Op0.getOperand(0));
8661 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8662 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8663 /// i64 vector to have f64 elements, since the value can then be loaded
8664 /// directly into a VFP register.
8665 static bool hasNormalLoadOperand(SDNode *N) {
8666 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8667 for (unsigned i = 0; i < NumElts; ++i) {
8668 SDNode *Elt = N->getOperand(i).getNode();
8669 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8675 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8676 /// ISD::BUILD_VECTOR.
8677 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8678 TargetLowering::DAGCombinerInfo &DCI,
8679 const ARMSubtarget *Subtarget) {
8680 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8681 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8682 // into a pair of GPRs, which is fine when the value is used as a scalar,
8683 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8684 SelectionDAG &DAG = DCI.DAG;
8685 if (N->getNumOperands() == 2) {
8686 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8691 // Load i64 elements as f64 values so that type legalization does not split
8692 // them up into i32 values.
8693 EVT VT = N->getValueType(0);
8694 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8697 SmallVector<SDValue, 8> Ops;
8698 unsigned NumElts = VT.getVectorNumElements();
8699 for (unsigned i = 0; i < NumElts; ++i) {
8700 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8702 // Make the DAGCombiner fold the bitcast.
8703 DCI.AddToWorklist(V.getNode());
8705 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8706 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8707 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8710 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8712 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8713 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8714 // At that time, we may have inserted bitcasts from integer to float.
8715 // If these bitcasts have survived DAGCombine, change the lowering of this
8716 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8717 // force to use floating point types.
8719 // Make sure we can change the type of the vector.
8720 // This is possible iff:
8721 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8722 // 1.1. Vector is used only once.
8723 // 1.2. Use is a bit convert to an integer type.
8724 // 2. The size of its operands are 32-bits (64-bits are not legal).
8725 EVT VT = N->getValueType(0);
8726 EVT EltVT = VT.getVectorElementType();
8728 // Check 1.1. and 2.
8729 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8732 // By construction, the input type must be float.
8733 assert(EltVT == MVT::f32 && "Unexpected type!");
8736 SDNode *Use = *N->use_begin();
8737 if (Use->getOpcode() != ISD::BITCAST ||
8738 Use->getValueType(0).isFloatingPoint())
8741 // Check profitability.
8742 // Model is, if more than half of the relevant operands are bitcast from
8743 // i32, turn the build_vector into a sequence of insert_vector_elt.
8744 // Relevant operands are everything that is not statically
8745 // (i.e., at compile time) bitcasted.
8746 unsigned NumOfBitCastedElts = 0;
8747 unsigned NumElts = VT.getVectorNumElements();
8748 unsigned NumOfRelevantElts = NumElts;
8749 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8750 SDValue Elt = N->getOperand(Idx);
8751 if (Elt->getOpcode() == ISD::BITCAST) {
8752 // Assume only bit cast to i32 will go away.
8753 if (Elt->getOperand(0).getValueType() == MVT::i32)
8754 ++NumOfBitCastedElts;
8755 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8756 // Constants are statically casted, thus do not count them as
8757 // relevant operands.
8758 --NumOfRelevantElts;
8761 // Check if more than half of the elements require a non-free bitcast.
8762 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8765 SelectionDAG &DAG = DCI.DAG;
8766 // Create the new vector type.
8767 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8768 // Check if the type is legal.
8769 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8770 if (!TLI.isTypeLegal(VecVT))
8774 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8775 // => BITCAST INSERT_VECTOR_ELT
8776 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8778 SDValue Vec = DAG.getUNDEF(VecVT);
8780 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8781 SDValue V = N->getOperand(Idx);
8782 if (V.getOpcode() == ISD::UNDEF)
8784 if (V.getOpcode() == ISD::BITCAST &&
8785 V->getOperand(0).getValueType() == MVT::i32)
8786 // Fold obvious case.
8787 V = V.getOperand(0);
8789 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8790 // Make the DAGCombiner fold the bitcasts.
8791 DCI.AddToWorklist(V.getNode());
8793 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8794 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8796 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8797 // Make the DAGCombiner fold the bitcasts.
8798 DCI.AddToWorklist(Vec.getNode());
8802 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8803 /// ISD::INSERT_VECTOR_ELT.
8804 static SDValue PerformInsertEltCombine(SDNode *N,
8805 TargetLowering::DAGCombinerInfo &DCI) {
8806 // Bitcast an i64 load inserted into a vector to f64.
8807 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8808 EVT VT = N->getValueType(0);
8809 SDNode *Elt = N->getOperand(1).getNode();
8810 if (VT.getVectorElementType() != MVT::i64 ||
8811 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8814 SelectionDAG &DAG = DCI.DAG;
8816 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8817 VT.getVectorNumElements());
8818 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8819 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8820 // Make the DAGCombiner fold the bitcasts.
8821 DCI.AddToWorklist(Vec.getNode());
8822 DCI.AddToWorklist(V.getNode());
8823 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8824 Vec, V, N->getOperand(2));
8825 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8828 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8829 /// ISD::VECTOR_SHUFFLE.
8830 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8831 // The LLVM shufflevector instruction does not require the shuffle mask
8832 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8833 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8834 // operands do not match the mask length, they are extended by concatenating
8835 // them with undef vectors. That is probably the right thing for other
8836 // targets, but for NEON it is better to concatenate two double-register
8837 // size vector operands into a single quad-register size vector. Do that
8838 // transformation here:
8839 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8840 // shuffle(concat(v1, v2), undef)
8841 SDValue Op0 = N->getOperand(0);
8842 SDValue Op1 = N->getOperand(1);
8843 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8844 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8845 Op0.getNumOperands() != 2 ||
8846 Op1.getNumOperands() != 2)
8848 SDValue Concat0Op1 = Op0.getOperand(1);
8849 SDValue Concat1Op1 = Op1.getOperand(1);
8850 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8851 Concat1Op1.getOpcode() != ISD::UNDEF)
8853 // Skip the transformation if any of the types are illegal.
8854 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8855 EVT VT = N->getValueType(0);
8856 if (!TLI.isTypeLegal(VT) ||
8857 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8858 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8861 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8862 Op0.getOperand(0), Op1.getOperand(0));
8863 // Translate the shuffle mask.
8864 SmallVector<int, 16> NewMask;
8865 unsigned NumElts = VT.getVectorNumElements();
8866 unsigned HalfElts = NumElts/2;
8867 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8868 for (unsigned n = 0; n < NumElts; ++n) {
8869 int MaskElt = SVN->getMaskElt(n);
8871 if (MaskElt < (int)HalfElts)
8873 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8874 NewElt = HalfElts + MaskElt - NumElts;
8875 NewMask.push_back(NewElt);
8877 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8878 DAG.getUNDEF(VT), NewMask.data());
8881 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8882 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8883 /// base address updates.
8884 /// For generic load/stores, the memory type is assumed to be a vector.
8885 /// The caller is assumed to have checked legality.
8886 static SDValue CombineBaseUpdate(SDNode *N,
8887 TargetLowering::DAGCombinerInfo &DCI) {
8888 SelectionDAG &DAG = DCI.DAG;
8889 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8890 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8891 const bool isStore = N->getOpcode() == ISD::STORE;
8892 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8893 SDValue Addr = N->getOperand(AddrOpIdx);
8894 MemSDNode *MemN = cast<MemSDNode>(N);
8897 // Search for a use of the address operand that is an increment.
8898 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8899 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8901 if (User->getOpcode() != ISD::ADD ||
8902 UI.getUse().getResNo() != Addr.getResNo())
8905 // Check that the add is independent of the load/store. Otherwise, folding
8906 // it would create a cycle.
8907 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8910 // Find the new opcode for the updating load/store.
8911 bool isLoadOp = true;
8912 bool isLaneOp = false;
8913 unsigned NewOpc = 0;
8914 unsigned NumVecs = 0;
8916 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8918 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8919 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8921 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8923 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8925 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8927 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8928 NumVecs = 2; isLaneOp = true; break;
8929 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8930 NumVecs = 3; isLaneOp = true; break;
8931 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8932 NumVecs = 4; isLaneOp = true; break;
8933 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8934 NumVecs = 1; isLoadOp = false; break;
8935 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8936 NumVecs = 2; isLoadOp = false; break;
8937 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8938 NumVecs = 3; isLoadOp = false; break;
8939 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8940 NumVecs = 4; isLoadOp = false; break;
8941 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8942 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8943 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8944 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8945 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8946 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8950 switch (N->getOpcode()) {
8951 default: llvm_unreachable("unexpected opcode for Neon base update");
8952 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8953 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8954 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8955 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
8956 NumVecs = 1; isLaneOp = false; break;
8957 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
8958 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8962 // Find the size of memory referenced by the load/store.
8965 VecTy = N->getValueType(0);
8966 } else if (isIntrinsic) {
8967 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8969 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8970 VecTy = N->getOperand(1).getValueType();
8973 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8975 NumBytes /= VecTy.getVectorNumElements();
8977 // If the increment is a constant, it must match the memory ref size.
8978 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8979 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8980 uint64_t IncVal = CInc->getZExtValue();
8981 if (IncVal != NumBytes)
8983 } else if (NumBytes >= 3 * 16) {
8984 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8985 // separate instructions that make it harder to use a non-constant update.
8989 // OK, we found an ADD we can fold into the base update.
8990 // Now, create a _UPD node, taking care of not breaking alignment.
8992 EVT AlignedVecTy = VecTy;
8993 unsigned Alignment = MemN->getAlignment();
8995 // If this is a less-than-standard-aligned load/store, change the type to
8996 // match the standard alignment.
8997 // The alignment is overlooked when selecting _UPD variants; and it's
8998 // easier to introduce bitcasts here than fix that.
8999 // There are 3 ways to get to this base-update combine:
9000 // - intrinsics: they are assumed to be properly aligned (to the standard
9001 // alignment of the memory type), so we don't need to do anything.
9002 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9003 // intrinsics, so, likewise, there's nothing to do.
9004 // - generic load/store instructions: the alignment is specified as an
9005 // explicit operand, rather than implicitly as the standard alignment
9006 // of the memory type (like the intrisics). We need to change the
9007 // memory type to match the explicit alignment. That way, we don't
9008 // generate non-standard-aligned ARMISD::VLDx nodes.
9009 if (isa<LSBaseSDNode>(N)) {
9012 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9013 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9014 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9015 assert(!isLaneOp && "Unexpected generic load/store lane.");
9016 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9017 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9019 // Don't set an explicit alignment on regular load/stores that we want
9020 // to transform to VLD/VST 1_UPD nodes.
9021 // This matches the behavior of regular load/stores, which only get an
9022 // explicit alignment if the MMO alignment is larger than the standard
9023 // alignment of the memory type.
9024 // Intrinsics, however, always get an explicit alignment, set to the
9025 // alignment of the MMO.
9029 // Create the new updating load/store node.
9030 // First, create an SDVTList for the new updating node's results.
9032 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9034 for (n = 0; n < NumResultVecs; ++n)
9035 Tys[n] = AlignedVecTy;
9036 Tys[n++] = MVT::i32;
9037 Tys[n] = MVT::Other;
9038 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9040 // Then, gather the new node's operands.
9041 SmallVector<SDValue, 8> Ops;
9042 Ops.push_back(N->getOperand(0)); // incoming chain
9043 Ops.push_back(N->getOperand(AddrOpIdx));
9046 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9047 // Try to match the intrinsic's signature
9048 Ops.push_back(StN->getValue());
9050 // Loads (and of course intrinsics) match the intrinsics' signature,
9051 // so just add all but the alignment operand.
9052 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9053 Ops.push_back(N->getOperand(i));
9056 // For all node types, the alignment operand is always the last one.
9057 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9059 // If this is a non-standard-aligned STORE, the penultimate operand is the
9060 // stored value. Bitcast it to the aligned type.
9061 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9062 SDValue &StVal = Ops[Ops.size()-2];
9063 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9066 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9068 MemN->getMemOperand());
9071 SmallVector<SDValue, 5> NewResults;
9072 for (unsigned i = 0; i < NumResultVecs; ++i)
9073 NewResults.push_back(SDValue(UpdN.getNode(), i));
9075 // If this is an non-standard-aligned LOAD, the first result is the loaded
9076 // value. Bitcast it to the expected result type.
9077 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9078 SDValue &LdVal = NewResults[0];
9079 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9082 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9083 DCI.CombineTo(N, NewResults);
9084 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9091 static SDValue PerformVLDCombine(SDNode *N,
9092 TargetLowering::DAGCombinerInfo &DCI) {
9093 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9096 return CombineBaseUpdate(N, DCI);
9099 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9100 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9101 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9103 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9104 SelectionDAG &DAG = DCI.DAG;
9105 EVT VT = N->getValueType(0);
9106 // vldN-dup instructions only support 64-bit vectors for N > 1.
9107 if (!VT.is64BitVector())
9110 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9111 SDNode *VLD = N->getOperand(0).getNode();
9112 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9114 unsigned NumVecs = 0;
9115 unsigned NewOpc = 0;
9116 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9117 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9119 NewOpc = ARMISD::VLD2DUP;
9120 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9122 NewOpc = ARMISD::VLD3DUP;
9123 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9125 NewOpc = ARMISD::VLD4DUP;
9130 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9131 // numbers match the load.
9132 unsigned VLDLaneNo =
9133 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9134 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9136 // Ignore uses of the chain result.
9137 if (UI.getUse().getResNo() == NumVecs)
9140 if (User->getOpcode() != ARMISD::VDUPLANE ||
9141 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9145 // Create the vldN-dup node.
9148 for (n = 0; n < NumVecs; ++n)
9150 Tys[n] = MVT::Other;
9151 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9152 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9153 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9154 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9155 Ops, VLDMemInt->getMemoryVT(),
9156 VLDMemInt->getMemOperand());
9159 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9161 unsigned ResNo = UI.getUse().getResNo();
9162 // Ignore uses of the chain result.
9163 if (ResNo == NumVecs)
9166 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9169 // Now the vldN-lane intrinsic is dead except for its chain result.
9170 // Update uses of the chain.
9171 std::vector<SDValue> VLDDupResults;
9172 for (unsigned n = 0; n < NumVecs; ++n)
9173 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9174 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9175 DCI.CombineTo(VLD, VLDDupResults);
9180 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9181 /// ARMISD::VDUPLANE.
9182 static SDValue PerformVDUPLANECombine(SDNode *N,
9183 TargetLowering::DAGCombinerInfo &DCI) {
9184 SDValue Op = N->getOperand(0);
9186 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9187 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9188 if (CombineVLDDUP(N, DCI))
9189 return SDValue(N, 0);
9191 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9192 // redundant. Ignore bit_converts for now; element sizes are checked below.
9193 while (Op.getOpcode() == ISD::BITCAST)
9194 Op = Op.getOperand(0);
9195 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9198 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9199 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9200 // The canonical VMOV for a zero vector uses a 32-bit element size.
9201 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9203 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9205 EVT VT = N->getValueType(0);
9206 if (EltSize > VT.getVectorElementType().getSizeInBits())
9209 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9212 static SDValue PerformLOADCombine(SDNode *N,
9213 TargetLowering::DAGCombinerInfo &DCI) {
9214 EVT VT = N->getValueType(0);
9216 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9217 if (ISD::isNormalLoad(N) && VT.isVector() &&
9218 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9219 return CombineBaseUpdate(N, DCI);
9224 /// PerformSTORECombine - Target-specific dag combine xforms for
9226 static SDValue PerformSTORECombine(SDNode *N,
9227 TargetLowering::DAGCombinerInfo &DCI) {
9228 StoreSDNode *St = cast<StoreSDNode>(N);
9229 if (St->isVolatile())
9232 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9233 // pack all of the elements in one place. Next, store to memory in fewer
9235 SDValue StVal = St->getValue();
9236 EVT VT = StVal.getValueType();
9237 if (St->isTruncatingStore() && VT.isVector()) {
9238 SelectionDAG &DAG = DCI.DAG;
9239 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9240 EVT StVT = St->getMemoryVT();
9241 unsigned NumElems = VT.getVectorNumElements();
9242 assert(StVT != VT && "Cannot truncate to the same type");
9243 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9244 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9246 // From, To sizes and ElemCount must be pow of two
9247 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9249 // We are going to use the original vector elt for storing.
9250 // Accumulated smaller vector elements must be a multiple of the store size.
9251 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9253 unsigned SizeRatio = FromEltSz / ToEltSz;
9254 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9256 // Create a type on which we perform the shuffle.
9257 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9258 NumElems*SizeRatio);
9259 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9262 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9263 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9264 for (unsigned i = 0; i < NumElems; ++i)
9265 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9267 // Can't shuffle using an illegal type.
9268 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9270 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9271 DAG.getUNDEF(WideVec.getValueType()),
9273 // At this point all of the data is stored at the bottom of the
9274 // register. We now need to save it to mem.
9276 // Find the largest store unit
9277 MVT StoreType = MVT::i8;
9278 for (MVT Tp : MVT::integer_valuetypes()) {
9279 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9282 // Didn't find a legal store type.
9283 if (!TLI.isTypeLegal(StoreType))
9286 // Bitcast the original vector into a vector of store-size units
9287 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9288 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9289 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9290 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9291 SmallVector<SDValue, 8> Chains;
9292 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, DL,
9293 TLI.getPointerTy());
9294 SDValue BasePtr = St->getBasePtr();
9296 // Perform one or more big stores into memory.
9297 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9298 for (unsigned I = 0; I < E; I++) {
9299 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9300 StoreType, ShuffWide,
9301 DAG.getIntPtrConstant(I, DL));
9302 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9303 St->getPointerInfo(), St->isVolatile(),
9304 St->isNonTemporal(), St->getAlignment());
9305 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9307 Chains.push_back(Ch);
9309 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9312 if (!ISD::isNormalStore(St))
9315 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9316 // ARM stores of arguments in the same cache line.
9317 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9318 StVal.getNode()->hasOneUse()) {
9319 SelectionDAG &DAG = DCI.DAG;
9320 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9322 SDValue BasePtr = St->getBasePtr();
9323 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9324 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9325 BasePtr, St->getPointerInfo(), St->isVolatile(),
9326 St->isNonTemporal(), St->getAlignment());
9328 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9329 DAG.getConstant(4, DL, MVT::i32));
9330 return DAG.getStore(NewST1.getValue(0), DL,
9331 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9332 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9333 St->isNonTemporal(),
9334 std::min(4U, St->getAlignment() / 2));
9337 if (StVal.getValueType() == MVT::i64 &&
9338 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9340 // Bitcast an i64 store extracted from a vector to f64.
9341 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9342 SelectionDAG &DAG = DCI.DAG;
9344 SDValue IntVec = StVal.getOperand(0);
9345 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9346 IntVec.getValueType().getVectorNumElements());
9347 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9348 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9349 Vec, StVal.getOperand(1));
9351 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9352 // Make the DAGCombiner fold the bitcasts.
9353 DCI.AddToWorklist(Vec.getNode());
9354 DCI.AddToWorklist(ExtElt.getNode());
9355 DCI.AddToWorklist(V.getNode());
9356 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9357 St->getPointerInfo(), St->isVolatile(),
9358 St->isNonTemporal(), St->getAlignment(),
9362 // If this is a legal vector store, try to combine it into a VST1_UPD.
9363 if (ISD::isNormalStore(N) && VT.isVector() &&
9364 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9365 return CombineBaseUpdate(N, DCI);
9370 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9371 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9372 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9376 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9378 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9383 APFloat APF = C->getValueAPF();
9384 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9385 != APFloat::opOK || !isExact)
9388 c0 = (I == 0) ? cN : c0;
9389 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9396 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9397 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9398 /// when the VMUL has a constant operand that is a power of 2.
9400 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9401 /// vmul.f32 d16, d17, d16
9402 /// vcvt.s32.f32 d16, d16
9404 /// vcvt.s32.f32 d16, d16, #3
9405 static SDValue PerformVCVTCombine(SDNode *N,
9406 TargetLowering::DAGCombinerInfo &DCI,
9407 const ARMSubtarget *Subtarget) {
9408 SelectionDAG &DAG = DCI.DAG;
9409 SDValue Op = N->getOperand(0);
9411 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9412 Op.getOpcode() != ISD::FMUL)
9416 SDValue N0 = Op->getOperand(0);
9417 SDValue ConstVec = Op->getOperand(1);
9418 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9420 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9421 !isConstVecPow2(ConstVec, isSigned, C))
9424 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9425 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9426 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9427 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9429 // These instructions only exist converting from f32 to i32. We can handle
9430 // smaller integers by generating an extra truncate, but larger ones would
9431 // be lossy. We also can't handle more then 4 lanes, since these intructions
9432 // only support v2i32/v4i32 types.
9437 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9438 Intrinsic::arm_neon_vcvtfp2fxu;
9439 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9440 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9441 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9443 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9445 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9446 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9451 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9452 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9453 /// when the VDIV has a constant operand that is a power of 2.
9455 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9456 /// vcvt.f32.s32 d16, d16
9457 /// vdiv.f32 d16, d17, d16
9459 /// vcvt.f32.s32 d16, d16, #3
9460 static SDValue PerformVDIVCombine(SDNode *N,
9461 TargetLowering::DAGCombinerInfo &DCI,
9462 const ARMSubtarget *Subtarget) {
9463 SelectionDAG &DAG = DCI.DAG;
9464 SDValue Op = N->getOperand(0);
9465 unsigned OpOpcode = Op.getNode()->getOpcode();
9467 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9468 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9472 SDValue ConstVec = N->getOperand(1);
9473 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9475 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9476 !isConstVecPow2(ConstVec, isSigned, C))
9479 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9480 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9481 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9482 // These instructions only exist converting from i32 to f32. We can handle
9483 // smaller integers by generating an extra extend, but larger ones would
9489 SDValue ConvInput = Op.getOperand(0);
9490 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9491 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9492 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9493 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9496 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9497 Intrinsic::arm_neon_vcvtfxu2fp;
9498 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9500 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9501 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9504 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9505 /// operand of a vector shift operation, where all the elements of the
9506 /// build_vector must have the same constant integer value.
9507 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9508 // Ignore bit_converts.
9509 while (Op.getOpcode() == ISD::BITCAST)
9510 Op = Op.getOperand(0);
9511 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9512 APInt SplatBits, SplatUndef;
9513 unsigned SplatBitSize;
9515 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9516 HasAnyUndefs, ElementBits) ||
9517 SplatBitSize > ElementBits)
9519 Cnt = SplatBits.getSExtValue();
9523 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9524 /// operand of a vector shift left operation. That value must be in the range:
9525 /// 0 <= Value < ElementBits for a left shift; or
9526 /// 0 <= Value <= ElementBits for a long left shift.
9527 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9528 assert(VT.isVector() && "vector shift count is not a vector type");
9529 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9530 if (! getVShiftImm(Op, ElementBits, Cnt))
9532 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9535 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9536 /// operand of a vector shift right operation. For a shift opcode, the value
9537 /// is positive, but for an intrinsic the value count must be negative. The
9538 /// absolute value must be in the range:
9539 /// 1 <= |Value| <= ElementBits for a right shift; or
9540 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9541 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9543 assert(VT.isVector() && "vector shift count is not a vector type");
9544 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9545 if (! getVShiftImm(Op, ElementBits, Cnt))
9549 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9552 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9553 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9554 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9557 // Don't do anything for most intrinsics.
9560 // Vector shifts: check for immediate versions and lower them.
9561 // Note: This is done during DAG combining instead of DAG legalizing because
9562 // the build_vectors for 64-bit vector element shift counts are generally
9563 // not legal, and it is hard to see their values after they get legalized to
9564 // loads from a constant pool.
9565 case Intrinsic::arm_neon_vshifts:
9566 case Intrinsic::arm_neon_vshiftu:
9567 case Intrinsic::arm_neon_vrshifts:
9568 case Intrinsic::arm_neon_vrshiftu:
9569 case Intrinsic::arm_neon_vrshiftn:
9570 case Intrinsic::arm_neon_vqshifts:
9571 case Intrinsic::arm_neon_vqshiftu:
9572 case Intrinsic::arm_neon_vqshiftsu:
9573 case Intrinsic::arm_neon_vqshiftns:
9574 case Intrinsic::arm_neon_vqshiftnu:
9575 case Intrinsic::arm_neon_vqshiftnsu:
9576 case Intrinsic::arm_neon_vqrshiftns:
9577 case Intrinsic::arm_neon_vqrshiftnu:
9578 case Intrinsic::arm_neon_vqrshiftnsu: {
9579 EVT VT = N->getOperand(1).getValueType();
9581 unsigned VShiftOpc = 0;
9584 case Intrinsic::arm_neon_vshifts:
9585 case Intrinsic::arm_neon_vshiftu:
9586 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9587 VShiftOpc = ARMISD::VSHL;
9590 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9591 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9592 ARMISD::VSHRs : ARMISD::VSHRu);
9597 case Intrinsic::arm_neon_vrshifts:
9598 case Intrinsic::arm_neon_vrshiftu:
9599 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9603 case Intrinsic::arm_neon_vqshifts:
9604 case Intrinsic::arm_neon_vqshiftu:
9605 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9609 case Intrinsic::arm_neon_vqshiftsu:
9610 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9612 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9614 case Intrinsic::arm_neon_vrshiftn:
9615 case Intrinsic::arm_neon_vqshiftns:
9616 case Intrinsic::arm_neon_vqshiftnu:
9617 case Intrinsic::arm_neon_vqshiftnsu:
9618 case Intrinsic::arm_neon_vqrshiftns:
9619 case Intrinsic::arm_neon_vqrshiftnu:
9620 case Intrinsic::arm_neon_vqrshiftnsu:
9621 // Narrowing shifts require an immediate right shift.
9622 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9624 llvm_unreachable("invalid shift count for narrowing vector shift "
9628 llvm_unreachable("unhandled vector shift");
9632 case Intrinsic::arm_neon_vshifts:
9633 case Intrinsic::arm_neon_vshiftu:
9634 // Opcode already set above.
9636 case Intrinsic::arm_neon_vrshifts:
9637 VShiftOpc = ARMISD::VRSHRs; break;
9638 case Intrinsic::arm_neon_vrshiftu:
9639 VShiftOpc = ARMISD::VRSHRu; break;
9640 case Intrinsic::arm_neon_vrshiftn:
9641 VShiftOpc = ARMISD::VRSHRN; break;
9642 case Intrinsic::arm_neon_vqshifts:
9643 VShiftOpc = ARMISD::VQSHLs; break;
9644 case Intrinsic::arm_neon_vqshiftu:
9645 VShiftOpc = ARMISD::VQSHLu; break;
9646 case Intrinsic::arm_neon_vqshiftsu:
9647 VShiftOpc = ARMISD::VQSHLsu; break;
9648 case Intrinsic::arm_neon_vqshiftns:
9649 VShiftOpc = ARMISD::VQSHRNs; break;
9650 case Intrinsic::arm_neon_vqshiftnu:
9651 VShiftOpc = ARMISD::VQSHRNu; break;
9652 case Intrinsic::arm_neon_vqshiftnsu:
9653 VShiftOpc = ARMISD::VQSHRNsu; break;
9654 case Intrinsic::arm_neon_vqrshiftns:
9655 VShiftOpc = ARMISD::VQRSHRNs; break;
9656 case Intrinsic::arm_neon_vqrshiftnu:
9657 VShiftOpc = ARMISD::VQRSHRNu; break;
9658 case Intrinsic::arm_neon_vqrshiftnsu:
9659 VShiftOpc = ARMISD::VQRSHRNsu; break;
9663 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9664 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9667 case Intrinsic::arm_neon_vshiftins: {
9668 EVT VT = N->getOperand(1).getValueType();
9670 unsigned VShiftOpc = 0;
9672 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9673 VShiftOpc = ARMISD::VSLI;
9674 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9675 VShiftOpc = ARMISD::VSRI;
9677 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9681 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9682 N->getOperand(1), N->getOperand(2),
9683 DAG.getConstant(Cnt, dl, MVT::i32));
9686 case Intrinsic::arm_neon_vqrshifts:
9687 case Intrinsic::arm_neon_vqrshiftu:
9688 // No immediate versions of these to check for.
9695 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9696 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9697 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9698 /// vector element shift counts are generally not legal, and it is hard to see
9699 /// their values after they get legalized to loads from a constant pool.
9700 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9701 const ARMSubtarget *ST) {
9702 EVT VT = N->getValueType(0);
9703 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9704 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9705 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9706 SDValue N1 = N->getOperand(1);
9707 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9708 SDValue N0 = N->getOperand(0);
9709 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9710 DAG.MaskedValueIsZero(N0.getOperand(0),
9711 APInt::getHighBitsSet(32, 16)))
9712 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9716 // Nothing to be done for scalar shifts.
9717 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9718 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9721 assert(ST->hasNEON() && "unexpected vector shift");
9724 switch (N->getOpcode()) {
9725 default: llvm_unreachable("unexpected shift opcode");
9728 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9730 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9731 DAG.getConstant(Cnt, dl, MVT::i32));
9737 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9738 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9739 ARMISD::VSHRs : ARMISD::VSHRu);
9741 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9742 DAG.getConstant(Cnt, dl, MVT::i32));
9748 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9749 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9750 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9751 const ARMSubtarget *ST) {
9752 SDValue N0 = N->getOperand(0);
9754 // Check for sign- and zero-extensions of vector extract operations of 8-
9755 // and 16-bit vector elements. NEON supports these directly. They are
9756 // handled during DAG combining because type legalization will promote them
9757 // to 32-bit types and it is messy to recognize the operations after that.
9758 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9759 SDValue Vec = N0.getOperand(0);
9760 SDValue Lane = N0.getOperand(1);
9761 EVT VT = N->getValueType(0);
9762 EVT EltVT = N0.getValueType();
9763 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9765 if (VT == MVT::i32 &&
9766 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9767 TLI.isTypeLegal(Vec.getValueType()) &&
9768 isa<ConstantSDNode>(Lane)) {
9771 switch (N->getOpcode()) {
9772 default: llvm_unreachable("unexpected opcode");
9773 case ISD::SIGN_EXTEND:
9774 Opc = ARMISD::VGETLANEs;
9776 case ISD::ZERO_EXTEND:
9777 case ISD::ANY_EXTEND:
9778 Opc = ARMISD::VGETLANEu;
9781 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9788 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9789 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9790 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9791 const ARMSubtarget *ST) {
9792 // If the target supports NEON, try to use vmax/vmin instructions for f32
9793 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9794 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9795 // a NaN; only do the transformation when it matches that behavior.
9797 // For now only do this when using NEON for FP operations; if using VFP, it
9798 // is not obvious that the benefit outweighs the cost of switching to the
9800 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9801 N->getValueType(0) != MVT::f32)
9804 SDValue CondLHS = N->getOperand(0);
9805 SDValue CondRHS = N->getOperand(1);
9806 SDValue LHS = N->getOperand(2);
9807 SDValue RHS = N->getOperand(3);
9808 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9810 unsigned Opcode = 0;
9812 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9813 IsReversed = false; // x CC y ? x : y
9814 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9815 IsReversed = true ; // x CC y ? y : x
9829 // If LHS is NaN, an ordered comparison will be false and the result will
9830 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9831 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9832 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9833 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9835 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9836 // will return -0, so vmin can only be used for unsafe math or if one of
9837 // the operands is known to be nonzero.
9838 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9839 !DAG.getTarget().Options.UnsafeFPMath &&
9840 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9842 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9851 // If LHS is NaN, an ordered comparison will be false and the result will
9852 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9853 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9854 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9855 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9857 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9858 // will return +0, so vmax can only be used for unsafe math or if one of
9859 // the operands is known to be nonzero.
9860 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9861 !DAG.getTarget().Options.UnsafeFPMath &&
9862 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9864 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9870 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9873 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9875 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9876 SDValue Cmp = N->getOperand(4);
9877 if (Cmp.getOpcode() != ARMISD::CMPZ)
9878 // Only looking at EQ and NE cases.
9881 EVT VT = N->getValueType(0);
9883 SDValue LHS = Cmp.getOperand(0);
9884 SDValue RHS = Cmp.getOperand(1);
9885 SDValue FalseVal = N->getOperand(0);
9886 SDValue TrueVal = N->getOperand(1);
9887 SDValue ARMcc = N->getOperand(2);
9888 ARMCC::CondCodes CC =
9889 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9907 /// FIXME: Turn this into a target neutral optimization?
9909 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9910 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9911 N->getOperand(3), Cmp);
9912 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9914 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9915 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9916 N->getOperand(3), NewCmp);
9919 if (Res.getNode()) {
9920 APInt KnownZero, KnownOne;
9921 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9922 // Capture demanded bits information that would be otherwise lost.
9923 if (KnownZero == 0xfffffffe)
9924 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9925 DAG.getValueType(MVT::i1));
9926 else if (KnownZero == 0xffffff00)
9927 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9928 DAG.getValueType(MVT::i8));
9929 else if (KnownZero == 0xffff0000)
9930 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9931 DAG.getValueType(MVT::i16));
9937 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9938 DAGCombinerInfo &DCI) const {
9939 switch (N->getOpcode()) {
9941 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9942 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9943 case ISD::SUB: return PerformSUBCombine(N, DCI);
9944 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9945 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9946 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9947 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9948 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9949 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9950 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9951 case ISD::STORE: return PerformSTORECombine(N, DCI);
9952 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9953 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9954 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9955 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9956 case ISD::FP_TO_SINT:
9957 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9958 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9959 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9962 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9963 case ISD::SIGN_EXTEND:
9964 case ISD::ZERO_EXTEND:
9965 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9966 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9967 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9968 case ISD::LOAD: return PerformLOADCombine(N, DCI);
9969 case ARMISD::VLD2DUP:
9970 case ARMISD::VLD3DUP:
9971 case ARMISD::VLD4DUP:
9972 return PerformVLDCombine(N, DCI);
9973 case ARMISD::BUILD_VECTOR:
9974 return PerformARMBUILD_VECTORCombine(N, DCI);
9975 case ISD::INTRINSIC_VOID:
9976 case ISD::INTRINSIC_W_CHAIN:
9977 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9978 case Intrinsic::arm_neon_vld1:
9979 case Intrinsic::arm_neon_vld2:
9980 case Intrinsic::arm_neon_vld3:
9981 case Intrinsic::arm_neon_vld4:
9982 case Intrinsic::arm_neon_vld2lane:
9983 case Intrinsic::arm_neon_vld3lane:
9984 case Intrinsic::arm_neon_vld4lane:
9985 case Intrinsic::arm_neon_vst1:
9986 case Intrinsic::arm_neon_vst2:
9987 case Intrinsic::arm_neon_vst3:
9988 case Intrinsic::arm_neon_vst4:
9989 case Intrinsic::arm_neon_vst2lane:
9990 case Intrinsic::arm_neon_vst3lane:
9991 case Intrinsic::arm_neon_vst4lane:
9992 return PerformVLDCombine(N, DCI);
10000 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10002 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10005 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10008 bool *Fast) const {
10009 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10010 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10012 switch (VT.getSimpleVT().SimpleTy) {
10018 // Unaligned access can use (for example) LRDB, LRDH, LDR
10019 if (AllowsUnaligned) {
10021 *Fast = Subtarget->hasV7Ops();
10028 // For any little-endian targets with neon, we can support unaligned ld/st
10029 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10030 // A big-endian target may also explicitly support unaligned accesses
10031 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10041 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10042 unsigned AlignCheck) {
10043 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10044 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10047 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10048 unsigned DstAlign, unsigned SrcAlign,
10049 bool IsMemset, bool ZeroMemset,
10051 MachineFunction &MF) const {
10052 const Function *F = MF.getFunction();
10054 // See if we can use NEON instructions for this...
10055 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10056 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10059 (memOpAlign(SrcAlign, DstAlign, 16) ||
10060 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10062 } else if (Size >= 8 &&
10063 (memOpAlign(SrcAlign, DstAlign, 8) ||
10064 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10070 // Lowering to i32/i16 if the size permits.
10073 else if (Size >= 2)
10076 // Let the target-independent logic figure it out.
10080 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10081 if (Val.getOpcode() != ISD::LOAD)
10084 EVT VT1 = Val.getValueType();
10085 if (!VT1.isSimple() || !VT1.isInteger() ||
10086 !VT2.isSimple() || !VT2.isInteger())
10089 switch (VT1.getSimpleVT().SimpleTy) {
10094 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10101 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10102 EVT VT = ExtVal.getValueType();
10104 if (!isTypeLegal(VT))
10107 // Don't create a loadext if we can fold the extension into a wide/long
10109 // If there's more than one user instruction, the loadext is desirable no
10110 // matter what. There can be two uses by the same instruction.
10111 if (ExtVal->use_empty() ||
10112 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10115 SDNode *U = *ExtVal->use_begin();
10116 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10117 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10123 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10124 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10127 if (!isTypeLegal(EVT::getEVT(Ty1)))
10130 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10132 // Assuming the caller doesn't have a zeroext or signext return parameter,
10133 // truncation all the way down to i1 is valid.
10138 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10142 unsigned Scale = 1;
10143 switch (VT.getSimpleVT().SimpleTy) {
10144 default: return false;
10159 if ((V & (Scale - 1)) != 0)
10162 return V == (V & ((1LL << 5) - 1));
10165 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10166 const ARMSubtarget *Subtarget) {
10167 bool isNeg = false;
10173 switch (VT.getSimpleVT().SimpleTy) {
10174 default: return false;
10179 // + imm12 or - imm8
10181 return V == (V & ((1LL << 8) - 1));
10182 return V == (V & ((1LL << 12) - 1));
10185 // Same as ARM mode. FIXME: NEON?
10186 if (!Subtarget->hasVFP2())
10191 return V == (V & ((1LL << 8) - 1));
10195 /// isLegalAddressImmediate - Return true if the integer value can be used
10196 /// as the offset of the target addressing mode for load / store of the
10198 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10199 const ARMSubtarget *Subtarget) {
10203 if (!VT.isSimple())
10206 if (Subtarget->isThumb1Only())
10207 return isLegalT1AddressImmediate(V, VT);
10208 else if (Subtarget->isThumb2())
10209 return isLegalT2AddressImmediate(V, VT, Subtarget);
10214 switch (VT.getSimpleVT().SimpleTy) {
10215 default: return false;
10220 return V == (V & ((1LL << 12) - 1));
10223 return V == (V & ((1LL << 8) - 1));
10226 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10231 return V == (V & ((1LL << 8) - 1));
10235 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10237 int Scale = AM.Scale;
10241 switch (VT.getSimpleVT().SimpleTy) {
10242 default: return false;
10250 Scale = Scale & ~1;
10251 return Scale == 2 || Scale == 4 || Scale == 8;
10254 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10258 // Note, we allow "void" uses (basically, uses that aren't loads or
10259 // stores), because arm allows folding a scale into many arithmetic
10260 // operations. This should be made more precise and revisited later.
10262 // Allow r << imm, but the imm has to be a multiple of two.
10263 if (Scale & 1) return false;
10264 return isPowerOf2_32(Scale);
10268 /// isLegalAddressingMode - Return true if the addressing mode represented
10269 /// by AM is legal for this target, for a load/store of the specified type.
10270 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10272 unsigned AS) const {
10273 EVT VT = getValueType(Ty, true);
10274 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10277 // Can never fold addr of global into load/store.
10281 switch (AM.Scale) {
10282 case 0: // no scale reg, must be "r+i" or "r", or "i".
10285 if (Subtarget->isThumb1Only())
10289 // ARM doesn't support any R+R*scale+imm addr modes.
10293 if (!VT.isSimple())
10296 if (Subtarget->isThumb2())
10297 return isLegalT2ScaledAddressingMode(AM, VT);
10299 int Scale = AM.Scale;
10300 switch (VT.getSimpleVT().SimpleTy) {
10301 default: return false;
10305 if (Scale < 0) Scale = -Scale;
10309 return isPowerOf2_32(Scale & ~1);
10313 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10318 // Note, we allow "void" uses (basically, uses that aren't loads or
10319 // stores), because arm allows folding a scale into many arithmetic
10320 // operations. This should be made more precise and revisited later.
10322 // Allow r << imm, but the imm has to be a multiple of two.
10323 if (Scale & 1) return false;
10324 return isPowerOf2_32(Scale);
10330 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10331 /// icmp immediate, that is the target has icmp instructions which can compare
10332 /// a register against the immediate without having to materialize the
10333 /// immediate into a register.
10334 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10335 // Thumb2 and ARM modes can use cmn for negative immediates.
10336 if (!Subtarget->isThumb())
10337 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10338 if (Subtarget->isThumb2())
10339 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10340 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10341 return Imm >= 0 && Imm <= 255;
10344 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10345 /// *or sub* immediate, that is the target has add or sub instructions which can
10346 /// add a register with the immediate without having to materialize the
10347 /// immediate into a register.
10348 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10349 // Same encoding for add/sub, just flip the sign.
10350 int64_t AbsImm = std::abs(Imm);
10351 if (!Subtarget->isThumb())
10352 return ARM_AM::getSOImmVal(AbsImm) != -1;
10353 if (Subtarget->isThumb2())
10354 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10355 // Thumb1 only has 8-bit unsigned immediate.
10356 return AbsImm >= 0 && AbsImm <= 255;
10359 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10360 bool isSEXTLoad, SDValue &Base,
10361 SDValue &Offset, bool &isInc,
10362 SelectionDAG &DAG) {
10363 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10366 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10367 // AddressingMode 3
10368 Base = Ptr->getOperand(0);
10369 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10370 int RHSC = (int)RHS->getZExtValue();
10371 if (RHSC < 0 && RHSC > -256) {
10372 assert(Ptr->getOpcode() == ISD::ADD);
10374 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10378 isInc = (Ptr->getOpcode() == ISD::ADD);
10379 Offset = Ptr->getOperand(1);
10381 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10382 // AddressingMode 2
10383 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10384 int RHSC = (int)RHS->getZExtValue();
10385 if (RHSC < 0 && RHSC > -0x1000) {
10386 assert(Ptr->getOpcode() == ISD::ADD);
10388 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10389 Base = Ptr->getOperand(0);
10394 if (Ptr->getOpcode() == ISD::ADD) {
10396 ARM_AM::ShiftOpc ShOpcVal=
10397 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10398 if (ShOpcVal != ARM_AM::no_shift) {
10399 Base = Ptr->getOperand(1);
10400 Offset = Ptr->getOperand(0);
10402 Base = Ptr->getOperand(0);
10403 Offset = Ptr->getOperand(1);
10408 isInc = (Ptr->getOpcode() == ISD::ADD);
10409 Base = Ptr->getOperand(0);
10410 Offset = Ptr->getOperand(1);
10414 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10418 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10419 bool isSEXTLoad, SDValue &Base,
10420 SDValue &Offset, bool &isInc,
10421 SelectionDAG &DAG) {
10422 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10425 Base = Ptr->getOperand(0);
10426 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10427 int RHSC = (int)RHS->getZExtValue();
10428 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10429 assert(Ptr->getOpcode() == ISD::ADD);
10431 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10433 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10434 isInc = Ptr->getOpcode() == ISD::ADD;
10435 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10443 /// getPreIndexedAddressParts - returns true by value, base pointer and
10444 /// offset pointer and addressing mode by reference if the node's address
10445 /// can be legally represented as pre-indexed load / store address.
10447 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10449 ISD::MemIndexedMode &AM,
10450 SelectionDAG &DAG) const {
10451 if (Subtarget->isThumb1Only())
10456 bool isSEXTLoad = false;
10457 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10458 Ptr = LD->getBasePtr();
10459 VT = LD->getMemoryVT();
10460 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10461 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10462 Ptr = ST->getBasePtr();
10463 VT = ST->getMemoryVT();
10468 bool isLegal = false;
10469 if (Subtarget->isThumb2())
10470 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10471 Offset, isInc, DAG);
10473 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10474 Offset, isInc, DAG);
10478 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10482 /// getPostIndexedAddressParts - returns true by value, base pointer and
10483 /// offset pointer and addressing mode by reference if this node can be
10484 /// combined with a load / store to form a post-indexed load / store.
10485 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10488 ISD::MemIndexedMode &AM,
10489 SelectionDAG &DAG) const {
10490 if (Subtarget->isThumb1Only())
10495 bool isSEXTLoad = false;
10496 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10497 VT = LD->getMemoryVT();
10498 Ptr = LD->getBasePtr();
10499 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10500 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10501 VT = ST->getMemoryVT();
10502 Ptr = ST->getBasePtr();
10507 bool isLegal = false;
10508 if (Subtarget->isThumb2())
10509 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10512 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10518 // Swap base ptr and offset to catch more post-index load / store when
10519 // it's legal. In Thumb2 mode, offset must be an immediate.
10520 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10521 !Subtarget->isThumb2())
10522 std::swap(Base, Offset);
10524 // Post-indexed load / store update the base pointer.
10529 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10533 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10536 const SelectionDAG &DAG,
10537 unsigned Depth) const {
10538 unsigned BitWidth = KnownOne.getBitWidth();
10539 KnownZero = KnownOne = APInt(BitWidth, 0);
10540 switch (Op.getOpcode()) {
10546 // These nodes' second result is a boolean
10547 if (Op.getResNo() == 0)
10549 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10551 case ARMISD::CMOV: {
10552 // Bits are known zero/one if known on the LHS and RHS.
10553 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10554 if (KnownZero == 0 && KnownOne == 0) return;
10556 APInt KnownZeroRHS, KnownOneRHS;
10557 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10558 KnownZero &= KnownZeroRHS;
10559 KnownOne &= KnownOneRHS;
10562 case ISD::INTRINSIC_W_CHAIN: {
10563 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10564 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10567 case Intrinsic::arm_ldaex:
10568 case Intrinsic::arm_ldrex: {
10569 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10570 unsigned MemBits = VT.getScalarType().getSizeInBits();
10571 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10579 //===----------------------------------------------------------------------===//
10580 // ARM Inline Assembly Support
10581 //===----------------------------------------------------------------------===//
10583 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10584 // Looking for "rev" which is V6+.
10585 if (!Subtarget->hasV6Ops())
10588 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10589 std::string AsmStr = IA->getAsmString();
10590 SmallVector<StringRef, 4> AsmPieces;
10591 SplitString(AsmStr, AsmPieces, ";\n");
10593 switch (AsmPieces.size()) {
10594 default: return false;
10596 AsmStr = AsmPieces[0];
10598 SplitString(AsmStr, AsmPieces, " \t,");
10601 if (AsmPieces.size() == 3 &&
10602 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10603 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10604 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10605 if (Ty && Ty->getBitWidth() == 32)
10606 return IntrinsicLowering::LowerToByteSwap(CI);
10614 /// getConstraintType - Given a constraint letter, return the type of
10615 /// constraint it is for this target.
10616 ARMTargetLowering::ConstraintType
10617 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10618 if (Constraint.size() == 1) {
10619 switch (Constraint[0]) {
10621 case 'l': return C_RegisterClass;
10622 case 'w': return C_RegisterClass;
10623 case 'h': return C_RegisterClass;
10624 case 'x': return C_RegisterClass;
10625 case 't': return C_RegisterClass;
10626 case 'j': return C_Other; // Constant for movw.
10627 // An address with a single base register. Due to the way we
10628 // currently handle addresses it is the same as an 'r' memory constraint.
10629 case 'Q': return C_Memory;
10631 } else if (Constraint.size() == 2) {
10632 switch (Constraint[0]) {
10634 // All 'U+' constraints are addresses.
10635 case 'U': return C_Memory;
10638 return TargetLowering::getConstraintType(Constraint);
10641 /// Examine constraint type and operand type and determine a weight value.
10642 /// This object must already have been set up with the operand type
10643 /// and the current alternative constraint selected.
10644 TargetLowering::ConstraintWeight
10645 ARMTargetLowering::getSingleConstraintMatchWeight(
10646 AsmOperandInfo &info, const char *constraint) const {
10647 ConstraintWeight weight = CW_Invalid;
10648 Value *CallOperandVal = info.CallOperandVal;
10649 // If we don't have a value, we can't do a match,
10650 // but allow it at the lowest weight.
10651 if (!CallOperandVal)
10653 Type *type = CallOperandVal->getType();
10654 // Look at the constraint type.
10655 switch (*constraint) {
10657 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10660 if (type->isIntegerTy()) {
10661 if (Subtarget->isThumb())
10662 weight = CW_SpecificReg;
10664 weight = CW_Register;
10668 if (type->isFloatingPointTy())
10669 weight = CW_Register;
10675 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10677 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10678 const std::string &Constraint,
10680 if (Constraint.size() == 1) {
10681 // GCC ARM Constraint Letters
10682 switch (Constraint[0]) {
10683 case 'l': // Low regs or general regs.
10684 if (Subtarget->isThumb())
10685 return RCPair(0U, &ARM::tGPRRegClass);
10686 return RCPair(0U, &ARM::GPRRegClass);
10687 case 'h': // High regs or no regs.
10688 if (Subtarget->isThumb())
10689 return RCPair(0U, &ARM::hGPRRegClass);
10692 if (Subtarget->isThumb1Only())
10693 return RCPair(0U, &ARM::tGPRRegClass);
10694 return RCPair(0U, &ARM::GPRRegClass);
10696 if (VT == MVT::Other)
10698 if (VT == MVT::f32)
10699 return RCPair(0U, &ARM::SPRRegClass);
10700 if (VT.getSizeInBits() == 64)
10701 return RCPair(0U, &ARM::DPRRegClass);
10702 if (VT.getSizeInBits() == 128)
10703 return RCPair(0U, &ARM::QPRRegClass);
10706 if (VT == MVT::Other)
10708 if (VT == MVT::f32)
10709 return RCPair(0U, &ARM::SPR_8RegClass);
10710 if (VT.getSizeInBits() == 64)
10711 return RCPair(0U, &ARM::DPR_8RegClass);
10712 if (VT.getSizeInBits() == 128)
10713 return RCPair(0U, &ARM::QPR_8RegClass);
10716 if (VT == MVT::f32)
10717 return RCPair(0U, &ARM::SPRRegClass);
10721 if (StringRef("{cc}").equals_lower(Constraint))
10722 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10724 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10727 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10728 /// vector. If it is invalid, don't add anything to Ops.
10729 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10730 std::string &Constraint,
10731 std::vector<SDValue>&Ops,
10732 SelectionDAG &DAG) const {
10735 // Currently only support length 1 constraints.
10736 if (Constraint.length() != 1) return;
10738 char ConstraintLetter = Constraint[0];
10739 switch (ConstraintLetter) {
10742 case 'I': case 'J': case 'K': case 'L':
10743 case 'M': case 'N': case 'O':
10744 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10748 int64_t CVal64 = C->getSExtValue();
10749 int CVal = (int) CVal64;
10750 // None of these constraints allow values larger than 32 bits. Check
10751 // that the value fits in an int.
10752 if (CVal != CVal64)
10755 switch (ConstraintLetter) {
10757 // Constant suitable for movw, must be between 0 and
10759 if (Subtarget->hasV6T2Ops())
10760 if (CVal >= 0 && CVal <= 65535)
10764 if (Subtarget->isThumb1Only()) {
10765 // This must be a constant between 0 and 255, for ADD
10767 if (CVal >= 0 && CVal <= 255)
10769 } else if (Subtarget->isThumb2()) {
10770 // A constant that can be used as an immediate value in a
10771 // data-processing instruction.
10772 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10775 // A constant that can be used as an immediate value in a
10776 // data-processing instruction.
10777 if (ARM_AM::getSOImmVal(CVal) != -1)
10783 if (Subtarget->isThumb()) { // FIXME thumb2
10784 // This must be a constant between -255 and -1, for negated ADD
10785 // immediates. This can be used in GCC with an "n" modifier that
10786 // prints the negated value, for use with SUB instructions. It is
10787 // not useful otherwise but is implemented for compatibility.
10788 if (CVal >= -255 && CVal <= -1)
10791 // This must be a constant between -4095 and 4095. It is not clear
10792 // what this constraint is intended for. Implemented for
10793 // compatibility with GCC.
10794 if (CVal >= -4095 && CVal <= 4095)
10800 if (Subtarget->isThumb1Only()) {
10801 // A 32-bit value where only one byte has a nonzero value. Exclude
10802 // zero to match GCC. This constraint is used by GCC internally for
10803 // constants that can be loaded with a move/shift combination.
10804 // It is not useful otherwise but is implemented for compatibility.
10805 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10807 } else if (Subtarget->isThumb2()) {
10808 // A constant whose bitwise inverse can be used as an immediate
10809 // value in a data-processing instruction. This can be used in GCC
10810 // with a "B" modifier that prints the inverted value, for use with
10811 // BIC and MVN instructions. It is not useful otherwise but is
10812 // implemented for compatibility.
10813 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10816 // A constant whose bitwise inverse can be used as an immediate
10817 // value in a data-processing instruction. This can be used in GCC
10818 // with a "B" modifier that prints the inverted value, for use with
10819 // BIC and MVN instructions. It is not useful otherwise but is
10820 // implemented for compatibility.
10821 if (ARM_AM::getSOImmVal(~CVal) != -1)
10827 if (Subtarget->isThumb1Only()) {
10828 // This must be a constant between -7 and 7,
10829 // for 3-operand ADD/SUB immediate instructions.
10830 if (CVal >= -7 && CVal < 7)
10832 } else if (Subtarget->isThumb2()) {
10833 // A constant whose negation can be used as an immediate value in a
10834 // data-processing instruction. This can be used in GCC with an "n"
10835 // modifier that prints the negated value, for use with SUB
10836 // instructions. It is not useful otherwise but is implemented for
10838 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10841 // A constant whose negation can be used as an immediate value in a
10842 // data-processing instruction. This can be used in GCC with an "n"
10843 // modifier that prints the negated value, for use with SUB
10844 // instructions. It is not useful otherwise but is implemented for
10846 if (ARM_AM::getSOImmVal(-CVal) != -1)
10852 if (Subtarget->isThumb()) { // FIXME thumb2
10853 // This must be a multiple of 4 between 0 and 1020, for
10854 // ADD sp + immediate.
10855 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10858 // A power of two or a constant between 0 and 32. This is used in
10859 // GCC for the shift amount on shifted register operands, but it is
10860 // useful in general for any shift amounts.
10861 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10867 if (Subtarget->isThumb()) { // FIXME thumb2
10868 // This must be a constant between 0 and 31, for shift amounts.
10869 if (CVal >= 0 && CVal <= 31)
10875 if (Subtarget->isThumb()) { // FIXME thumb2
10876 // This must be a multiple of 4 between -508 and 508, for
10877 // ADD/SUB sp = sp + immediate.
10878 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10883 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
10887 if (Result.getNode()) {
10888 Ops.push_back(Result);
10891 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10894 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10895 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10896 unsigned Opcode = Op->getOpcode();
10897 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10898 "Invalid opcode for Div/Rem lowering");
10899 bool isSigned = (Opcode == ISD::SDIVREM);
10900 EVT VT = Op->getValueType(0);
10901 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10904 switch (VT.getSimpleVT().SimpleTy) {
10905 default: llvm_unreachable("Unexpected request for libcall!");
10906 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10907 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10908 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10909 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10912 SDValue InChain = DAG.getEntryNode();
10914 TargetLowering::ArgListTy Args;
10915 TargetLowering::ArgListEntry Entry;
10916 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10917 EVT ArgVT = Op->getOperand(i).getValueType();
10918 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10919 Entry.Node = Op->getOperand(i);
10921 Entry.isSExt = isSigned;
10922 Entry.isZExt = !isSigned;
10923 Args.push_back(Entry);
10926 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10929 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10932 TargetLowering::CallLoweringInfo CLI(DAG);
10933 CLI.setDebugLoc(dl).setChain(InChain)
10934 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10935 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10937 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10938 return CallInfo.first;
10942 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10943 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10947 SDValue Chain = Op.getOperand(0);
10948 SDValue Size = Op.getOperand(1);
10950 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10951 DAG.getConstant(2, DL, MVT::i32));
10954 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10955 Flag = Chain.getValue(1);
10957 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10958 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10960 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10961 Chain = NewSP.getValue(1);
10963 SDValue Ops[2] = { NewSP, Chain };
10964 return DAG.getMergeValues(Ops, DL);
10967 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10968 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10969 "Unexpected type for custom-lowering FP_EXTEND");
10972 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10974 SDValue SrcVal = Op.getOperand(0);
10975 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10976 /*isSigned*/ false, SDLoc(Op)).first;
10979 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10980 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10981 Subtarget->isFPOnlySP() &&
10982 "Unexpected type for custom-lowering FP_ROUND");
10985 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10987 SDValue SrcVal = Op.getOperand(0);
10988 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10989 /*isSigned*/ false, SDLoc(Op)).first;
10993 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10994 // The ARM target isn't yet aware of offsets.
10998 bool ARM::isBitFieldInvertedMask(unsigned v) {
10999 if (v == 0xffffffff)
11002 // there can be 1's on either or both "outsides", all the "inside"
11003 // bits must be 0's
11004 return isShiftedMask_32(~v);
11007 /// isFPImmLegal - Returns true if the target can instruction select the
11008 /// specified FP immediate natively. If false, the legalizer will
11009 /// materialize the FP immediate as a load from a constant pool.
11010 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11011 if (!Subtarget->hasVFP3())
11013 if (VT == MVT::f32)
11014 return ARM_AM::getFP32Imm(Imm) != -1;
11015 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11016 return ARM_AM::getFP64Imm(Imm) != -1;
11020 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11021 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11022 /// specified in the intrinsic calls.
11023 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11025 unsigned Intrinsic) const {
11026 switch (Intrinsic) {
11027 case Intrinsic::arm_neon_vld1:
11028 case Intrinsic::arm_neon_vld2:
11029 case Intrinsic::arm_neon_vld3:
11030 case Intrinsic::arm_neon_vld4:
11031 case Intrinsic::arm_neon_vld2lane:
11032 case Intrinsic::arm_neon_vld3lane:
11033 case Intrinsic::arm_neon_vld4lane: {
11034 Info.opc = ISD::INTRINSIC_W_CHAIN;
11035 // Conservatively set memVT to the entire set of vectors loaded.
11036 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11037 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11038 Info.ptrVal = I.getArgOperand(0);
11040 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11041 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11042 Info.vol = false; // volatile loads with NEON intrinsics not supported
11043 Info.readMem = true;
11044 Info.writeMem = false;
11047 case Intrinsic::arm_neon_vst1:
11048 case Intrinsic::arm_neon_vst2:
11049 case Intrinsic::arm_neon_vst3:
11050 case Intrinsic::arm_neon_vst4:
11051 case Intrinsic::arm_neon_vst2lane:
11052 case Intrinsic::arm_neon_vst3lane:
11053 case Intrinsic::arm_neon_vst4lane: {
11054 Info.opc = ISD::INTRINSIC_VOID;
11055 // Conservatively set memVT to the entire set of vectors stored.
11056 unsigned NumElts = 0;
11057 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11058 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11059 if (!ArgTy->isVectorTy())
11061 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11063 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11064 Info.ptrVal = I.getArgOperand(0);
11066 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11067 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11068 Info.vol = false; // volatile stores with NEON intrinsics not supported
11069 Info.readMem = false;
11070 Info.writeMem = true;
11073 case Intrinsic::arm_ldaex:
11074 case Intrinsic::arm_ldrex: {
11075 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11076 Info.opc = ISD::INTRINSIC_W_CHAIN;
11077 Info.memVT = MVT::getVT(PtrTy->getElementType());
11078 Info.ptrVal = I.getArgOperand(0);
11080 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11082 Info.readMem = true;
11083 Info.writeMem = false;
11086 case Intrinsic::arm_stlex:
11087 case Intrinsic::arm_strex: {
11088 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11089 Info.opc = ISD::INTRINSIC_W_CHAIN;
11090 Info.memVT = MVT::getVT(PtrTy->getElementType());
11091 Info.ptrVal = I.getArgOperand(1);
11093 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11095 Info.readMem = false;
11096 Info.writeMem = true;
11099 case Intrinsic::arm_stlexd:
11100 case Intrinsic::arm_strexd: {
11101 Info.opc = ISD::INTRINSIC_W_CHAIN;
11102 Info.memVT = MVT::i64;
11103 Info.ptrVal = I.getArgOperand(2);
11107 Info.readMem = false;
11108 Info.writeMem = true;
11111 case Intrinsic::arm_ldaexd:
11112 case Intrinsic::arm_ldrexd: {
11113 Info.opc = ISD::INTRINSIC_W_CHAIN;
11114 Info.memVT = MVT::i64;
11115 Info.ptrVal = I.getArgOperand(0);
11119 Info.readMem = true;
11120 Info.writeMem = false;
11130 /// \brief Returns true if it is beneficial to convert a load of a constant
11131 /// to just the constant itself.
11132 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11134 assert(Ty->isIntegerTy());
11136 unsigned Bits = Ty->getPrimitiveSizeInBits();
11137 if (Bits == 0 || Bits > 32)
11142 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11144 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11145 ARM_MB::MemBOpt Domain) const {
11146 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11148 // First, if the target has no DMB, see what fallback we can use.
11149 if (!Subtarget->hasDataBarrier()) {
11150 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11151 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11153 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11154 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11155 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11156 Builder.getInt32(0), Builder.getInt32(7),
11157 Builder.getInt32(10), Builder.getInt32(5)};
11158 return Builder.CreateCall(MCR, args);
11160 // Instead of using barriers, atomic accesses on these subtargets use
11162 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11165 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11166 // Only a full system barrier exists in the M-class architectures.
11167 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11168 Constant *CDomain = Builder.getInt32(Domain);
11169 return Builder.CreateCall(DMB, CDomain);
11173 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11174 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11175 AtomicOrdering Ord, bool IsStore,
11176 bool IsLoad) const {
11177 if (!getInsertFencesForAtomic())
11183 llvm_unreachable("Invalid fence: unordered/non-atomic");
11186 return nullptr; // Nothing to do
11187 case SequentiallyConsistent:
11189 return nullptr; // Nothing to do
11192 case AcquireRelease:
11193 if (Subtarget->isSwift())
11194 return makeDMB(Builder, ARM_MB::ISHST);
11195 // FIXME: add a comment with a link to documentation justifying this.
11197 return makeDMB(Builder, ARM_MB::ISH);
11199 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11202 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11203 AtomicOrdering Ord, bool IsStore,
11204 bool IsLoad) const {
11205 if (!getInsertFencesForAtomic())
11211 llvm_unreachable("Invalid fence: unordered/not-atomic");
11214 return nullptr; // Nothing to do
11216 case AcquireRelease:
11217 case SequentiallyConsistent:
11218 return makeDMB(Builder, ARM_MB::ISH);
11220 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11223 // Loads and stores less than 64-bits are already atomic; ones above that
11224 // are doomed anyway, so defer to the default libcall and blame the OS when
11225 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11226 // anything for those.
11227 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11228 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11229 return (Size == 64) && !Subtarget->isMClass();
11232 // Loads and stores less than 64-bits are already atomic; ones above that
11233 // are doomed anyway, so defer to the default libcall and blame the OS when
11234 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11235 // anything for those.
11236 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11237 // guarantee, see DDI0406C ARM architecture reference manual,
11238 // sections A8.8.72-74 LDRD)
11239 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11240 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11241 return (Size == 64) && !Subtarget->isMClass();
11244 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11245 // and up to 64 bits on the non-M profiles
11246 TargetLoweringBase::AtomicRMWExpansionKind
11247 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11248 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11249 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11250 ? AtomicRMWExpansionKind::LLSC
11251 : AtomicRMWExpansionKind::None;
11254 // This has so far only been implemented for MachO.
11255 bool ARMTargetLowering::useLoadStackGuardNode() const {
11256 return Subtarget->isTargetMachO();
11259 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11260 unsigned &Cost) const {
11261 // If we do not have NEON, vector types are not natively supported.
11262 if (!Subtarget->hasNEON())
11265 // Floating point values and vector values map to the same register file.
11266 // Therefore, althought we could do a store extract of a vector type, this is
11267 // better to leave at float as we have more freedom in the addressing mode for
11269 if (VectorTy->isFPOrFPVectorTy())
11272 // If the index is unknown at compile time, this is very expensive to lower
11273 // and it is not possible to combine the store with the extract.
11274 if (!isa<ConstantInt>(Idx))
11277 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11278 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11279 // We can do a store + vector extract on any vector that fits perfectly in a D
11281 if (BitWidth == 64 || BitWidth == 128) {
11288 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11289 AtomicOrdering Ord) const {
11290 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11291 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11292 bool IsAcquire = isAtLeastAcquire(Ord);
11294 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11295 // intrinsic must return {i32, i32} and we have to recombine them into a
11296 // single i64 here.
11297 if (ValTy->getPrimitiveSizeInBits() == 64) {
11298 Intrinsic::ID Int =
11299 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11300 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11302 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11303 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11305 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11306 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11307 if (!Subtarget->isLittle())
11308 std::swap (Lo, Hi);
11309 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11310 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11311 return Builder.CreateOr(
11312 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11315 Type *Tys[] = { Addr->getType() };
11316 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11317 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11319 return Builder.CreateTruncOrBitCast(
11320 Builder.CreateCall(Ldrex, Addr),
11321 cast<PointerType>(Addr->getType())->getElementType());
11324 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11326 AtomicOrdering Ord) const {
11327 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11328 bool IsRelease = isAtLeastRelease(Ord);
11330 // Since the intrinsics must have legal type, the i64 intrinsics take two
11331 // parameters: "i32, i32". We must marshal Val into the appropriate form
11332 // before the call.
11333 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11334 Intrinsic::ID Int =
11335 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11336 Function *Strex = Intrinsic::getDeclaration(M, Int);
11337 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11339 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11340 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11341 if (!Subtarget->isLittle())
11342 std::swap (Lo, Hi);
11343 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11344 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11347 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11348 Type *Tys[] = { Addr->getType() };
11349 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11351 return Builder.CreateCall(
11352 Strex, {Builder.CreateZExtOrBitCast(
11353 Val, Strex->getFunctionType()->getParamType(0)),
11365 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11366 uint64_t &Members) {
11367 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11368 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11369 uint64_t SubMembers = 0;
11370 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11372 Members += SubMembers;
11374 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11375 uint64_t SubMembers = 0;
11376 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11378 Members += SubMembers * AT->getNumElements();
11379 } else if (Ty->isFloatTy()) {
11380 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11384 } else if (Ty->isDoubleTy()) {
11385 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11389 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11396 return VT->getBitWidth() == 64;
11398 return VT->getBitWidth() == 128;
11400 switch (VT->getBitWidth()) {
11413 return (Members > 0 && Members <= 4);
11416 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11417 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11418 /// passing according to AAPCS rules.
11419 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11420 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11421 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11422 CallingConv::ARM_AAPCS_VFP)
11425 HABaseType Base = HA_UNKNOWN;
11426 uint64_t Members = 0;
11427 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11428 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11430 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11431 return IsHA || IsIntArray;